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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Meh, You can use jQuery, but…
You can subscribe to the window resize event like this:
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.
CSS Media Queries is Where It’s At!
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:
There’s even a great polyfill for older version of IE: https://github.com/scottjehl/Respond