Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Noko Time Tracking and Every Time Zone and write books like Retinafy.me.
   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.