0

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');
        }
    });
Val Do
  • 2,695
  • 4
  • 20
  • 35
  • ...and where are you getting the value of width?! – Lee Taylor Dec 02 '14 at 13:17
  • can you post the origine of with value you can use: var width = document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth; – Sebri Zouhaier Dec 02 '14 at 13:17
  • 1
    If you assign value to `width` only **before** any pages resizes, and never change its value after resize, then there is no wonder you don't get what you want. It's logic error, by the way. – Regent Dec 02 '14 at 13:19
  • https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/ – A. Wolff Dec 02 '14 at 13:22

3 Answers3

2

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');
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

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');
    }
});
1

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');
}  
})
Sebri Zouhaier
  • 745
  • 7
  • 18