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('https://quotesondesign.com/wp-json/posts?filter[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 = 'http://twitter.com/home/?status=' + 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 {
window.open(tweetLink);
}
});
//link with button
//url: https://twitter.com/intent/tweet?text=
//+ quote
Possibly .map(), or a while loop. Any suggestions would be much appreciated?
Thanks!