pencilpix pencilpix - 1 year ago 378
Javascript Question

How to trigger window resize event using vanilla javascript?

I'm trying to trigger resize event using plain js for testing purpose, but

don't trigger the event according to the modern browsers prevent these actions. I tried jquery
but it works only for events that attached via jquery like
$(window).on('resize', handler);
. however in my case the project I am working on uses plain javascript.


window.addEventListener('resize', function(){
console.log('window has been resized !');

// or even using global onresize
window.onresize = function() {
console.log('window has been resized!');

Answer Source

You are most likely getting downvoted as people will see it as a duplicate, however from the you might not need jquery website:


Trigger native

// For a full list of event types:
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);

Trigger custom

if (window.CustomEvent) {
  var event = new CustomEvent('my-event', {detail: {some: 'data'}});
} else {
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent('my-event', true, true, {some: 'data'});

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download