简体   繁体   中英

Event listener for A tag to close overlay menu not working

I have an overlay menu that I need to shut when clicking on the links. I have some event listeners but it doesn't work on the links. The menu event used on the burger icon works, the menuItems is for the links that doesn't work. I need it to also work with Pjax link

I have tried target the a tags like menuItems = document.querySelectorAll('.__overlay_nav_content_list_item a'); but it does not work.

 (function($) { "use strict"; var app = function() { var body = undefined; var menu = undefined; var menuItems = undefined; var init = function init() { body = document.querySelector('body'); menu = document.querySelector('.burger_menu_icon'); menuItems = document.querySelectorAll('.__overlay_nav_content_list_item'); applyListeners(); }; var applyListeners = function applyListeners() { menu.addEventListener('click', function() { return toggleClass(body, '__overlay_nav-active'); }); menuItems.addEventListener('click', function() { return toggleClass(body, '__overlay_nav-active'); }); }; var toggleClass = function toggleClass(element, stringClass) { if (element.classList.contains(stringClass)) element.classList.remove(stringClass); else element.classList.add(stringClass); }; init(); }(); })(jQuery); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Have you checked event bubbling? If menuItems are descendants of menu, clicking the menu items will trigger menuItems.addEventListener('click', function() { and hence toggle the class, then the event will bubble up to menu and trigger menu.addEventListener('click', function() { , removing the class you just added. So the end result is that it looks like nothing changed.

If that is the issue, only use the click event on menu , or stop the bubbling up of the event of the menuItems by using event.stopPropagation() .

Although i would prefer only using the click event of the menu, first try: Keep in midn that querySelectorAll() returns a nodeList, so it's an arraylike object containing all the links, not a single link.

Array.from( menuItems ).forEach(function( menuItem ) {
  menuItem.addEventListener('click', function( event ) { // add event here so you have access to it!
    event.stopPropagation(); // call stopPropagation() first
    return toggleClass(body, '__overlay_nav-active'); // Once you return, the function stops.
  });
});

so we know that this is the problem or not. Do not forget to add event as the parameter for the event handler function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM