Mobile menu, problem with event delegation

Asked

Viewed 33 times

0

I am creating a desktop/mobile menu that will be replicated a few times on the page, however my code presents a bug that when clicking 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 class "active-menu" has only one visibility:Hidden; to open and close the menu, the script made can delegate and identify which button is clicking, 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 on this line, where I have tried in some ways to turn this ". menu-Section" into a target delegate, but without success

$('.menu-section').removeClass('active-menu');
  • Knows the object this javascript?

  • was, manage to resolve yesterday, just did not publish, I will post the answer

1 answer

0


Manage to solve the problem by changing the html hierarchy, leaving the button inside ul and using this method

The script went 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');
   }  });
  • 1

    Also read about the function toggleClass

  • I actually mistook the method for slidetoggle rsrsrs

  • Toggle class Download my layout when returning to desktop version

  • 1

    So there’s something else wrong with your layout/script.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.