views:

46

answers:

3

I'm using jQuery focus() and blur() to highlight image links during keyboard navigation (tabbing) but need to be able to run some code when a link is followed via 'Enter' on the keyboard.

Is there a built in event which does this or do I need do something like bind keypress and check for the 'Enter' key?

+2  A: 
<a href="http://www.google.com" id="testlink">CatchMe</a>

$('#testlink').attr("rel", $('#testlink').attr("href"));
$('#testlink').attr("href","");
$('#testlink').keydown(function(event) {
    if (event.keyCode == '13') {
        alert("Don't you dare!");
    }
    if (event.keyCode == '71') {
        location.href=$('#testlink').attr("rel");
    }
});

This code removes the href (stores it in rel). Now you can catch the keydowns. You can respond to the enter key (13) however you like (alert in this case). Afterwards you can let the browser follow the link after all, if you want. In this example however, I only let the browser follow the link when the 'g' key (code 71) is pressed.

Note that this also works when the href value is like 'javascript:alert("blah")'.

Edit: this is a lot easier however (inspired by the answer to this question):

$('#testlink').click(function () {alert("hi"); return false; });

(return true if you do want the link to be followed after the alert)

Jochem
I guess this means there's no specific 'onEnter' type event, but .keydown(function(event) { if (event.keyCode == '13') { } works fine. Thanks
pelms
No problem. (Btw: onEnter does not exist as far as I know. However the click event seems to respond to a keyboard-induced-link-activation, as long as you return true or false in the event handler function)
Jochem
You can create your own event by using $.trigger() -- take a look at http://api.jquery.com/trigger/
thomasmalt
A: 

Look at the following:

focusin

focusout

Also, if you are entering the key handling scene, than please read quirksmode

Final link is very important because every browser is special in its own way, i.e. some events get ignored, some get fired off when you don't expect them to.

vikp
A: 

To elaborate on the reply by Jochem. You can use .trigger() to create your own events like this:

$('#testlink').keydown(function(event) {
    if (event.keyCode == '13') {
        // alert("Don't you dare!");
        $('#testlink').trigger('enterdown');
    }
});

and also:

$('#testlink').bind('enterdown', function(event) {
    alert('Enter was pressed.');
});
thomasmalt