Better way to filter through quotes?

Hello, i’m using the quotes by design api and have it filtering to give me an array of 25. I want a different quote each time i click the new quote button. I was originally going to use a forEach but had trouble getting a new quote each time.

Now i tried to use a for loop but its giving me each quote in the array on the page, which is not ideal.

Here is my code:

//store buttons for later
let quoteBtn = document.getElementById('quote');
let shareBtn = document.getElementById('share');

//store output area
let html = '';
let output = document.getElementById('quoteReply');

//make call to quote api and output generated html
quoteBtn.addEventListener('click', function() {
  $.ajax('[orderby]=rand&filter[posts_per_page]=25', {
    dataType: 'json',
  success: function (res) {
    let randomNum = Math.floor(Math.random() * 25);
    let output = document.getElementById('quoteReply');
    let html = '';
    //loop over array with forEach
    for (var i = 0; i < res.length; i++) {
      html += "<p class='lead'>" + res[i].content + "</p>" + "<br>" + "<p>" + "- " + res[i].title + "</p>" + "<br>";
      //output html to page
      output.innerHTML = html;
    html = '';

//tweet a quote out
shareBtn.addEventListener('click', function () {
  let tweetLink = '' + output.innerText.replace(/[^\w\s-.,']/gi, "");
  //check if less than 140 characters
  if (output.innerText.length > 140) {
    alert('Your tweet cannot be longer than 140 characters.');
  } else {;

//link with button
//+ quote  

Possibly .map(), or a while loop. Any suggestions would be much appreciated?


Why loop over the array at all? You are generating a random number between 0 and 25. Why not just grab the quote by index?

Not sure that wasn’t clear to me beforehand. It’s what i essentially wanted to do, but thought i need a loop to over complicate it for some reason.

Anyhow. Thanks so much for your help! :slight_smile:

In my experience, that’s often a side effect of thinking and coding at the same time. :slight_smile:

1 Like