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

118
Views
addEventListener to all buttons using forEach

I am trying to addEventListener to all of my buttons. This is my first time using addEventListener and it is not running the usergetNumber function which should display a random number when any button is clicked.

const btns = document.querySelectorAll(".button");

btns.forEach(function(i) {
    i.addEventListener('click', usergetNumber(){
    });

function usergetNumber(){
    const userRanNum = Math.floor(Math.random() * 10)
    userscore_div.innerHTML = "You have " + userRanNum + " points";
    computergetNumber();

function computergetNumber(){
    const compRanNum = Math.floor(Math.random() * 10)
    computerscore_div.innerHTML = "You have " + compRanNum + " points";
}

What am I doing wrong?
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

From top to bottom.

  1. There's already a function usergetNumber() { ... } declaration in addEventListener(). It's a function declaration not a callback here. Ref: Event Listener Callbacks.
  2. The closing bracket on usergetNumber() { ... is missing so therefore it isn't declared.

Here's a basic example. You can also just return and not console.log. Here, I'm just trying to duplicate the logic.

const btn = document.querySelectorAll('button');
    
function getRandomNum() {
  let randomNum = Math.random();
  console.log(randomNum);
} 

btn.forEach(function(button) {
  button.addEventListener('click', getRandomNum);
});
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!