JavaScript
Article

jQuery Capture Window Resize on End Event

By Sam Deering

Two methods to capture a resize event on a window, but how to capture the event once the user has finished resizing the window? A little trick is to use a setTimeout() with clearTimeout() and optimal duration is 250 even captures slowish window resizes smoothly. See Window resize examples for how you might use them.

Method 1

$(window).bind('resize', function(e)
 {
     //do something
});

Method 2

$(window).resize( function(e)
{
    //do something
});

Method 2 with timeout

$(window).bind('resize', function(e)
{
    window.resizeEvt;
    $(window).resize(function()
    {
        clearTimeout(window.resizeEvt);
        window.resizeEvt = setTimeout(function()
        {
            //code to do after window is resized
        }, 250);
    });
});

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • Pingback: jQuery Capture Window Resize on End Event » PHP Script Blog()

  • kilian

    Great solutions!

    Why do you have the resize listener twice on “method 2 with timeout” ?
    $(window).bind(‘resize’, function(e)….

    $(window).resize(function()…

    • Spork Schivago

      I wish you got an answer. I too wonder why. I can’t get the code to work properly and I wonder if this is why. :(

      • James Hibbard

        I have no idea why the author used bind and resize. It looks like a mistake to me.
        In any case, using modern jQuery syntax, this should do what you want:

        var resizeEvt;
        $(window).on("resize", function() {
        clearTimeout(resizeEvt);
        resizeEvt = setTimeout(function() {
        console.log("hi");
        }, 250);
        });

        If you want to discuss this some more, why not post a question in our JavaScript forum?
        http://community.sitepoint.com/c/javascript

        • Spork Schivago

          Thank you! Sorry for the late reply! Totally forgot about all this. Been busy working on other stuff. Thanks!!!

  • http://www.sharkattackdata.com/ SharkAttackData

    Method 2 with timeout does the trick–thanks.

    I made a couple minor changes: I declared resizeEvt in the parent scope (i.e. outside the .bind() call). This way it avoids putting a variable in the global namespace in case I want to apply this method elsewhere.

    One more change was to use .on() instead of .bind(), which is now the preferred way of attaching an event handler.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.