简体   繁体   中英

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

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

Move var w = $(window).width(); inside resizer() . This will get the value of current dimensions of window .

See the comments inline in the code.

var isMobile = false;

function resizer() {
    var w = $(window).width();
    // Move this inside resize handler

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

$(window).resize(function() {
    resizer();
}).trigger('resize');
// ^^^^^^^^^^^^^^^^^^
// 
// Trigger event on page load

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