ConsoleLog
ConsoleLog

Reputation: 511

Enter key fires both click event and keypress when multiple events are attached to button

I have two events attached to a button and when I press a key while the button is on focus both keypress and click events are fired. However, if I click the button only the click event is fired. By adding e.preventDefault() seems to fix the issue but I want to understand why it's behaving that way in the first place. Apologies if this is a duplicate but I couldn't find a relevant answer apart from this one but the explanation isn't clear enough there. Many thanks.

$('.btn').on('click keypress',function(e){
  console.log(e.type);
});
<button type="button" class="btn" >click me</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 6

Views: 4930

Answers (1)

aa-Ahmed-aa
aa-Ahmed-aa

Reputation: 382

On button focus

if you pressed any key except (space and enter) only the keypress event will fire

But

if you focus the button and press space or enter this will fire both the events because this is a browser default behavior also for this same reason e.preventDefault() solved the problem for you.

Upvotes: 9

Related Questions