jared-dev
jared-dev

Reputation: 131

Why addEventListener returns undefined?

This is the code: let rockClick = rockBtn.addEventListener('click', playRound.bind("rock", computerPlay(), false));

I console.log and it returns undefined. The rockBtn:const rockBtn = document.querySelector("#rock"); should select the button with the id of #rock and when I click the button it should run the playRound function with "rock" as its first parameter and computerPlay() as the second. The playRound function plays a single round of rock paper scissors.

When I click the rock button, nothing happened so I put the rockBtn.addEventListener to a variable and console.log() it, and it returns undefined. Why is this happening? What should I do?

Here's the fiddle: https://jsfiddle.net/JaredDev/8syrwfm9/48/

Upvotes: 0

Views: 231

Answers (1)

Mina
Mina

Reputation: 17159

There are some mistakes in your code

  1. bind() method, accept first argument this context, then the function parameters

  2. I'm not sure what do you expect from returning a value from addEventListener, but yes it is void method, it returns undefined

  3. If you want call playGround on rockBtn click, all you need is

const rockBtn = document.querySelector("#rock");

rockBtn.addEventListener('click', () => {
        playRound("rock", computerPlay(), false)
    });

This is working fiddle of the example.

https://jsfiddle.net/h306pudt/

Upvotes: 2

Related Questions