0

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();
});
paddyfields
  • 1,466
  • 2
  • 15
  • 25

1 Answers1

1

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");
      });

    }
  });
});
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Hi. Thanks but I've read that the screen.width doesn't give a true indication of screensize: http://stackoverflow.com/questions/19291873/window-width-not-the-same-as-media-query – paddyfields May 14 '17 at 14:44
  • 1
    @paddyfields As I mentioned in my answer, you need to differentiate between "screen" and "browser" width. There is no discrepancy in getting the `screen.wdith`, which returns the screen resolution size. When it comes to the browser width, `window.innerWidth` (as I mention in my answer) is the way to get the usable space within the browser window. This is different than `window.width`. – Scott Marcus May 15 '17 at 01:35