The resize event runs when the browser viewport changes size. Attach it to window.
$( window ).on( "resize", function () {
// The viewport size changed.
});
$( function () {
$( window ).on( "resize", function () {
$( "#d1" ).text(
"Window width: " + $( window ).width() + " px"
);
});
});
<div id="d1">Resize this browser window.</div>
Resize handlers can fire frequently. For expensive work, consider debouncing the handler so layout calculations do not run on every intermediate resize event.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.