Val Do
Val Do

Reputation: 2695

if condition always work inside $(window).resize function

I have this script and I want when window is only less than 768px console.log('less than 768px'); but my script works always when window is more then 768px please help me someone :(

    var width = $(window).width();
    $(window).on('resize',function(){
        if (width < 768){
            console.log('less than 768px');
        }else{
            console.log('nothing');
        }
    });

Upvotes: 0

Views: 1739

Answers (3)

Sebri Zouhaier
Sebri Zouhaier

Reputation: 745

This works when set width value

$(window).resize(function (){
    var width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
if (width < 768){
    console.log('less than 768px');
} else{
    console.log('nothing');
}  
})

Upvotes: 1

Daniel Edholm Ignat
Daniel Edholm Ignat

Reputation: 268

You need to get the width inside the resize event callback to get the updated value:

$(window).on('resize',function(){
    var width = $(window).width();
    if (width < 768){
        console.log('less than 768px');
    }else{
        console.log('nothing');
    }
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to set the width variable inside the resize handler, otherwise it only uses the window width as set on page load.

$(window).on('resize',function(){
    var width = $(window).width();

    if (width < 768){
        console.log('less than 768px');
    } else {
        console.log('nothing');
    }
});

Upvotes: 2

Related Questions