@Ayman-Shakil192
Posted
Hey Galache👋!
Congratulations on successfully completing this challenge. Your solution looks amazing!
Now to answer you query , To generate new advice every time the button is clicked, you can modify the JavaScript code as follows:
const id = document.querySelector('h1');
const advice = document.querySelector('p');
const dice = document.querySelector('.dice');
function generateAdvice() {
fetch(`https://api.adviceslip.com/advice`)
.then(response => response.json())
.then(data => {
console.log(data.slip.id);
console.log(data.slip.advice);
id.textContent = `Advice #${data.slip.id}`;
advice.textContent = `"${data.slip.advice}"`;
})
.catch(error => console.error(error));
}
dice.addEventListener('click', generateAdvice);
// generate advice on page load (optional)
generateAdvice();
Here, we define a new function generateAdvice() that fetches advice from the API and updates the HTML with the new advice. We then attach this function to the button's click event listener.
Finally, we call generateAdvice() once when the page loads to generate the initial advice. This step is optional
With this modification, every time the button is clicked, a new advice will be fetched and displayed on the page.
Hope this helps. Do let me know if it works!
@Ayman-Shakil192 Hi, thanks for your response. I tried that way (putting the request in a function that is called every time the dice is clicked) before posting the solution to frontend mentor, for some reason it didn't work. Seeing your answer, I exactly copied the code but it doesn't work either. It always shows the same result 🤷♀️