Jacob Larsen Jacob Larsen - 1 month ago 9
Javascript Question

Basic JavaScript - How to make a certain lines of code run before prompts/prompt-containing functions?

function restart_game() {
document.getElementById("myBody").style.backgroundColor = "rgba(255,255,255,1)";
finished=false;
do_game(); //do_game() has a prompt within it that interrupts the .document line.
}


So let's say I want to run
document.getElementById
before
do_game()
(a function that calls a prompt) but they are called by the same function: How do I make this happen effectively?

I want them both to run but in the order that I decide, without the prompt within
do_game()
happening before my style changes in the line before. Or is there just a better way to achieve what I'm attempting to do with different code?

Any advice would be highly welcome.

Answer

I would do this in order to make sure that do_game() runs after style changes:

var myBody = document.getElementById("myBody");

function restart_game() {
   myBody.style.backgroundColor = "rgba(255,255,255,1)";
   finished=false;
}

myBody.addEventListener("DOMAttrModified", function(e){
   if (e.attrName === 'style')
      do_game();
});

Explanation: This way, restart_game() function will change style of "myBody" element. When that happens, eventListener attached to "myBody" element will detect style changes and execute do_game() so you'll have their execution aligned.

Comments