Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
function works on page load but not on button click

I'm trying to get my web app to run when clicked but it only works when the page is initially loaded. If I keep pressing f5 it will select an item randomly and work correctly. But I'd like for it to do so when the 'next' button is pressed.

I'm attempting to change the 'locationTitle' id to a random item from myArray.

When I open up the developer tools and click on the 'NEXT' button, it flashes on the 'locationTitle' value of the div.

let myArray = [
    'Boardwalk', 
    'Highland Park', 
    'Waterfront',
    'Beach', 
    'North End', 
    'Canal',
    'Wiley Island', 
    'Conservation Park', 
    'Dufferin Falls',
    'Old Town',
]

const random = Math.floor(Math.random() * myArray.length);
console.log(myArray[random]);

let my_btn = document.getElementById("my_btn");

function nextElement() {
    document.getElementById("locationTitle").innerHTML = (myArray[random]);
    

}


window.addEventListener("load", nextElement);
my_btn.addEventListener("click", nextElement);


html:
<button id = "my_btn" onclick = "nextElement()" ;>NEXT</button>
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

It seems the function is being called every time you click the button, but you choose your random value once at the beginning of the script and use the same value each time.

If you move the random value selection into the function, so that the function reads as follows, you should see it change to a different value each time:


...

function nextElement() {
    const random = Math.floor(Math.random() * myArray.length);
    document.getElementById("locationTitle").innerHTML = (myArray[random]); 
}

...
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda