Use JavaScript onresize event to get to know if the browser window has been resized. The resize
event fires when the document view (window) has been resized.
In HTML:
<element onresize="myScript">
In JavaScript:
object.onresize = function(){myScript};
JavaScript onresize event
A simple example code executes a JavaScript when the browser window is resized:
<!DOCTYPE html>
<html>
<body onresize="myFunction()">
<script>
function myFunction() {
var w = window.outerWidth;
var h = window.outerHeight;
console.log("Window size: width=" + w + ", height=" + h);
}
</script>
</body>
</html>
Output:
Using the addEventListener() method:
<script>
window.addEventListener("resize", myFunction);
var x = 0;
function myFunction() {
var txt = x += 1;
console.log(txt
}
</script>
The best practice is to attach to the resize event.
window.addEventListener('resize', function(event) {
...
}, true);
jQuery is just wrapping the standard resize
DOM event, eg.
window.onresize = function(event) {
...
};
Do comment if you have any doubts or suggestions on this JS event topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version