pencilpix pencilpix - 3 months ago 60
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

window.resizeTo()
and
window.resizeBy()
don't trigger the event according to the modern browsers prevent these actions. I tried jquery
$(window).trigger('resize');
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.

example

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

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

IE9+

Trigger native

// For a full list of event types: https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);

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'});
}

el.dispatchEvent(event);