14

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!');
};
1
  • 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). Commented Aug 30, 2016 at 21:55

1 Answer 1

29

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);
Sign up to request clarification or add additional context in comments.

3 Comments

For people looking to trigger a resize event, use resize, not change in the call to initEvent.
Where did the "el" come from?
wherever the event was attached to. it could be window or a dom element.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.