Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda