Reputation: 69
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?
Upvotes: 0
Views: 3288
Reputation: 66
From top to bottom.
usergetNumber() { ... }
declaration in addEventListener()
. It's a function declaration not a callback here. Ref: Event Listener Callbacks.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);
});
Upvotes: 2