2

I'm currently trying to learn more about event listeners. Inside an IIFE, I have the following code:

function display(){
console.log('itemAdded');
}

document.querySelector('.add__btn').addEventListener('click',display);

document.addEventListener('keypress',function(event){

   if(event.which == 13 || event.keyCode == 13){ //if 'enter' is pressed
      display();
   }

});

What I'm trying to achieve is running the display function either by clicking the button with the right class or by hitting the enter key.

I pressed Enter, 'itemAdded' appears in console. I hit the button with the class .add__btn, 'itemAdded' appears again in console. Now when I click Enter again, it generates 2 'itemAdded' in the console.

I ran further tests, and found out that once I click the button with .add__btn class, the Enter key starts to generate 2 'itemAdded' texts:

console.log

'itemAdded' <- Generated by hitting Enter
'itemAdded' <- Generated by clicking
'itemAdded'
'itemAdded' <- 3rd and 4th were generated by a single hit of the enter button.

Can anyone help me understand why the Enter key generates 2 'itemAdded'?

Stephen King
  • 581
  • 5
  • 18
  • 31
Jp Arcilla
  • 83
  • 1
  • 1
  • 8

0 Answers0