Search code examples
javascriptloopsbuttonforeachinfinite

Button stops after first click


const btnEl = document.getElementById("btn")
var taraEl = document.getElementById("tara")
var capitalaEl = document.getElementById("capitala")
const rezultatEl = document.getElementById("rezultat")

let randomNr;

randomNr = Math.floor(Math.random() * 251)

btnEl.addEventListener("click", async function(){
    try {
        const response = await fetch("https://restcountries.com/v3.1/all");
        const data = await response.json();
        rezultatEl.style.display = "block"
               
        taraEl.innerText = data[randomNr].name.common;
        capitalaEl.innerText = data[randomNr].capital;
        
    } catch (error) {
        console.log("error");
    }
})

Any idea how can I made the button brings another's data, without refreshing the page?
Now after I press the button, one time, the generator button is inactive.

I want to press the button and get another country, also capital, but without refreshing the page.


Solution

  • You only generate the random number once, when your JS first runs after the page is loaded. So it will be the same every time the button is clicked - resulting in no visible change to your page. To get a new random number each time, move these lines of code:

    let randomNr;
    
    randomNr = Math.floor(Math.random() * 251)
    

    (which by the way could just be one line: let randomNr = ...) inside your event handler function:

    btnEl.addEventListener("click", async function(){
        try {
            const response = await fetch("https://restcountries.com/v3.1/all");
            const data = await response.json();
            let randomNr = Math.floor(Math.random() * 251);
            rezultatEl.style.display = "block"
                   
            taraEl.innerText = data[randomNr].name.common;
            capitalaEl.innerText = data[randomNr].capital;
            
        } catch (error) {
            console.log("error");
        }
    });
    

    (using a hardcoded 251 to generate your random number is a bit weird too. Presumably that's the length of the data array but it's better just to write it as data.length, which you couldn't do in your first version - data is unknown at the point it runs - but you can in the above version.)