When I hover over the parent links in my menu the class “toggle-active” is added to a span tag so the arrow image is changed. I also want this class to be added to the span tag when I’m hovering over the child links of the parent link inside the .sub-menu container, but I cannot get it to work. Here is the structure of the menu with the jQuery I’m using::
jQuery(".sub-menu").hide();
jQuery("#gallery-nav").find("li").each(function() {
if (jQuery(this).find("ul").length > 0) {
jQuery("<span class=\"gallery-toggle-button\">").appendTo(jQuery(this).children(":first"));
jQuery("#gallery-nav li a").hover(function(){
jQuery(this).children(".gallery-toggle-button").addClass("toggle-active");
}, function () {
jQuery(this).children(".gallery-toggle-button").removeClass("toggle-active");
});
jQuery("#gallery-nav li a").hover(function(){
jQuery(this).next("ul").slideDown('fast');
});
jQuery("#gallery-nav li ul").hover(function(){
jQuery(this).slideDown('fast');
}, function () {
jQuery(this).slideUp('fast');
});
jQuery("#gallery-nav li ul").hover(this).prev(function(){
jQuery("#gallery-nav li a").children(".gallery-toggle-button").addClass("toggle-active");
}, function () {
jQuery("#gallery-nav li a").children(".gallery-toggle-button").removeClass("toggle-active");
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a href="#">Link 1 <span class="toggle-active"></span></a>
<ul class="sub-menu">
<li><a href="#">Sub link 1</a></li>
</ul>
</li>
</ul>
I see a few problems.
has that dash so it doesn’t match this ul here
Next, Javascript closures are tricky. In this bit of code here, “this” stops meaning the “li” and starts meaning the element you matched on, which is the “a”.
In other words, you should do it this way
Finally, I’d just do the whole thing thusly.
Edited
Now it adds the classes and spans. ghostpool, “find” targets children, so it only shows the correct sub navigation. Copy and paste that HTML and try it for yourself.