How to fix the resize event in IE

In IE the window resize event is fired multiple times per actual resize: it is a well known issue for IE6 and IE7, but they misbehave along different patterns. Actually it seems that IE6 is worse than IE7.

After quite a long session of R&D, I’ve got to a pretty good solution, in the form of a jQuery plugin: jquery.wresize.js

/*  
===============================================================================
WResize is the jQuery plugin for fixing the IE window resize bug
...............................................................................
                                               Copyright 2007 / Andrea Ercolino
-------------------------------------------------------------------------------
LICENSE: http://www.opensource.org/licenses/mit-license.php
WEBSITE: http://noteslog.com/
===============================================================================
*/

( function( $ ) 
{
	$.fn.wresize = function( f ) 
	{
		version = '1.1';
		wresize = {fired: false, width: 0};

		function resizeOnce() 
		{
			if ( $.browser.msie )
			{
				if ( ! wresize.fired )
				{
					wresize.fired = true;
				}
				else 
				{
					var version = parseInt( $.browser.version, 10 );
					wresize.fired = false;
					if ( version < 7 )
					{
						return false;
					}
					else if ( version == 7 )
					{
						//a vertical resize is fired once, an horizontal resize twice
						var width = $( window ).width();
						if ( width != wresize.width )
						{
							wresize.width = width;
							return false;
						}
					}
				}
			}

			return true;
		}

		function handleWResize( e ) 
		{
			if ( resizeOnce() )
			{
				return f.apply(this, [e]);
			}
		}

		this.each( function() 
		{
			if ( this == window )
			{
				$( this ).resize( handleWResize );
			}
			else
			{
				$( this ).resize( f );
			}
		} );

		return this;
	};

} ) ( jQuery );

If you want to try it, here is a test page, where a div is automatically resized when the window is resized.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="overflow:hidden;">
 <head>
  <title> test window resize </title>

<script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"></script>
<script type="text/javascript" src="jquery.wresize.js"></script>


<script type="text/javascript">
jQuery( function( $ ) 
{
	function content_resize() 
	{
		var w = $( window );
		var H = w.height();
		var W = w.width();
		$( '#content' ).css( {width: W-20, height: H-20} );
	}

	$( window ).wresize( content_resize );

	content_resize();
} );
</script>

 </head>

 <body>
 
<div id="content" style="border: 1px dashed silver; position:absolute; overflow:auto;">
test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test 
</div>

 </body>
</html>

References:

http://dev.jquery.com
http://snook.ca
http://ecmascript.stchur.com

