Skip to main content

JavaScript Snippet Force a DOM Element Redraw/Repaint

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

JavaScript code snippet to force a DOM element redraw/repaint. A bit hacky but useful as a last resort.

var element = document.getElementById('id');
var n = document.createTextNode(' ');
var disp = element.style.display;  // don't worry about previous display style

element.appendChild(n);
element.style.display = 'none';

setTimeout(function(){
    element.style.display = disp;
    n.parentNode.removeChild(n);
},20); // you can play with this timeout to make it as short as possible

Using Transit.js

If your using a transition plugin like transit.js this also works:

$('#element')
    .transition({ x: '-500px', easing: 'snap', duration:'0' })
    .transition({ x: '0', easing: 'snap', duration:'0' })
    .css('z-index','10');

CSS:

#element {
     position: absolute;
     right: '-500px';
     z-index: -1;
}

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.