I am trying to create a button where every time you click, a new sentence generates from a list. What I have now is only generating a new sentence when I refresh the page and I’m not sure what to try. I only started learning yesterday so be nice to me please.
Here is what I have so far.
<div>
<button onclick="button" id="myButton">Hit me.</button>
<p id="randomQuote"> </p>
</div>
<script>
var quote = ["S1","S2","S3","S4", ];
var randomQuote = Math.floor(Math.random() * quote.length);
document.getElementById("randomQuote").innerHTML = quote[randomQuote];
</script>
2
Answers
You should provide a function call (
onclick
‘s value should be a JS expression) inonclick
‘s value:But a recommended way is to use
addEventListener
:Also I would recommend to learn the modern JS from the beginning: const/let instead of var, arrow functions, etc.
Use an event listener rather than an onclick attribute, then call your callback funtion in your event listener when you click the button.
Also you placed the button element in the HTML onclick call within your HTML. This answer here may also help out.