Running a function with jQuery when the window is resized

Posted in Javascript -

Although it should be avoided where possible, there may be times when something on a web page needs to be adjusted if the window size is changed. This can be done quite easily with jQuery but it needs to be done with caution as I show in this post how different browsers react to $(window).resize()

Update August 26th 2009

Thanks to Paul Irish for letting me know about his resize() jQuery plug-in which addresses the cross-browser issues noted in this post. Update ends.

$(window).resize()

Running a function whenever the window is resized with jQuery is as simple as this:

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

It's possible to also assign resize() to any element but this post is specifically looking at when a window is resized.

Browser Issues

If you do have to resort to using $(window).resize() be aware that the trigger can be called multiple times as a window is resized depending on the browser version and operating system. Therefore it is best to keep the code that runs on resize to a minimum to prevent slowing the browser too much.

I have tested the following:

Firefox 3.5 on Windows 7: The function is run only after the window resize operation is complete.

Firefox 3.0/2.0/1.5/1.0 on Windows XP: As for Firefox 3.5. However there was a marginal delay between the end of the resize operation and when the function was run compared with FF3.5. This could be due to it being XP vs Windows 7, or the fact I was running it in a VM with far less memory.

IE6 on Windows XP: The function is triggered during the window resize so will be triggered multiple times as the window is resized. It also appears to be triggered twice every time. For example, maximizing the window will trigger the resize() function twice.

IE7 on Windows XP: As for IE6. Note also that it will trigger on page load if a DOCTYPE is set.

IE8 on Windows XP and Windows 7: As for IE6.

Safari 3 on Windows XP, Safari 4 on Windows 7: Safari also triggers the function as the window is resized but it only calls the function once each time, instead of twice like IE.

Opera 9.64 on Windows 7: Same as for Safari, but it seems to hold off the function calls until the window has finished resizing and then suddenly runs them all.

Google Chrome 2.0.172.39 on Windows 7: Same as for IE6

Code used for testing

The following is the code I used for testing the above:

<script language="javascript" src="/js/jquery-1.3.2.min.js"></script>
<script language="javascript">

$(document).ready(function() {
    var i = 0;
    $(window).resize(function() {
        i++;
        $("#status").append(i + " ");
    });
});

</script>

<div id="status"></div>

Whenever the window is resized it increments the "i" variable and appends it to the #status div along with a space for readability.



Related posts:


Comments