Adam Brady Adam Brady - 5 months ago 11
CSS Question

Javascript not visually updating Text with Webkit Gradient

I have some text 'foo', which uses a gradient to colour it. I want to update this text to 'bar', but when I do this, the text stays the same until I highlight it, when it then changes. A jsfiddle with example code is here. Can anyone figure out how to make it so it does update?
Note: The current gradient code only works in Chrome

HTML:

<div id="gradient_div">
<p id="gradient_text" onload="update">
Foo
</p>
</div>


CSS:

#gradient_div
{
background: linear-gradient(#000000,#ffffff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}


Javascript:

setTimeout(function(){
document.getElementById("gradient_text").innerHTML="bar";
},500);

Answer

You would have to force a repaint, similar to what @BrianDiesel said, except it might take a little more than that. This should work:

setTimeout(function(){
  var elem = document.getElementById("gradient_text")
  elem.innerHTML = "bar";
  // force reflow
  var display = elem.style.display
  elem.style.display = 'none'
  setTimeout(function(){
    elem.style.display = display
  }, 50)
}, 500);
#gradient_div
{
  background: linear-gradient(#000000,#ffffff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
<div id="gradient_div">
  <p id="gradient_text" onload="update">
    Foo
   </p>
</div>

Essentially these are all hacks and might not work depending on your use cases, but it should be possible to find one that will work for the browsers you plan to support. Let me know if this one doesn't.

I hope that helps!

Comments