6

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
vdhant
  • 2,218
  • 4
  • 24
  • 28

4 Answers4

10

The 'click' event will fire in both cases, this will get you what you want:

$('a').click(function(){
    alert('perform action here');
});
pjesi
  • 3,931
  • 3
  • 20
  • 16
3

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;
}
KyleFarris
  • 17,274
  • 5
  • 40
  • 40
1

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

RuudKok
  • 5,252
  • 2
  • 26
  • 27
-1
$('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.
Flexo
  • 87,323
  • 22
  • 191
  • 272
John
  • 1