devid G. devid G. - 1 month ago 6
CSS Question

Why my javascript code not process from top to bottom coding?

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>

Answer

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.

Comments