The code below adds width of screen to class .reverse
var w = $(window).width();
$('.reverse').css('width', w);
but I want it to do so only if the screen width is less than 960px:
if ($(window).width() < 960) {
$('.reverse').css('width', w);
}
The code above is not working, could you take a look? Thx!
I think you are resizing window to check this effect so you need to add resize eventListener,to the DOM.
$(window).on('resize',function(){
var w=$(window).width();
if (w< 960) {
$('.reverse').css('width', w);
}
})
Try with jQuery
$(window).resize(function(){
var width = $(window).width();
console.log(width);
if (width < 960){
$('.reverse').css('width', width);
};
});
This way you're constantly checking the window's width while resizing as well.
You can also do this with CSS and a media query if you don't have to use javascript
@media (max-width: 960px) {
.reverse {
width: 100vw;
}
}
var w = $(window).width();
if (w < 960) {
$('.reverse').css('width', w);
}
Note, add the event management if needed but no w
was defined.
IF you add the event management in, be careful as it will fire a lot and it would be best to NOT force a re-flow every time - look into that separate issue.
A link to a possible debounce for the resize https://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
if ($(window).width() < 960) { $('.reverse').css('width', w); }
You didn't initialize w
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.