Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  33] [ 7]  / answers: 1 / hits: 31792  / 9 Years ago, sun, august 30, 2015, 12:00:00

I need help fixing my script. Basically, I want it to flip a coin and update a <span> with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button.



JavaSript:



var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip(heads);
}else{
flip(tails);
}
};
function flip(coin) {
document.getElementById(result).innerHTML = coin;
};


HTML:



<button id=click type=button>CLICK ME</button>
<p>
You got: <span id=result></span>
</p>



More From » html

 Answers
14

That's simply because you need to attach the event handler:





document.getElementById('click').onclick = click;

var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip(heads);
}else{
flip(tails);
}
};
function flip(coin) {
document.getElementById(result).innerHTML = coin;
};

<button id=click type=button>CLICK ME</button>
<p>
You got: <span id=result></span>
</p>




[#65248] Thursday, August 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;