简体   繁体   中英

Javascript Menu toggle with Media Queries

How do I remove an event listener and class from an element in relation to a media query. I have been fiddling around with this, but nothing seems to work. It works fine on moblie, but when I re-size the screen to become larger the 'menu-show' class is still there.

How would I use this with removeEventListener , it did not seem to work for me.

function showMobileOptions(x) {
  if (x.matches) { 
      filters.forEach(filter => filter.addEventListener('click', function(){
        filter.querySelector('.menu-list').classList.toggle("menu-show");
        filter.querySelector('.menu-list').classList.toggle("toggle-close");
      }))
    } else {
      //remove event listener + '.menu-show' from all items
     filters.forEach(filter, function(){
      filter.querySelector('.menu-list').classList.remove("menu-show");
      filter.querySelector('.menu-list').classList.remove("toggle-close");
  });
  }
}

const x = window.matchMedia("(max-width: 768px)")
showMobileOptions(x)
x.addListener(showMobileOptions)

Use it like this

filter.removeEventListener('click');

Best practice is to create a function for what you do when click fire, and then use the remove

filter.removeEventListener('click',myClickFunction);

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