JS or jQuery or window resize or when window width is less than npx

38,980

Solution 1

Meh, You can use jQuery, but...

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.

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:

@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

Solution 2

jQuery:

$(window).resize(function() {
    //do something

    var width = $(document).width();
    if (width < 900) {
       // do something else
    }
});

Solution 3

You can use $(window).resize() like follows

$(window).resize(function() {
     if($(this).width() < 900)
       //do whatever you want
  });

Here is the documentation for $.resize

Solution 4

According to what you need, this could handle when windows size is less than 900px:

 $(window).on("resize", function(event){
      console.log('User is using resize!');
      var w = $(this).width();
      if(w < 900)
        console.log('Your window is ' + w + 'px (less than 900px)');
 });​

Solution 5

$(window).resize(function() {
  $('body').prepend('<div>' + $(window).width() + '</div>');
  // Do stuff
});
Share:
38,980
itsme
Author by

itsme

JS

Updated on July 21, 2022

Comments

  • itsme
    itsme almost 2 years

    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.

  • jamiebarrow
    jamiebarrow about 11 years
    I'm not sure if this is off topic, but a use case I have for using JS instead of CSS media query for a responsive view is switching out the view template being used (in my example by durandal.js / knockout.js). I found that width() works, however also changes when you zoom. Still not sure how to get the actual width in this case (in my mind it shouldn't change when zooming).
  • Silkster
    Silkster over 6 years
    As mentioned in the selected answer here, you don't want the function to fire a bunch of times while resizing the window. I recommend using a debounce function to prevent that. See davidwalsh.name/javascript-debounce-function