dimanche 15 mai 2016

Stupid simple Random Code Generator - JS/CodePen

I'm working on a programming challenge. I am a noob. I'm building it in CodePen, which for the uninitiated, has separate HTML, CSS, and JS sections per "pen" (or coding project environment). I'm not sure if it's not working because of CodePen intricacies, or what is more likely, my code.

The task is simple, have a button, that when clicked, displays a random quote. I have already built a JSON object to store my quotes and have built a function to randomly select and print a quote from the object.

The HTML snippet - button (Bootstrap etc.)

<div class="row" id="quotebox">
  <div class="text-center">
      <button class="btn btn-default" onclick ="randomQuote()"type="submit">Hit Me Baby One More Time</button>
  </div>
</div>

The JSON object storing 5 quotes

    var quotesList = [{quote:"Planting popcorn does not produce more popcorn", 
  person: "Farmer Ted"},
  {quote: "White whale, bad whale",
  person: "Confucious (Moby Dick)"},
  {quote: "Use the strobe function to disorientate your attacker", 
   person:"Flashlight"},
  {quote: "Apply liberally to your erogenous zones", person: "Spice Bomb"},
  {quote: "Help me, I'm bleaching", person: "The Great Barrier Reef"}];

Finally, the function to print the random quote (triggered by onClick)

function randomQuote(){
 var listLength =  Object.keys(quoteList).length;
  var randVal = Math.floor(Math.random() * listLength);
  document.write(quotesList[randVal]);
}

I'm not sure whether in CodePen, I need to enclosed the JS code in tags or not.

The JS code in it's entirety as shown in CodePen

var quotesList = [
  {quote:"Planting popcorn does not produce more popcorn", 
  person: "Farmer Ted"},
  {quote: "White whale, bad whale",
  person: "Confucious (Moby Dick)"},
  {quote: "Use the strobe function to disorientate your attacker", 
   person:"Flashlight"},
  {quote: "Apply liberally to your erogenous zones", person: "Spice Bomb"},
  {quote: "Help me, I'm bleaching", person: "The Great Barrier Reef"}];

function randomQuote(){
 var listLength =  Object.keys(quoteList).length;
  var randVal = Math.floor(Math.random() * listLength);
  document.write(quotesList[randVal]);
}

Thanks all




Aucun commentaire:

Enregistrer un commentaire