dimanche 22 novembre 2015

Getting a random word to display on page load with Javascript

I'm trying to make a random word generator where, when you click a button, a random word appears. I've managed to get this to work, but would also like one of the random words to appear when the page loads (so that it's not just a blank page).

Thanks!

Javascript

var randomStrings = [
    "hello 1",
    "hello 2",
    "hello 3", 
    "hello 4",
    "hello 5",
];



var randomDiv = document.getElementById("myRandomDiv");

document.getElementById("myButton").addEventListener("click", function() {
      randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
      newText = randomStrings[randomIndex];
      randomDiv.innerHTML = newText;
});

HTML

  <!doctype html>
  <html>

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brandomiser</title>
    <link href='http://ift.tt/1PTUHMF' rel='stylesheet' type='text/css'>
    <link href="main.css" rel="stylesheet" type="text/css">
    <link href="/downloads/favicon.ico" />
  </head>

  <body>
  <div class="row">
    <div id="bar" class="col-12 col-t-12 col-d-12 col-b-12">
      <p id="brand">Brandomiser</p>
    </div>
  </div>

  <div class="row">
    <div class="col-12 col-t-12 col-d-12 col-b-12">
      <h1 id="myRandomDiv"></h1>
    </div>
  </div>

  <div class="row">
    <div id="buttonmiddle" class="col-12 col-t-12 col-d-12 col-b-12">
      <button type="button" id="myButton">Hit me.</button>
    </div>
  </div>
  <script src="thing.js"></script>
  <script src="http://ift.tt/1LdO4RA"></script>
  </body> 
  </html>       




Aucun commentaire:

Enregistrer un commentaire