/blog/snippets/

Force repaint of an element with Javascript

Today I had a pretty nasty situation in which Safari on OSX would render an element in a place where it doesn't belong. It was clearly a rendering bug/issue because when highlighting the element in the web inspector the place where the element should have been rendered was highlighted.

I tried adding transform: translate3d(0,0,0); to push the element on it's own layer to increase rendering performance, but that didn't help. I thought that if I could bring the browser to repaint the element, I'd be fine, even though it's probably not the nicest solution. I dug around the internet and found a solution to force the repaint of an element with Javascript:

/**
 * Force Repaint of Header because of
   OSX Safari Rendering Bug
 */
var siteHeader = document.getElementById('header');

siteHeader.style.display='none';
siteHeader.offsetHeight; // no need to store this anywhere, the reference is enough
siteHeader.style.display='block';

But be careful when you execute this code. You don't want to repaint an element more often than you absolutely have to.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.