Tagged with: ,
Posted in Fixing
44 comments on “How to fix the resize event in IE
  1. max says:

    Brillant!
    …but check variable $.browser.version… It’s not numeric!
    for get work, I have to change in $.browser.version != “7″

  2. Andrea Ercolino says:

    Thanks Max. Fixed and incremented version to 1.1 :-)

  3. BrandyCruzn says:

    How do u have a fixed width? only resize on the height?

  4. tech says:

    This works well. Thanks! But this works only at the end of the window resize event in firefox, and during in IE. Is there some way I can call an event handler DURING the resize (that works cross browser?) I’d like to adjust some splitter panes while the window is being resized.

  5. rwbaker says:

    When I use the plugin and call a function with passing variables, such as resize(800,700), it bombs out. Any way the plugin could use functions with passing variables? Any one else experienced this problem and come up with a work around?

  6. Steve Rogers says:

    The Plugin works really well. I thought I was going to have to write something myself. Well done!

  7. matt says:

    This is a fantastic plugin. But I need a huge refinement. I need to perform a resize on an element AFTER MSIE 6/7 have finished the resize. Can you think of any voodoo that can know when that event occurs?

  8. Andrea Ercolino says:

    In the above example I resize the #content DIV after a window resize occurs…

  9. Alex K says:

    Andrea,

    Thanks for posting your solution. I noticed that binding multiple wresize handlers only executes the last one. Is that by design? Would it make sense to enhance the plugin to execute all attached handlers, in sequence?

    Thanks
    Alex

  10. ..alee says:

    hi,

    I am trying to use the jQuery splitter with richFaces, which i am able to integerate using tag. However, I am not able to make that “bind” function work with rich faces. I used the following query

    Can you people help me in binding it ?

  11. Si says:

    Hi, thank you for such a useful plugin. Can i ask a question?

    Does this only fire when the user’s browser is IE6 or IE7?

    I have written a website with a resizing image gallery. It works in all browsers except IE<8 and then it only breaks on resize of the window. What i would like to do is still have a $(window).bind(“resize”){func} to resize the images except for IE<8 where i could use

    jQuery( function($) {
    function content_resize(){
    window.location.reload(true);
    }
    $( window ).wresize( content_resize );
    } );

    this would force a refesh which is a minor annoyance for IE users and completely ok by me ; )

    Thank you

  12. Tooms says:

    Thank you for this plugin.

    But, if you have a flash in your website, there is a strange
    behavior.
    This plugin zoom in the flash.

    Sorry for my english.

  13. jerome says:

    very neat plugin – i’m wondering how complex it would be to fire the event instantly, the idea would be to have a smooth resizing of the elements on the page, like in the old days with the table’s width at 100%. not sure how i could do this… could you exlain a bit more the logic you are using?

    many thanks!

  14. Wulffy says:

    If I try to copy the second code in IE7 a yellow windows appears, sometimes with no content until I click into this. But then the code is not marked. If I try to mark it, the window closes. In FF3 this works perfect.

  15. sunnypyk says:

    Very fantastic demo~~ But I have one question wanna ask you, Mr. Expert!
    I am so amazing that Your example file can successfully ran in My IE7 without “IE prompt me to accept ActiveX”. This makes me very confuse. It is because Once I save as your example file with other name such as test-wresize2.htm and open it in IE7. It will prompt me to accept the ActiveX again. I have checked both original file and my new saved file have the same file size in byte and the coding are all the same. Would you please advise how can you do that? Many Thanks.

  16. Toeknee581 says:

    Awesome – All hail jquery. I spent so much time trying to figure this out. Your plugin worked perfectly in both ie7 and firefox 3. Thanks!

  17. scopes says:

    It seems to me that this script hasn’t really fixed the problem. If i copy your test file, add firebug lite for IE7′s benefit, and drop a console.log(‘resize’) inside of your content_resize() method, it shows that IE7 is still firing the same number of times as it does when i use resize(). Am I missing something?

  18. success_21 says:

    it didn’t work for me also. Below is the code i used,

    jQuery( function( $ )
    {
    function content_resize(){
    document.getElementById(‘leftDiv’).style.height=(document.body.clientHeight-260)+’px’;
    document.getElementById(‘rightDiv’).style.width=(document.body.clientWidth-270)+’px’;
    document.getElementById(‘rightDiv’).style.height=(document.body.clientHeight-130)+’px’;
    }
    $( window ).wresize( content_resize );
    content_resize();
    } );

    It is still firing the same number of times as it does when i use resize(). Is there anything wrong in my code? your reply would be very helpful for me.
    Thanks in advance.

  19. Nacho says:

    Thanks for this contribution, very usefull!

    Btw, I hate IE…

  20. Dom says:

    I’m not sure I understand this plug-in. I was hoping it would not fire a dozen events while the browser was being resized, but fire only once when the person has stopped dragging the browser’s width. In FF3, I get the event fired when the user pauses his movement and when he lets go of the resize handle. In IE6/IE7 I get the event fired continuously while the browser resize handle is being dragged. This is not working any better than using jQuery’s (1.3.2) built-in $(window).resize(fn).
    [...]

  21. Raymond Shaw says:

    Thank you :)

  22. Steven says:

    thanks

  23. Hugh says:

    ABSOLUTELY BRILLIANT!
    I have been trying to work around the IE Resize Bug many times, many hours and for many different projects!
    Finally, thanks to you, I have a solution which I can tailor for every need!!!
    I really owe my thanks to you and hope that others find it as useful as I did!

  24. Cujo says:

    I’m also not sure I understand how this is supposed to work. I’m developing a plugin for generic resizing (of windows, images, etc.). When I enter the plugin using the regular jQuery event handler method — $(selector).resize(function(){…$(selector).plugin(options)…} — jQuery gives a “this” object with at least one member. If instead I enter the plugin using wresize — $(selector).wresize($(selector).plugin(options)) — the plugin sees a “this” object with this.length == 0. Shouldn’t the plugin get identical “this” objects from jquery’s resize and wresize?

  25. Michael says:

    Great plugin. Saved me from a serious headache with IE/FF resizing! I did have some trouble copying and pasting your code. Whatever you’re using to display code on this page is a bit buggy. Thanks again!

  26. Hari says:

    I’m sorry if I sound negative, but I think that the following is a way better solution to for those who are looking into NOT executing the same code too many times. The “DelayedResize” method bellow will execute multiple times before user releases the mouse (e.g. drag window size handle, then pause without releasing the mouse), but not even nearly as many times as the onResize fires by default. And, this does not change Mozilla’s behavior at all.

    $(document).ready(function()
    {
    var tempCounter = 0;
    var windowResizeTimeout;

    window.onresize = function()
    {
    window.clearTimeout(windowResizeTimeout);
    windowResizeTimeout = window.setTimeout(DelayedResize, 100);
    };

    function DelayedResize()
    {
    window.status = ++tempCounter;
    // Add your original window.onresize implementation here
    }
    }

  27. Hari says:

    My apologies: add the following at the LAST statement of DelayedResize.

    window.clearTimeout(windowResizeTimeout);

  28. ollie says:

    What a life saver!

  29. djuRa says:

    Thanks Hari…Very, Very nice

  30. Aamir Afridi says:

    Hello guys I just discovered another problem which might help you.

    I am using jQuery and I have window.resize event to call a function which will re-position the div appended to the body.

    Now when I set the LEFT css property of that appended div, the window.resize event get trigger for NO GOOD REASON.

    It it results in an infinite loop, triggering the window.resize again and again.

    The code without fix:
    =============

    $(window).resize(function(){

    onResize = function() {
    //The method which sets the LEFT css property which triggers window.resize again and it was a infinite loop
    setWrapperPosition($mainWrapper.parent());
    }
    window.clearTimeout(resizeTimeout);
    resizeTimeout = window.setTimeout(onResize, 10);
    });

    Solution:
    =====

    var winWidth = $(window).width(),
    winHeight = $(window).height();

    $(window).resize(function(){

    onResize = function() {
    //The method which sets the LEFT css property which triggers window.resize again and it was a infinite loop
    setWrapperPosition($mainWrapper.parent());
    }

    //New height and width
    var winNewWidth = $(window).width(),
    winNewHeight = $(window).height();

    // compare the new height and width with old one
    if(winWidth!=winNewWidth || winHeight!=winNewHeight)
    {
    window.clearTimeout(resizeTimeout);
    resizeTimeout = window.setTimeout(onResize, 10);
    }
    //Update the width and height
    winWidth = winNewWidth;
    winHeight = winNewHeight;
    });

    So basically it will check if the height or width is changed (which will happen ONLY when you actually resize with window).

  31. pengkai says:

    @Hari YEP,your function is useful. like to handle dbclick in javascript. Don’t to use plug-ins is better. :)

  32. Hi everyone, a little bit late, but I believe both Hari and Aamir are valid solutions.

    In my case I needed to make sure no repeated events were fired and also check if the only the width has changed. Here is the code I used, based on both solutions:

    var windowResizeTimeout;
    var tempCounter = 0;
    var winWidth;

    function DelayedResize() {
    window.status = ++tempCounter;
    var winNewWidth = $(window).width();
    if (winWidth != winNewWidth)
    UpdateAllSizes(); // function to process the resize to the controls on the page.
    winWidth = winNewWidth;
    }

    function checkResize() {
    window.clearTimeout(windowResizeTimeout);
    windowResizeTimeout = window.setTimeout(DelayedResize, 250);
    }
    $(window).wresize(checkResize);

    Regards

  33. estetik says:

    very good article thanks admin for the post

  34. Ron C says:

    I’m seeing another IE8 quirk with resize. The HTML page has no width set and uses the jQuery scroll with a timer as above to reposition an absolute DIV if it has gone off-screen.

    Under IE8, when the window is reduced in width, IE briefly inserts a horizontal scroll bar (reducing the height). It appears to then send separate resize events for the reduction in width and height, then another appreciably later for the increase in height when it removes the horizontal scroll bar it just added! This does not happen under Firefox, Safari, nor Chrome.

    I can increase the delay started the resize events to mask this. About 500mS does the trick on my test machine, but have doubt that will work on a broad spectrum of machines. It also makes the app look a bit unresponsive, though it’s better than seeing the div glide in from the right, then drop down from the top under IE.

    Grrr.

  35. Tchat says:

    Thank you for work :-)

  36. Steve says:

    It seems that you have turned overflow on this site to hidden or somehow turned off scrollbars. Looking at this in Chrome 6. Thanks for the post.

  37. Andrea Ercolino says:

    @Steve, many thanks. There was something wrong with my post template, still to understand what exactly, but I could fix it.

  38. Robert D. Cluett says:

    Pretty much had the same solution…

    var dashboard = {

    ieresizeTimer : null,

    setSizeWrapper : function()
    {
    if (client.isIE)
    {
    $(‘resizemask’).style.display = ‘block’;
    clearTimeout(dashboard.ieresizeTimer);
    dashboard.ieresizeTimer = setTimeout(“dashboard.setSize()”,100);
    }
    else
    {
    dashboard.setSize();
    }
    },

    setSize : function()
    {
    // resize code here
    }

  39. Renuka says:

    Thanks for your code. It helps me a lot.

  40. Art says:

    Hello,
    I did exactly as in your example but in IE8 the function in wresize event is called incrementally on and on.

  41. Andrea Ercolino says:

    @Art Unfortunately I have not any more a Windows PC to update this plugin. If you can provide an update yourself I’ll be pleased to publish it here or link from here to your blog. Thanks.

  42. Shorty says:

    An answer from an eerxpt! Thanks for contributing.

  43. Thanks! Your method helped me finished my task! It could work, but I still want to ask you why resize in Chrome execute twice?

  44. Dorian says:

    Hi, thank you very much! It really helped me, but I’m a real newbie in javascript and I can not seem to get the value of the current width outside of the function (I’m trying to set video player size based on some conditions). Contact me if you want to :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>