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=".3.1/jquery.min.js"></script>
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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Share
Improve this question
asked Aug 9, 2019 at 21:33
ConsoleLogConsoleLog
5113 silver badges14 bronze badges
7
- 1 Well, i mean, pressing a key causes the button to click, right? So that's both a click and a key press. But a mouse click is not a keypress. It doesn't involve the keyboard at all. – Taplar Commented Aug 9, 2019 at 21:36
-
1
As you mentioned
e.preventDefault()
resolves the issue - that means it is a default browser behaviour to trigger a click event on a focused item when the 'enter' button is pressed. If you notice, when you press keys other than 'enter' it will only triggers the 'keypress' event – ajai Jothi Commented Aug 9, 2019 at 21:41 - @ajaiJothi Thanks for the reply - both enter and spacebars fire the event? – ConsoleLog Commented Aug 9, 2019 at 21:45
- Thanks @Taplar for the explanation - wasn't aware that keypress is treated as a click as well. – ConsoleLog Commented Aug 9, 2019 at 21:47
- 1 It's not that keypress is treated as a click. It's that the user interaction causes the element to be "clicked". If you had focus on a link and hit enter, it would also generate a click event for the link. The important part being what element you are interacting with when the key event happens. – Taplar Commented Aug 9, 2019 at 21:51
1 Answer
Reset to default 9On 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.