Differentiate between mouse and keyboard triggering onclick

Could check if event.screenX and event.screenY are zero.

$('a#foo').click(function(evt) {
  if (evt.screenX == 0 && evt.screenY == 0) {
    window.alert('Keyboard click.');
  } else {
    window.alert('Mouse click.');
  }
});

Demo on CodePen

I couldn't find a guarantee that it works in all browsers and all cases, but it has the benefit of not trying to detect a "click" done via the keyboard. So this solution detects "click" more reliably at the cost of detecting if it's from keyboard or mouse somewhat less reliably. If you prefer the reverse, look as the answer from @Gonzalo.

Note: One place I found using this method is Chromium


You can create a condition with event.type

function submitData(event, id)
{
    if(event.type == 'mousedown')
    {
        // do something
        return;
    }
    if(event.type == 'keypress')
    {
        // do something else
        return;
    }
}

Note: You'll need to attach an event which supports both event types. With JQuery it would look something like $('a.save').bind('mousedown keypress', submitData(event, this));

The inline onClick="" will not help you as it will always pass that click event since that's how it's trapped.

EDIT: Here's a working demo to prove my case with native JavaScript: http://jsfiddle.net/AlienWebguy/HPEjt/

I used a button so it'd be easier to see the node highlighted during a tab focus, but it will work the same with any node.


You can use event.detail

if(event.detail === 0) {
    // keypress
} else {
    // mouse event
}