user2287793
user2287793

Reputation: 13

Preventing Focus event on Clicks

I have a web page with a bunch of div elements in it. This page runs on a TV which is connected to a very slow settop box. The box runs the embbeded Opera browser version 9.50. The only input device I have is the STB's Remote Control, No mouse! In this web page (on TV) the user navigates around using the arrow up/down/left/right keys on the remote to go from one div to another since there's no mouse. Now, I'm trying to "debounce" theses keypresses when someone is pressing them too quickly! I can control the keypress events but I'm not having any luck with preventing the focus events, it seems like they're fired regardless what I do in the keypress handler anyway.

The question is: how can I prevent focus from going to another element inside the keypress handler of the current element? Calling keypress event.preventDefault() and returning false (from the keypress handler) does not prevent the focus from shifting to the next element. In other words the event "bubbles up" anyway. How can I prevent that? I've played around with changing the tabIndex property too but it's no use.

Any ideas. Thanks.

Upvotes: 1

Views: 716

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

If you want to prevent focus from a click event, you have to e.preventDefault() from the mousedown handler. Can't do it from the click handler since that is not a physical event, it's just an abstraction of mousedown and mouseup

If you want to prevent tab from changing focus, you have to e.preventDefault() from the keydown handler. Can't do it from keypress, because keypress is not a physical event, it's an abstraction of keydown and keyup events (notice that keypress fires multiple times when you hold down the key).

http://jsfiddle.net/gtwhF/

$('#a').on('mousedown', function(e) {
    e.preventDefault();
})

$('#a').on('keydown', function(e) {
  if (e.keyCode == 9) { 
      e.preventDefault(); 
  } 
})

Upvotes: 2

Related Questions