jQuery force element redraw

So, today I’ve discovered a neat trick to solve an issue that’s been bothering me essentially since I’ve started web development.

As you know, jQuery offers the ability to modify the DOM at will. Now, all of the functions available to perform DOM operations are syncronous, meaning that the next instruction will start only when the one that preceedes it will have finished its task.

This is not necessarily true for the actual DOM manipulation, leaving us in the middle of a muddy unfathomable jungle, where one thing is syncronous, but actually isn’t.

Before complex UI libraries came around, this led generations of developers, including myself, to solve this issue with loads of setTimeout calls, whose milliseconds parameter was inconsistent, at best: sometimes a 1 millisecond value would do it, sometimes it was 10 milliseconds, other times any other number that you could think of.

In all honesty, this felt weird and unstable from day one: so what if there was a way to get rid of setTimeouts entirely and force a redraw of the manipulated DOM element?

Turns out, it’s simpler than I thought. Here’s the snippet:

$.fn.force_redraw = function() {
    return this.hide( 0, function() {
        $( this ).show();
    } );
}

Simply instantly hide and show the element, and you’ll be good to go, and you’ll be able to say goodbye to at least some of your setTimeouts.

Leave a Reply