Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of the script.aculo.us user interface JavaScript library, a member of the Prototype core team and a Ruby on Rails core alumnus.
You're using my JavaScript work every day, even if you're not aware of it!
   Need corporate training or want me to speak at your conference? Contact me!

Little JavaScript hints, episode 3: force redraw

January 11th, 2009

If you ever did some advanced DOM manipulation stuff, especially CSS-based animations, you might have run into situations where the browser just wouldn’t redraw an element correctly.

Here’s a little snippet for Prototype I use to force redraw in such situations:

Element.addMethods({
  redraw: function(element){
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    (function(){n.parentNode.removeChild(n)}).defer();
    return element;
  }
});

The defer() call is interesting, as I needed to add it to fix some really weird redraw issues with WebKit nightlies. Obviously the rendering optimization in browsers have come a long way, so there might be even more tricky “force redraw” schemes necessary, depending on the browser and situation.

$('element_id').redraw();

I’d love to hear feedback from you if you have to use any such contraptions in your code.