Search code examples
javascriptjqueryviewport

How to check if viewport is smaller than a certain width using javascript?


I want to have a simple statement to set a variable bool to false or true. isMobile should be set to true when the viewport is smaller then 768px and above this amount it should be set to false.

I don't know why the following code does nothing. Also there is no error in the console log.

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

function resizer() {
    if (w < 768) {
        console.log("resize");
        isMobile = true;
    } else {
        isMobile = false;
    }
}

$(window).resize(function() {
    resizer();
});

Solution

  • Because you don't measure the width on every resize. Try this way:

    var isMobile = false;
    
    function resizer() {
        var w = $(window).width();
        if (w < 768) {
            console.log("resize");
            isMobile = true;
        } else { 
            isMobile = false;
        }
    }
    
    $(window).on('load resize', function(){ 
        resizer();
    });