Search code examples
javascriptjquerymodernizr

Modernizr media query triggering inconsistently


I'm trying to have my script trigger only when the screen size is above a specific size (800px), not just on load, but on screen resize.

I've put it inside a Modernizr mq script, but it's triggering inconsistently. Sometimes it will trigger my script at a small screen size.. sometimes at large.. sometimes not at all. Which leads me to believe that I've completely screwed it up!

Can anyone point me in the right direction?

$(function() {
  $(window).resize(function(){
    if (Modernizr.mq('(min-width: 800px)')) {

      // script to trigger
      $('.dropdown').on('mouseenter mouseleave click tap', function() {
        $(this).toggleClass("open");
      });

    }
  }).resize();
});

Solution

  • Could be because you are triggering the resize event from the resize event, which causes an infinite looping of event triggering.

    Also, why not just test the screen size directly?

    $(function() {
      $(window).resize(function(){
    
        // Use this for browser width: if(window.innerWidth >= 800)
        if (screen.width >= 800) {
    
          // script to trigger
          $('.dropdown').on('mouseenter mouseleave click tap', function() {
            $(this).toggleClass("open");
          });
    
        }
      });
    });