13

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!');
};
Mohamed Hassan
  • 151
  • 1
  • 1
  • 6
  • If your event listener is a named function you can just call that function directly (assuming it doesn't need to use the `event` object). – nnnnnn Aug 30 '16 at 21:55

1 Answers1

28

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 el = document; // This can be your element on which to trigger the event
var event = document.createEvent('HTMLEvents');
event.initEvent('resize', true, false);
el.dispatchEvent(event);

Trigger custom

var el = document; // This can be your element on which to trigger the event
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);
theunexpected1
  • 1,017
  • 11
  • 23
bitten
  • 2,463
  • 2
  • 25
  • 44