March 14, 2012

Prevent keydown() from being captured by document binding

Question by Elliot Bonneville

I’m not exactly sure how to phrase this, so I couldn’t search it. Basically, I have a keydown() bind on $(document). I’d like to show() another div, and have all keydown events be rerouted to this div and prevented from firing off in the document handler. Is this even possible, or would I have to put all my main keybindings on another div and work from there?

Answer by Jeffrey Sweeney

e.stopPropagation, or
e.preventDefault (depending on the situation)
Where e is the event.

Ex:

function onKeyDown(e) {
   doStuff();
   e.preventDefault();
}

Answer by Starx

e.preventDefault() will prevent the default behaviour of an event. What you need is to use
e.stopPropagation(), so that the event does not bubble up the DOM structure.

To read more about the difference, read this post.

$(element).keydown(function(e) {
     // do the task
     // allow the default behaviour also
     e.stopPropagation();
   //^. BUT stop the even bubbling up right here
});

e.stopProgation(), can be bit confusing to grasp on the first but I created a demo with click event to explain it.

Hope it helps!!

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!