Caspert
Caspert

Reputation: 4363

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

Upvotes: 2

Views: 2449

Answers (3)

danial
danial

Reputation: 21

you can use these ways:

  • Method 1: Check if the user is on a mobile device

const isMobile = /Android/i.test(navigator.userAgent);

  • Method 2: Check if the screen width is less than 680 pixels

const isMobileWidth = window.innerWidth < 680;

Upvotes: 0

Skatch
Skatch

Reputation: 2272

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

Upvotes: 5

Tushar
Tushar

Reputation: 87203

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

Upvotes: 2

Related Questions