skip to Main Content

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


  1. You should provide a function call (onclick‘s value should be a JS expression) in onclick‘s value:

    <div>
        <button onclick="onButtonClick()" id="myButton">Hit me.</button>
        <p id="randomQuote"> </p>
    </div>
    
    <script>
    
        var quote = ["S1","S2","S3","S4",  ];
    
        function onButtonClick() {
          var randomQuote = Math.floor(Math.random() * quote.length);
          document.getElementById("randomQuote").innerHTML = quote[randomQuote];
        }
    
    </script> 

    But a recommended way is to use addEventListener:

    <div>
        <button id="myButton">Hit me.</button>
        <p id="randomQuote"> </p>
    </div>
    
    <script>
    
        var quote = ["S1","S2","S3","S4",  ];
    
        document.getElementById('myButton').addEventListener('click', function() {
          var randomQuote = Math.floor(Math.random() * quote.length);
          document.getElementById("randomQuote").innerHTML = quote[randomQuote];
        });
    
    </script> 

    Also I would recommend to learn the modern JS from the beginning: const/let instead of var, arrow functions, etc.

    Login or Signup to reply.
  2. 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.

    const quote = ["S1", "S2", "S3", "S4"];
    
    const btn = document.getElementById('myButton');
    
    const getQuote = () => {
      let randomItem = quote[Math.floor(Math.random()*quote.length)];
      document.getElementById("randomQuote").textContent = randomItem;
    }
    
    btn.addEventListener('click', getQuote);
    <div>
      <button type="button" id="myButton">Hit me.</button>
      <p id="randomQuote"> </p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search