Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Why are there two event listeners? There should be one

I opened the Developer Tools in Google Chrome, pasted the following code in console and pressed Enter:

Code:
document.removeEventListener(`keypress`, a1);
document.addEventListener(`keypress`, a1);
function a1(event){ 
    console.log(`I should have been called only once`);
}
Then I pressed some key and the console printed the following:

I should have been called only once

Then I pasted and entered the above-mentioned code ONCE AGAIN. And then pressed some key. Now the console printed the following:

I should have been called only once
I should have been called only once

But why? When I entered the code for the first time it added the event listener "a1". When I entered the code for the second time it should have removed the event listener "a1" and then added the event listener "a1". I.e. there should be ONE event listener. Why are there two?
 
The issue seems to be that you declared the function a1 twice. If you do not do that (that is: the second time, ONLY enter the first two lines), it works correctly.
 
Back
Top Bottom