How can I detect when a user resizes the browser window?
I'm looking for a script that does somenthing when user resizes the window or when the window's width is less than, for example, 900px.
You can subscribe to the window resize event like this:
$(window).on("resize", function(event){
console.log( $(this).width() );
});
Just be careful with this, since a if-statement that executes code when the width is less than n would execute that code a ridiculous number of times while you resize a window that meets those conditions. Better to set some flags or add classes to the document, and make those part of your condition as well.
However, what you're asking sounds like it would most appropriately be solved with CSS Media Queries. For instance, if we wanted to change the body background color when the window is less than 900px:
@media screen and (max-width: 900px) {
body {
background: #ccc;
}
}
There's even a great polyfill for older version of IE: https://github.com/scottjehl/Respond
jQuery:
$(window).resize(function() {
//do something
var width = $(document).width();
if (width < 900) {
// do something else
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With