I am using the code below to add a class to my menu section when I hover an item on my menu :
<script>
jQuery(document).ready(function() {
jQuery('.has-children').hover(function(){
jQuery('.header-jr').addClass('br-top-only');
},function(){
jQuery('.header-jr').removeClass('br-top-only');
});
});
</script>
It works great but now I need to transform this function in a function that add/remove the class only when I click (not hover) on an item. I thought the following function would work, but it did not (nothing happend and no error in consol).
<script>
jQuery(document).ready(function() {
jQuery('.has-children').click(function(){
jQuery('.header-jr').addClass('br-top-only');
},function(){
jQuery('.header-jr').removeClass('br-top-only');
});
});
</script>
Can someone help me with this. I must confess, I have almost 0 knowledge in jQuery/JS so if you could give me a simple solution that would help me a lot.
PS1 : .has-children is my CHILD and .header-jr is my PARENT.
PS2 : the child ".has-children" is not directly below the parent ".header-jr" in my code, I have like 5/6 div between so I think that I can’t use "parent" in jQuery.
2
Answers
You can use
toggleClass
like:If you have multiple
header
andhas child
:If you have multiple level of
divs
you need to useclosest
:After the page load (i.e. by clicking a button) you need to use event delegation by using jquery ,
.on()
Try with toggleClass like
If you want to toggle 2 classes br-top-only and other_class then use like