Dan Dan - 3 months ago 16
HTML Question

HTML how to make a button output random text

I need help. Can someone help me make a button (HTML) that when you press it will display different text. For example if I press it it has a 50% chance to say "Hello" and a 20% chance to output "Whats up" etc...
Thanks!

Answer

Have fun!

<html>
  <script>
    // Greetings
    var words = ['Hello', 'Hey', 'What\'s up!?'];

    function randomAlert() {

      // Index for picking the greeting you want to show
      var alertIndex;

      // Generates a number between 0 and 1
      var randomValue = Math.random();

      // 50% chance of 'Hello'
      if (randomValue < 0.5) {
        alertIndex = 0;
      }

      // 30% chance of 'Hi'
      else if(randomValue < 0.8) {
        alertIndex = 1;
      }

      // 20% chance of 'What's up!?'
      else {
        alertIndex = 2;
      }

      alert(words[alertIndex])
    }
  </script>
  <button onClick="randomAlert()">Click me!</button>
</html>

Comments