Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
How to create a randomized quote generator?

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>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!