0

Is it possible to redefine event in JavaScript?

Example: if F12 key is pressed and the event occurs, I need the browser to process it as a Tab or a Space keyboard's key.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Max
  • 1,090
  • 10
  • 23
  • 1
    You want to change the key by which a function is triggered? Or am I misunderstanding? – David Thomas Aug 07 '12 at 11:45
  • You can preventDefault of keypress of F12 key. But in the way you want to do a Tab or Space you will need to emulate them by your own code. And simulation will depend on what you need in the current situation. – Flops Aug 07 '12 at 11:49
  • You could probably detect a `keypress` event, determine whether it was caused by the F12 key, and if so programmatically trigger a new `keypress` event representing the `tab` or `space` keys being pressed on the same element. – Anthony Grist Aug 07 '12 at 11:50

1 Answers1

3

Without testing to see if this works, this is along the lines of what I would try.

Essentially listen for a keydown event, and if the key pressed is F12, fire another keydownevent simulating tab.

$(document).keydown(function(event) {
  if(event.which == 123) { // Chrome code for F12 
    event.preventDefault(); // Stop the default actions for this event.
    var press = jQuery.Event("keydown"); // Create a new keypress event.
    press.ctrlKey = false; // No control key down
    press.which = 9; // Chrome code for tab
    $(document).trigger(press); // Fire the keypress event for tab
  }
});

I'm not sure if you can trigger keydown events on the document, that's just a guess as well.

Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • You can assume jQuery because the question has been tagged jQuery. – nalply Aug 07 '12 at 12:00
  • Thanks @nalply, I removed the jQuery comment. I realise that you can trigger keypress events, hence my answer. What I was aiming at is whether you can select the **document** and trigger the event, as opposed to selecting another element from the page. – Aesthete Aug 07 '12 at 12:08
  • Good point... If we only had more free time to check such subtle things instead of posting on StackOverflow ;-) – nalply Aug 07 '12 at 12:10
  • I already tried such solution but browser (Firefox) does not process it as "Tab" key – Max Aug 07 '12 at 12:27
  • Yeah I played around in jsFiddle and didn't quite get it either. I'm sure it can be done, just have to fiddle with it a bit more. From a few other articles, it seems `keypress` won't pick up those keys, whereas `keydown` is a bit more 'low-level` and should handle them. (I made adjustments to my answer to reflect this. I am still very wary about using **document** in the selector, I'm almost positive this is invalid. – Aesthete Aug 07 '12 at 12:34