Mobile menu, issue with event delegation

0

I'm creating a desktop / mobile menu that will be replicated a few times on the page, however my code has a bug that when you click open one ends up opening all. Follow the code

<div class="nav-section">
    <div class="menu-button-section">Mobile Menu</div>

    <ul class="menu-section active-menu">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li> 
    </ul>
  </div>
The active-menu class has only visibility: hidden; to open and close the menu, the script can delegate and identify which button it is clicking on , however it does not identify which menu is changing the class since this html will be replicated a few times

$(document).on('click', '.menu-button-section', function () {
 if( $('.menu-section').hasClass('active-menu')){
    $('.menu-section').removeClass('active-menu');
  } else {
     $('.menu-section').addClass('active-menu');
  }   });

The bug happens in this line, where I tried in some ways to turn this ".menu-section" into a delegated target, but without success

$('.menu-section').removeClass('active-menu');
    
asked by anonymous 20.08.2018 / 07:41

1 answer

0

To solve the problem by changing the html hierarchy, leaving the button inside the ul and using this

The script looks like this:

$(document).on('click', '.menu-button', function () {
 if( $(this).children('.menu').hasClass('active-menu')){
     $(this).children('.menu').removeClass('active-menu');
   } else {
     $(this).children('.menu').addClass('active-menu');
   }  });
    
20.08.2018 / 16:03