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

111
Visualizações
Picking random elements from array on click event not working

I have written some question generator functions which work fine. Then put those functions in an array, when the user clicks the new question button it is supposed to pick a random question type from the array, but it is only randomising when I load the page rather than click the button. Thanks in advance.

let questionArray =[questionTypeZero, questionTypeOne];
function questionSelector(){
   return questionArray[Math.floor(Math.random()*2)]
};
window.addEventListener('load', questionSelector());
newQuestion.addEventListener('click', questionSelector() );
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you have to change this line:

newQuestion.addEventListener('click', questionSelector() );

has to be this way:

newQuestion.addEventListener('click', questionSelector);

doing the way you did is like: in the moment when JS goes in taht line of code it will call the function because of the (), on the way I suggest it will be called when the event.

also in this line of code

window.addEventListener('load', questionSelector());

havo to remove the (), because is callign the function when JS engine is in that line of code, NOT when the window is loaded.

Im not sure about the event of 'load' in that case I usually use 'DOMContentLoaded'

mu line of code will be like this:

window.addEventListener('DOMContentLoaded', questionSelector);
about 4 years ago · Juan Pablo Isaza 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