Howto: Force a browser redraw/repaint
Have you ever had the problem that IE (most often in IE6, IE7 and even in IE8) or other browsers just didn’t redraw the content? This happens quite often when CSS properties get changed via JavaScript. There are already some solutions available to solve this problem but most of them just don’t work properly. I’m now going to show you the way it works most often and a solution which I found myself.
The one which works almost everytime is reassigning the class name:
el.className = el.className
But the above fix doesn’t work for absolute positioned elements and in some other cases. I came up with the following solution.
By changing the padding for a very short moment (1ms) and changing it back afterwards to its original value a browser redraw gets triggered.
For convenience sake I wrote a jQuery plugin which is available at http://plugins.jquery.com/project/force_redraw.
Examples:
$('#myelement').forceRedraw(); //same as el.className = el.className
$('#myelement').forceRedraw(true); //this will use the padding method
That’s it! I really hope it will save you lots of time!
Hi Pascal
I had this problem today in IE7 (probably also the other IEs) and jQuery’s fadeIn function.
Your solution worked!
Thanks,
TJ
Thanks so much for this plugin. It does exactly what I needed. I have one small suggestion: instead of returning void, return the jQuery node on which forceRedraw was called so it can be chained.
@James A. Rosen
Hi James
Thanks for the hint. I uploaded a new version which enables chaining.
Best regards
Pascal