Home > OS >  How to create a randomized quote generator?
How to create a randomized quote generator?

Time:12-19

I'm building a positive affirmation generator and would like some input. I'm trying to figure out how to generate quotes. I already written down the Math.random. Here's some code.

function newQuote() {
  var randomNumber = Math.floor(Math.random() * (positiveAff.length));
  document.getElementById(affirmations).innerHTML = positiveAff[randomNumber];
}
<body>
  <h1>Positive Affirmations Generator</h1>

  <div id="affirmations">

  </div>
  <button onclick="newQuote()">Click to change affirmations</button>


  <script src="script.js"></script>
</body>

CodePudding user response:

My answer is by assuming you will have an array of quotes.

const positiveAff = [
{ id: 1, quote: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, dolores!" },
{ id: 2, quote: "consectetur adipisicing elit. Velit, dolores!" },
{ id: 3, quote: "amet consectetur adipisicing elit. Velit, dolores!" }]

const button = document.getElementById('button')

button.addEventListener("click", function () {
  newQuote()
})
function newQuote() {
  var randomNumber = Math.floor(Math.random() * (positiveAff.length));
  document.getElementById("affirmations").innerHTML = positiveAff[randomNumber].quote;
}
<h1>Positive Affirmations Generator</h1>
<div id="affirmations"></div>
<button id="button">Click to change affirmations</button>

CodePudding user response:

Based on your snippet, the problem is not your code to get the quote. The issue was how you wrote it. In document.getElementById(affirmations) you use affirmations as a variable, which is never defined. I changed it to a string, and added an array, and now it works.

   positiveAff = [
  "Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, dolores!",
  "consectetur adipisicing elit. Velit, dolores!",
  "amet consectetur adipisicing elit. Velit, dolores!"
]

function newQuote() {
  var randomNumber = Math.floor(Math.random() * (positiveAff.length));
  document.getElementById('affirmations').innerHTML = positiveAff[randomNumber];
}
<h1>Positive Affirmations Generator</h1>
<div id="affirmations"></div>
<button onclick="newQuote()">Click to change affirmations</button>

  • Related