Why my javascript code not process from top to bottom coding ?
https://jsfiddle.net/p47f6Lcy/1/
With my code when press on id="test" Why still alert before change backgroundColor and translate3d
See on my code it's should change backgroundColor and translate3d before call function test2_fn
How can i do for change backgroundColor and translate3d befire alert ?
..
<div id="test" onclick="test_fn()">
CLICK
</div>
<script>
function test_fn(){
document.getElementById("test").style.backgroundColor = "red";
document.getElementById("test").style.transform = "translate3d(500px, 0px, 0px)";
test2_fn();
}
function test2_fn(){
alert("555");
}
</script>
As nnnnnn mentioned in the comments:
Because the browser doesn't repaint the screen until the current JS finishes executing. So the element styles have been updated in the DOM, you just don't see it yet.
If you really want to do it, you can postpone the execution of the other function to the next cycle in the event loop. You can simply use setTimeout(test2_fn, 0).
Working fiddle
This is also a good read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With