Reputation: 2695
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
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
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
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