I need to add a class to an li
on hover but remove the same class from all other li
s in the list (this is for a nav).
The code I have so far is:
jQuery(".navcontent").on('mouseenter', 'li', function() {
if (jQuery('.childmenu', this)) {
jQuery('.childmenu', this).addClass("child-active");
} else {
jQuery('.navcontent li .childmenu').removeClass("child-active");
}
});
I can't quite work out what I need to do...
Any help would be much appreciated.
I need to add a class to an li
on hover but remove the same class from all other li
s in the list (this is for a nav).
The code I have so far is:
jQuery(".navcontent").on('mouseenter', 'li', function() {
if (jQuery('.childmenu', this)) {
jQuery('.childmenu', this).addClass("child-active");
} else {
jQuery('.navcontent li .childmenu').removeClass("child-active");
}
});
I can't quite work out what I need to do...
Any help would be much appreciated.
Share Improve this question edited Jul 24, 2015 at 8:54 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jul 24, 2015 at 8:49 user3181912user3181912 951 silver badge7 bronze badges 1- 2 Kindly post your HTML structure – user1608841 Commented Jul 24, 2015 at 8:51
5 Answers
Reset to default 3You have alternative ways to do that:
- first remove class of all the elements and add one you want:
jQuery(".navcontent li").on('mouseenter', function() { jQuery('.childmenu').removeClass("child-active"); jQuery('.childmenu', this).addClass("child-active"); });
- if they are siblings, you can use
siblings
:
jQuery(".navcontent li").on('mouseenter', function() { jQuery('.childmenu', this).addClass("child-active") .siblings('.childmenu').removeClass("child-active"); });
Please check the code below
jQuery(".navcontent li").on('mouseenter', function(event) {
jQuery('.navcontent li').removeClass("child-active");
jQuery(this).addClass("child-active");
});
.child-active {
color: red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul class="navcontent">
<li>Links</li>
<li>Links</li>
<li>Links</li>
<li>Links</li>
<li>Links</li>
</ul>
jQuery(".navcontent li").on('mouseenter', function(event) {
jQuery('.navcontent li .childmenu').removeClass("child-active");
jQuery(event.target).addClass("child-active");
});
jQuery(".navcontent li").on('mouseenter', function() {
jQuery(".navcontent li").removeClass("child-active");
jQuery(this).addClass("child-active");
});
jQuery(".navcontent li").on('mouseover', function() {
jQuery(".navcontent li .childmenu").removeClass('child-active');
jQuery(this).addClass('child-active');
});
Use above code