Tim Mcneal
Tim Mcneal

Reputation: 283

How to actively seek and receive the browser window's width?

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.

Upvotes: 0

Views: 44

Answers (1)

Salman Arshad
Salman Arshad

Reputation: 272106

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.

Upvotes: 2

Related Questions