简体   繁体   中英

Preventing browser from reacting to keydown-event, but without canceling the event

In my JavaScript I need to catch keyboard events.
However, when certain keys are pressed, the browser has a certain action like for example going to the previous page if backspace is pressed, or scrolling to the bottom of the page if the spacebar is pressed.

I can stop these browser-actions by for example catching the keydown event and call event.preventDefault() . However, if I call event.preventDefault() on the keydown event the keypress and keyup events never occur.

I need to be able to block default browser behavior for keydown events, and still catch the same keys when they are released. How can I do this?

However, if I call event.preventDefault() on the keydown event the keypress and keyup events never occur.

You didn't cancel the events themselves , you just cancelled the browser default actions (ie the default registered event handlers ) with preventDefault - which is exactly what you wanted - but you now want to specify your own keyup and/or keypress event handler , right? The events keyup and keypress are still there, it's just that they probably have no event handlers. Perfect! So now of course "nothing happens" - you took the default event handlers out like you wanted to for "keydown" event, and there were probably no other event handlers registered to the keyup and keypress events so there were no more actions (handlers) to fire anymore!

So from your same event keydown handler, right after you call event.preventdefault() , you can say $('#whatever').on('keyup',function(){console.log('key is up now')}) for example. I mean just bind keyup directly now from same keydown handler to whatever function you desire and I believe that when key goes up it should actually fire that function (ie event handler) that you bound to that event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM