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 Answer 1

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">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.