As I delve into the world of Javascript, I find myself grasping the concepts bit by bit. However, there's one thing that's been puzzling me, something so basic that I can't seem to find a clear answer on.
My challenge involves a sidebar with three small drop-down menus, each structured like this:
<ul>
<li>LEVEL 1
<button class="sidebtn u1btn">
<span class="material-icons-round">expand_more</span></button>
</li>
<ul class="u1">
<li><a href="lessons?page=u1">the Weather</a></li>
<li><a href="lessons?page=u2">Emotions</a></li>
<li><a href="lessons?page=u3">the Family</a></li>
<li><a href="lessons?page=u4">Food</a></li>
</ul>
</ul>
My goal is to have the arrow (the span element) flip when clicked. Initially, I tried the following solution:
$('.sidebtn').click(function () {
$('div.sidebar button.sidebtn span.material-icons-round').toggleClass('flip');
});
However, this caused all three buttons with the .sidebtn class to flip, instead of just the one that was clicked. How can I target only the specific element that triggered the action, along with its child element (the span)?
I attempted to learn more about Javascript, but most of what I found was too advanced for my current knowledge level. I came across mentions of "event.target" but I'm unsure if that's the right approach. I tried the following without success:
function flipbtn() {
event.target.firstChild.toggleClass('flip');
(I added onclick="flipbtn()" in the HTML.) My rationale was to toggle the "flip" class on the first child of the element that initiated the function, but I received an error stating "event.target.firstChild.toggleClass is not a function". I also experimented with:
const sidebtn = document.querySelectorAll('.sidebtn');
function flipbtn() {
$(sidebtn).firstChild.toggleClass('flip');
}
However, the browser indicated that "$(....).firstChild is undefined". I also tried using "forEach" at one point, but that didn't yield the desired results, possibly due to incorrect implementation.
Understanding why these approaches failed would be enlightening, as I feel confident in my understanding of the objective and my logic behind the methods, even though they haven't worked. Nonetheless, any guidance on the correct approach would be immensely appreciated as I'm currently at a standstill.
Additionally, I aim to have each button open its respective drop-down menu. While I currently have a working solution by individually targeting each menu, I believe there must be a more efficient method. My current code for this task is:
$('.u1btn').click(function () {
$('ul ul.u1').toggleClass('show');
});
$('.u2btn').click(function () {
$('ul ul.u2').toggleClass('show');
});
$('.u3btn').click(function () {
$('ul ul.u3').toggleClass('show');
});
There has to be a simpler way to achieve this. I could replicate the same strategy for the flip effect, but I'm confident that there's a more elegant solution that I'm overlooking. Thank you tremendously for your assistance.