Help with random quote machine challenge

Hello guys trying to random quote challenge and I could some help. I’m using fetch to get API data.

Now everything works fine when window loads but I wanted to make button to get new quote each time someone clicks on that button and I can’t get it to work.

This is my original code:

fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', {
  cache: "no-cache"
})
  .then(response => response.json())
  .then(function(data) {
    console.log(data);

    data.filter(key => {

      let quote = document.getElementById('quote');
      let author = document.getElementById('author');

      quote.innerHTML = key.content;
      author.innerHTML = key.title;

    });

  })
  .catch(function(error) {
    // If there is any error you will catch them here
    console.log(error);
  });

To make quotes load on click I have tried following:

const newQuote = document.getElementById('newQuote')
 newQuote.addEventListener('click', _ => {
   fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=', {
    mode: 'no-cors'
   })
    .then(response => response.json())
    .then(data => {
      data.filter(key => {
          let quote = document.getElementById('quote')
          quote.innerHTML = key.content
      })
    })
    .catch(err => console.error(err))
 })

So guys can I make it work with click event ?? Here is JSBin so you can better understand my problem: https://jsbin.com/qidudat/edit?html,js,output

That works great, I think similar approach at one point but could not get to work for some reason. Do you have any idea why my code is not working ?

Thank you very much for your help :slight_smile:

1 Like