Martin Suchan – BloQ Random #WPdev stuff

15Feb/111

Disabling key down event propagation in JavaScript

Imagine this non-trivial problem: you have div element with overflow: auto; and long text inside. The scrollbar appears automatically. Normally when the div is focused pressing keys Up or Down causes moving the content up or down. But what if you don't want to scroll the content on keydown event?

This is rather non-trivial issue, because automatic scrolling of the div is browser-specific behavior. I've search several article and guides, but only one approach worker. Forget about setting tabIndex="-1" or using things like element.blur() for losing focus, it 's no use using these.

The solution is using the method event.preventDefault(); This call prevents executing default action binded to the event, in this case keydown. preventDefault() method is supported in several browser by default, but it is also included in jQuery library. The method from jQuery should work in all major browsers without problem. Just a last note - keep in mind that preventing all key events in propagating is not a great idea - it would disable behavior like F5 for refresh, F1 for help and other common shortcuts. Use check against pressed key code and use this method only on keys you don't want to propagate further.

Original source of this idea: http://forums.smartclient.com/showthread.php?t=6596