automatically detect web browser window width change?
Solution 1
Try the resize event
$(window).resize(function() {
console.log('window was resized');
});
Solution 2
Writing this down cause somehow none of these answers give the modern best-practices way of doing this:
window.addEventListener("resize", function(event) {
console.log(document.body.clientWidth + ' wide by ' + document.body.clientHeight+' high');
})
Solution 3
The JavaScript event is named window.onresize
.
The JQuery binding is named .resize()
Solution 4
In MDN they give a really good Javascript standalone code:
window.onresize = resize;
function resize()
{
alert("resize event detected!");
}
If you need just this kind of functionality I would recommend to go for it.
Solution 5
You might want to use debounce
:
https://davidwalsh.name/javascript-debounce-function
Otherwise the
window.addEventListener("resize")
Will fire the whole time as the window resize is in progress. Which will tax your CPU overhead.
Comments
-
ajsie over 3 years
i know that you with $(window).width() can get the size of the web browser.
i want to detect when the user change the size of his web browser so i could readjust the columns width. is there a way to automatically detect this or do i have to use setTimeinterval to loop and see if it has changed?