If I have this
window.onresize = function() {
alert('resized!!');
};
My function gets fired multiple times throughout the resize, but I want to capture the completion of the resize. This is in IE.
Any ideas? There are various ideas out there, but not has worked for me so far (example IE's supposed window.onresizeend event.)
simple pure javascript solution, just change the 1000 int value to be lower for more responsiveness
In this case, I would strongly suggest debouncing. The most simple, effective, and reliable way to do this in JavaScript that I've found is Ben Alman's jQuery plugin, Throttle/Debounce (can be used with or without jQuery - I know... sounds odd).
With debouncing, the code to do this would be as simple as:
Hope that can help someone. ;)
Not sure if this might help, but since it seems to be working perfectly, here it is. I have taken the snippet from the previous post and modified it slightly. The function doCenter() first translates px to em and than substracts the width of the object and divides the remainder by 2. The result is assigned as left margin. doCenter() is executed to center the object. timeout fires when the window is resized executing doCenter() again.
I always use this when I want to do something after resizing. The calls to
setTimeout
andclearTimeout
are not of any noticable impact on the speed of the resizing, so it's not a problem that these are called multiple times.You get multiple events because there really are multiple events. Windows animates the resize by doing it several times as you drag the window (by default, you can change it in the registry I think).
What you could do is add a delay. Do a clearTimeout, setTimout(myResize,1000) every time the IE event fires. Then, only the last one will do the actual resize.
I liked Pim Jager's elegant solution, though I think that there's an extra paren at the end and I think that maybe the setTimeout should be "timeOut = setTimeout(func,100);"
Here's my version using Dojo (assuming a function defined called demo_resize())...
Note: in my version the trailing paren IS required.