Search code examples
javascripthtmldom-eventsmouseevent

Javascript onclick event doesn't work after the first click - random quote generator


I'm building a random quote generator, when I click the 'get a quote button' it generates one of the quotes randomly, but after the first click it doesn't provide more sentences when clicked again.

hHere is my code:

html:

<h1>Random Quotes</h1>
<p>Press The below button to read a random quote</p>

<p id="demo"></p>
<div class="button" onclick="loopQuotes()">Get a quote</div>
<script type="text/javascript">
            
</script>

Javascript:

var quotes = [("Quote 1"), ('quote 2'), ('quote 3'), ('quote 4')];

var length = quotes.length;
var rand = Math.round(Math.random() * (length - 1));

function loopQuotes(){
    for (var i = 0; i < quotes.length; i++ ) {
        document.getElementById('demo').innerHTML = quotes[rand];
    }
} 

Can someone kindly check and advise?


Solution

  • As someone has already pointed out, your rand value is not getting generated again. Since you call loopQuotes methods which doesn't have the logic of generating rand again.

    Try

    function loopQuotes()
    {
      var rand = Math.round(Math.random() * (length - 1));
      document.getElementById('demo').innerHTML = quotes[rand];
    }