J. Doe
J. Doe

Reputation: 95

How to stop Keyup event from triggering twice

Console.log is printed twice. I have tried using e.stopPropagation(),e.preventDefault() and .stop(). It does not work. The console.log should trigger only once

$('html').keyup(function (e) {
    if (e.keyCode == 46) {
        console.log("delete press");
        e.stopPropagation();
        e.preventDefault();
    }
});

Upvotes: 0

Views: 5450

Answers (3)

Elish
Elish

Reputation: 476

Detaching the event with off() also works

 $('html').off('keyup').on('keyup',function (e) {
  if (e.keyCode == 46) {
    console.log("delete press");
    e.stopPropagation();
    e.preventDefault();
  }
});

OR

execute the event handler only once using one() as

$('html').one('keyup',function (e) {
if (e.keyCode == 46) {
    console.log("delete press");
    e.stopPropagation();
    e.preventDefault();
}

});

Upvotes: 0

Henry
Henry

Reputation: 86

I had a similar problem a while back. I ended up using $.unbind() and $.bind(). I would first call $.unbind() to remove any callback functions to the event that were potentially already bound to event. Then, I would call $.bind() on the event so it can do what I want it to do.

$('html').unbind('keyup');
$('html').bind('keyup', function (e) {

Upvotes: 5

Zach Leighton
Zach Leighton

Reputation: 1941

You probably need to debounce the event.

You can use something like lodash to do this easily, or you can roll your own if you want to learn how it works.

function handler(e) {
    if (e.keyCode == 46) {
        console.log("delete press");
        e.stopPropagation();
        e.preventDefault();
    }
}
$('html').keyup(lodash.debounce(handler, 250));

250 here is the number of milliseconds to debounce an event, also notice how the event is wrapped.

The documentation for all the options can be found here: https://lodash.com/docs/4.17.11#debounce

Upvotes: 0

Related Questions