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.
JavaScript
x
18
18
1
const btns = document.querySelectorAll(".button");
2
3
btns.forEach(function(i) {
4
i.addEventListener('click', usergetNumber(){
5
});
6
7
function usergetNumber(){
8
const userRanNum = Math.floor(Math.random() * 10)
9
userscore_div.innerHTML = "You have " + userRanNum + " points";
10
computergetNumber();
11
12
function computergetNumber(){
13
const compRanNum = Math.floor(Math.random() * 10)
14
computerscore_div.innerHTML = "You have " + compRanNum + " points";
15
}
16
17
What am I doing wrong?
18
Advertisement
Answer
From top to bottom.
- There’s already a function
usergetNumber() { ... }
declaration inaddEventListener()
. It’s a function declaration not a callback here. Ref: Event Listener Callbacks. - 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.
JavaScript
1
11
11
1
const btn = document.querySelectorAll('button');
2
3
function getRandomNum() {
4
let randomNum = Math.random();
5
console.log(randomNum);
6
}
7
8
btn.forEach(function(button) {
9
button.addEventListener('click', getRandomNum);
10
});
11