DEV Community

loading...
Cover image for When to use Keyup or Keypress in Javascript

When to use Keyup or Keypress in Javascript

urielbitton profile image Uriel Bitton ・2 min read

Eventhough the differences between keyup and keypress in javascript may seem insignificant, it can cause damaging consequences when not used appropriately.

Keyup and keypress are javascript functions that allow you to execute an action when a specified key is pressed. But what are the actual differences between keyup and keypress?

Difference

The keypress function executes code when a specified key is detected to be pressed. The keyup function activates when you release that key. So with keypress it detects as the key is being pressed down, while keyup is not detected when you press the key but when you release it.
You may say, so what? There's no difference both instances will result in the key being pressed and the action being executed.
This is only partially true and this fact can cause unwanted consueqneces in your app.

The Problem

To udnerstand why we'll demnstrate with a simple example. Say we want to append an element to our page when we press the enter key with a keypress function. Here's our code:

$('input').on('keypress', function(e) {
    var enter = e.keyCode || e.which;
    if(enter == 13){
        $('body').append($(this).val());
    }
});

Enter fullscreen mode Exit fullscreen mode

What will happen here is if the user unintentionally presses the key twice or holds on to the key for too long, the content that we wanted to append to our page will be appened twice or more. This is undesired.

So what can we do to fix that, so no matter how many times the user presses enter, the content is appended only once to our page? (if that is what we desire - sometimes we want to append as many times as user presses enter, but in most cases we don't).

Solution

The solution is using keyup.

Let's modify our code slightly to achieve this:

$('input').on('keyup', function(e) {
    var enter = e.keyCode || e.which;
    if(enter == 13){
        $('body').append($(this).val());
    }
});

Enter fullscreen mode Exit fullscreen mode

Now if the user presses enter and holds on to the key a little too long, the content will only be appended once.
If we program our form to dissappear after the user hits the enter key, then no matter how many times the user presses enter, the content will only be appended once, which is what we desire in most cases (i'll venture to say).

So there you have it, the difference between keyup and keypress. Use keyup for single action execution and keypress for executing actions everytime the user hits the desired key.

Hope you enjoyed this one.

See you un the next one!

Discussion (0)

Forem Open with the Forem app