Reputation: 23
I'm trying to display either heads or tails when a button is clicked. I'm not sure where I'm going wrong. It seems like a pretty simple thing to do but maybe I'm missing something? Here is what I have.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9</title>
<link href="images/avatar.png" rel="shortcut icon" type="image/png">
<link href="css/stylesheet.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" type="text/javascript"></script>
<style type="text/css">
.auto-style1 {
text-align: center;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<header>
</header>
<aside>
</aside>
<div id="main">
<h1> Arrays and Coditional Statements</h1>
<h2 class="auto-style1"> Quote of the Day</h2>
<h2 class="auto-style1">Flip a coin </h2>
<script>
<script>
function myFunction1{
var x =Math.floor(Math.random()*2);
if ( x==0){
document.getElementById("Coin").innerHTML= "Heads";
}
else{
document.getElementById("Coin").innerHTML= "Tails";
}}
myFunction1();
</script>
<button type="button" onclick="myFunction1" id="Coin"> CLick ME</button>
</div>
<footer>
</footer>
</body>
</html>
Upvotes: 1
Views: 4890
Reputation: 9172
You can use this single line of JavaScript to get either heads
or tails
console.log(Math.random() >= 0.5 ? "heads" : "tails")
Upvotes: 3
Reputation: 36438
A few things:
script
tag just below the one that's actually needed()
on your onclick
call - onclick="myFunction1()"
()
on your function definition: function myFunction1() {
myFunction1()
, your Coin
element does not yet exist - put the script after that element's creation, or in a window.onload
handler.Putting those fixes together:
<button type="button" onclick="myFunction1()" id="Coin">CLick ME</button>
<script>
function myFunction1() {
var x = Math.floor(Math.random() * 2);
console.log(x);
if (x == 0) {
document.getElementById("Coin").innerHTML = "Heads";
} else {
document.getElementById("Coin").innerHTML = "Tails";
}
}
myFunction1();
</script>
The JavaScript console would have told you about these problems, one-by-one, as you solved them. I recommend getting familiar with it.
Upvotes: 0
Reputation: 2206
Here is the solution:
Assignment 9 .auto-style1 { text-align: center; }
<h2 class="auto-style1"> Quote of the Day</h2>
<h2 class="auto-style1">Flip a coin </h2>
CLick ME
myFunction1();
function myFunction1() {
var x =Math.floor(Math.random()*2);
if ( x==0){
document.getElementById("Coin").innerHTML= "Heads";
}
else{
document.getElementById("Coin").innerHTML= "Tails";
}
}
</div>
<footer>
</footer>
</body>
</html>
Upvotes: 0
Reputation: 780994
You're not calling the function in your onclick
attribute, you're just naming it. Functions are called by putting ()
(to enclose the arguments) after the function name. So it should be
onclick="myFunction1()"
Upvotes: 1