0

For a project I'm making a board game using HTML and JavaScript, and I'm fairly new to it. I need the main function to wait for the player to click "roll" and then return the result as a variable so it can be used for other functions.

How do I force JavaScript to wait for the button to be clicked and how can I then get a variable from the script that runs?

The HTML of the button looks like this:

<input type = "button" id="roll" value = "roll">

How the JS might look:

function makeNumber(){
  //returns number >=1 <=6
}

function main(){
    while (win ! true){ 
        //here it should wait for the click event
        document.getElementById("roll").addEventListener("click", 
        makeNumber());
        
        var diceResult; // here id like to save the result from the 
        makeNumber function above 

        doSomething(diceResult);
    }
}

I've also tried this other method, but have the exact same problem:

document.getElementById("foo").onclick =  function() {myFunction()}; 
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Riro
  • 1
  • 1
  • There's a lot of context missing from your question, but it seems like `rollDice()` should be called by `main()` which should be called by the click event listener. (i.e. **when the user clicks the button, then the dice and rolled and the player is moved** as opposed to **when the button is clicked the dice are rolled** combined with **when something unrelated and unspecified happens the player is moved based on the dice roll**). – Quentin Feb 01 '23 at 10:22
  • Re edit: "my Question: how do force JavaScript to wait for the button to be clicked and how can i then get a variable from the script that runs." — That's really rather country to how JS works (you could sort of doing it by wrapping the event listener in a promise and `await`ing it but that's going to be long winded, complicated, and require you to learn a lot). Do what I suggest in my previous comment instead. – Quentin Feb 01 '23 at 14:05
  • Hi your advice was a big help. got it dealt with now – Riro Feb 01 '23 at 16:03

0 Answers0