Detect when link is activated - either by click or tab and enter
Question
Just wondering if anyone knows of a way that wiring up jquery to run a function for when a user clicks on a link or tabs to a link and hits enter.
I want to intercept that activation of a link and perform an action before the page is changed, but I want to do it in either case.
Solution
The 'click' event will fire in both cases, this will get you what you want:
$('a').click(function(){
alert('perform action here');
});
OTHER TIPS
It's pretty simple actually... When pressing enter on an element, it acts as a click in browsers. No need to do anything special.
$('a.links_to_bind').bind('click', function() {
/* do your stuff... */
return false;
});
Edit:
If you want the page to change after your actions are complete, you may want to add a conditional statemenet to that return false
. Something like:
if(everythings_good) {
return true;
} else {
return false;
}
The following two links provide information about the events in jQuery you want to handle.
jQuery Events/keypress: http://docs.jquery.com/Events/keypress
jQuery Events/click: http://docs.jquery.com/Events/click
$('a').keydown(function() {
return false; // Prevent default action
});
$('a').keyup(function(event){
if(event.keyCode == '13'){
$(this).find('button.mychoice').click();
}
});
// This does the trick for both IE and FF.