Duplo W
Duplo W

Reputation: 623

How to call the function every time I click the button?

How do I randomize a new number every time I click the button? It works once, but when I click again it's the same numbers. How do I solve this?

HTML:

 <div id="center">
    <h1>Dragon</h1>

    <div id="dragonRedHpBar">
        <div id="dragonGreenHpBar"></div>
    </div>

 <span id="hpLeft1"></span>

 <p>The Dragon hit you for: <span id="DragonHit"></span></p>

 <p>You hit a: <span id="MyHit"></span></p>

 <h1>Player</h1>

    <div id="myRedHpBar">
        <div id="myGreenHpBar"></div>
    </div>

    <span id="hpLeft2"></span><br />

    <button id="button" onclick="play()">Fight!</button>

  </div> <!-- End of div #center-->

Javascript:

window.onload = function() { 
   document.getElementById("hpLeft1").innerHTML= "<b>200/200</b>";
   document.getElementById("hpLeft2").innerHTML = "<b>200/200</b>";
};

var myHit = Math.floor(Math.random() * 40 + 1);
var dragonHit = Math.floor(Math.random() * 40 + 1);
var playerHitpoints, dragonHitpoints = 200;
var slaying = true;

Here is the function I want to call:

function play() { 


    document.getElementById("DragonHit").innerHTML = dragonHit;
    document.getElementById("MyHit").innerHTML = myHit;
}

Upvotes: 0

Views: 2916

Answers (2)

halkujabra
halkujabra

Reputation: 2942

Create the random values in your play() function man. You are just creating them once, so they are obviously going to stay the same.

Upvotes: 1

domdomcodecode
domdomcodecode

Reputation: 2453

You need to call the random functions again in your play() function. Currently you've set it so it only runs once when your myHit and dragonHit variables were declared.

function play() { 
    myHit = Math.floor(Math.random() * 40 + 1);
    dragonHit = Math.floor(Math.random() * 40 + 1);

    document.getElementById("DragonHit").innerHTML = dragonHit;
    document.getElementById("MyHit").innerHTML = myHit;
}

Upvotes: 4

Related Questions