Search code examples
jquerywordpressmenuclick

jQuery on click on a child element add class to a non-direct parent


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.


EDIT (SOLUTION) : I found a solution to my demand + to an additionnal issue (who was that I needed to remove the class if I click elsewhere on the page, something that I could not achieve with only a function toggleClass).

jQuery(document).ready(function() {
   jQuery('.has-children').on('click', function(event){  
       jQuery('.header-jr').toggleClass('br-top-only');    
   });});

jQuery(document).click(function(e) {                    
   if(!jQuery(e.target).hasClass('has-children') )
   {
       jQuery('.header-jr').removeClass('br-top-only');               
   }
});

It might not be optimal at all but I am not a jQuery pro and it fit my need.


Solution

  • After the page load (i.e. by clicking a button) you need to use event delegation by using jquery , .on()

    Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

    Try with toggleClass like

    jQuery(document).ready(function() {
       jQuery('.has-children').on('click', function(event){  
           jQuery('.header-jr').toggleClass('br-top-only');    
       });});
    

    If you want to toggle 2 classes br-top-only and other_class then use like

    jQuery(document).ready(function() {
       jQuery('.has-children').on('click', function(event){  
           jQuery('.header-jr').toggleClass('br-top-only other_class');    
       });});