Search code examples
javascriptjqueryeventsonresize

How to trigger the window resize event in JavaScript?


I have registered a trigger on window resize. I want to know how I can trigger the event to be called. For example, when hide a div, I want my trigger function to be called.

I found window.resizeTo() can trigger the function, but is there any other solution?


Solution

  • Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

    window.onresize = doALoadOfStuff;
    
    function doALoadOfStuff() {
        //do a load of stuff
    }
    

    In this example, you can call the doALoadOfStuff function without dispatching an event.

    In your modern browsers, you can trigger the event using:

    window.dispatchEvent(new Event('resize'));
    

    This doesn't work in Internet Explorer, where you'll have to do the longhand:

    var resizeEvent = window.document.createEvent('UIEvents'); 
    resizeEvent.initUIEvent('resize', true, false, window, 0); 
    window.dispatchEvent(resizeEvent);
    

    jQuery has the trigger method, which works like this:

    $(window).trigger('resize');
    

    And has the caveat:

    Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

    You can also simulate events on a specific element...

    function simulateClick(id) {
      var event = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true
      });
    
      var elem = document.getElementById(id); 
    
      return elem.dispatchEvent(event);
    }