Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!