tags:

views:

32

answers:

2

I have an event handler for the click event on an anchor. The event is fired both by clicking on the anchor and by the enter key when the anchor has the focus.

I wanted to know if the event was triggered by a click o by the enter key.

Thanks!

+1  A: 

I updated @patrick's demo using a bind with mouseup and keyup. When I used click instead of mouseup my message returned that I clicked when I actually pressed enter, but just the first time.

 $('a').bind('mouseup keyup', function(e){
  var msg = '';
  if (e.which == 13) {
   msg = 'enter pressed';
  } else if (e.which == 1) {
   msg = 'clicked';
  }
  alert( e.which + ': ' + msg );
  return false;
 })

Using e.which you will find that 1 = left mouse button, 2 = middle and 3 = right (I believe these numbers are right). So you can include all 3 if you need to.

fudgey
@fudgey - Cool. I didn't realize that `e.which` gave mouse button information. I guess I won't give you a hard time for not formatting your code (at first). ;o)
patrick dw
@patrick - It doesn't :) jQuery normalizes it a bit: http://github.com/jquery/jquery/blob/master/src/event.js#L468 and http://github.com/jquery/jquery/blob/master/src/event.js#L479
Nick Craver
@Nick - Very cool. Thanks for the note and links. :o)
patrick dw
A: 
$(document).ready(function(e) {
  $("a").keypress(function(e){
    if (e.keyCode==13) {
      alert('Enter!');
    }
  }).mousedown(function(){
    alert('Clicked!');
  });
});
Gert G
@Gert - Did you take the time to test this cross-browser?
patrick dw
Only Opera and Firefox. IE probably sucks... as usual... ;)
Gert G