Search code examples
jqueryif-statementviewport

if statements - $(window).width() not working so well in Chrome and IE


Good Day

I want to execute 2 statements based on the window width or Viewport size: Here is my code:

var w = $(window).width();

if (w > 767){run myFunc()};

if (w < 767){run myFunc()}; //But this function has different CSS Values

The problem:

in Chrome and IE (not FF), only the second if statement is executed, doesn't matter that the viewport size is...

Why is that?

Thanks


Solution

  • I think you forgot to wrap it inside an resize event-handler...

    Works like a charm for me:

    var myFunc = function(arg){
        console.log(arg);
    };
    
    $(window).resize(function(){
        var w = $(window).width();
    
        if (w > 767) myFunc(1);
        if (w < 767) myFunc(2);
    });
    

    http://fiddle.jshell.net/Ms3u5/