KEYPRESS (enter key)
Click inside the snippet and press Enter key.
Vanilla
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
alert('hi.');
}
});
_x000D_
Vanilla shorthand (ES6)
this.addEventListener('keypress', event => {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
jQuery
$(this).on('keypress', function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
jQuery classic
$(this).keypress(function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
jQuery shorthand (ES6)
$(this).keypress((e) => {
if (e.keyCode == 13)
alert('hi.')
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Even shorter (ES6)
$(this).keypress(e=>
e.which==13?
alert`hi.`:null
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Due some requests, here an explanation:
I rewrote this answer as things have become deprecated over time so I updated it.
I used this
to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.
Deprecated:
The .which
and .keyCode
methods are actually considered deprecated so I would recommend .code
but I personally still use keyCode as the performance is much faster and only that counts for me.
The jQuery classic version .keypress()
is not officially deprecated as some people say but they are no more preferred like .on('keypress')
as it has a lot more functionality(live state, multiple handlers, etc.).
The 'keypress'
event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown today. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)
All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.
Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress')
, this is the way to go and understandable by most people.
Performance:
I always follow my phrase Performance over Effectiveness as anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode
even if it's considered deprecated(in most cases). It's all up to you though.