Trigger window’s resize event with JavaScript/jQuery
This post will discuss how to trigger a window resize event in JavaScript and jQuery.
1. Using jQuery
In jQuery, you can trigger the window resize event using the .trigger() method.
|
1 2 3 4 5 6 7 |
$(document).ready(function() { $(window).trigger('resize'); }); $(window).resize(function() { alert('Handler for .resize() called!'); }); |
2. Using JavaScript
In pure JavaScript, you can trigger the resize event using window.dispatchEvent() method:
|
1 2 3 4 5 6 7 |
window.addEventListener("load", function() { window.dispatchEvent(new Event('resize')); }); window.onresize = function() { alert('Handler for .resize() called!'); } |
Alternatively, you can use the window.resizeTo() to trigger the resize event.
|
1 2 3 4 5 6 7 8 9 10 |
window.addEventListener("load", function() { window.resizeTo( window.screen.availWidth / 2, window.screen.availHeight / 2 ); }); window.onresize = function() { alert('Handler for .resize() called!'); } |
That’s all about triggering the window’s resize event in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)