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!
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!
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.
$(document).ready(function(e) {
$("a").keypress(function(e){
if (e.keyCode==13) {
alert('Enter!');
}
}).mousedown(function(){
alert('Clicked!');
});
});