0

example..

<input type="button" value="click me" id="p1">

<script>
 document.querySelector("#p1").onclick = function () {
    this.style.backgroundColor = "green";
    alert(`My background color is ${this.style.backgroundColor} ??`);
  }
</script>

The alert write My background color is green but at the moment of alert the color is gray!!

I know many ways to get around this:

..but is a way to be sure that the browser rendering is done?

1 Answers1

1

You could use requestAnimationFrame - similar to setTimeout except the browser will take care of the timing as the function is run before a repaint.

A simple example:

function tellMe() {
  alert(`My background color is ${document.querySelector('#p1').style.backgroundColor} ??`);
}
document.querySelector("#p1").onclick = function() {
  this.style.backgroundColor = "green";
  requestAnimationFrame(function() {
    requestAnimationFrame(tellMe)
  });
}
<input type="button" value="click me" id="p1">
A Haworth
  • 30,908
  • 4
  • 11
  • 14