1

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);

2 Answers2

0

I've used this trick in the past in order to force the the browser to redraw the element:

setTimeout(function(){
  var elm = document.getElementById("gradient_text");
  elm.innerHTML="bar";
  elm.style.display = 'none';
  elm.style.display = 'block';
},500);
BrianDiesel
  • 168
  • 5
0

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 repaint
  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!

m-a-r-c-e-l-i-n-o
  • 2,622
  • 18
  • 26
  • Thank you! That works perfectly. I see you have a 50 millisecond delay on the timeout, how come 50 milliseconds? Is that just to make sure it has time to visually disapear? –  Jun 28 '16 at 21:05
  • You're very welcome! I'm not 100% sure, I was familiar with a few hacks along those lines, so I just tried some variations and it worked. But for the sake of curiosity, I went ahead and posted the question here just now: http://stackoverflow.com/q/38086610/1666547 Feel free to follow it for a more elaborate answer. – m-a-r-c-e-l-i-n-o Jun 28 '16 at 21:31
  • What browser and what version of it are you running? – m-a-r-c-e-l-i-n-o Jun 28 '16 at 21:57