0

The JQuery code:

if ($(window).width() < 1000) {
    alert("width is less than 1000");
}

Only returns the window width value when the page is loaded. If the user's window started out being greater than 1000 and the shrunk the window width so that it was lower than 1000, the above code would not run. How do I get a constant check for the width of the window to account for this scenario.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Tim Mcneal
  • 283
  • 4
  • 19

1 Answers1

2

You listen to window resize event (as well as the load event):

$(window).on("load resize", function() {
    console.log($(this).width());
});

Note that the resize event fires constantly while the user is dragging the window. If you add complex logic in the event handler you might experience sluggish performance. It would be nice to wrap your code inside a debounce function... a function that fires few milliseconds after the user is finished resizing the window.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • Adding an event listener like @Salman A mentions is the correct answer. Though I think it is important to add discretionary notes to this sort of thing. Remember that your css and javascript will interpret the size of the viewport differently (~15-30px in my experience). The only available CSS solution doesn't full degrade to all available browsers, but it is a decent solution: http://stackoverflow.com/questions/8161304/how-to-reliably-get-screen-width-with-the-scrollbar – Joseph Casey Apr 30 '15 at 21:40