I need to find a way to determine if a link has been activated via a mouse click or a keypress.
<a href="" onclick="submitData(event, '2011-07-04')">Save</a>
The idea is that if they are using a mouse to hit the link then they can keep using the mouse to choose what they do next. But if they tabbing around the page and they tab to the Save link, then I'll open then next line for editing (the page is like a spreadsheet with each line becoming editable using ajax).
I thought the event parameter could be queried for which mouse button is pressed, but when no button is pressed the answer is 0 and that's the same as the left mouse button. They I thought I could get the keyCode from the event but that is coming back as undefined so I'm assuming a mouse event doesn't include that info.
function submitData(event, id)
{
alert("key = "+event.keyCode + " mouse button = "+event.button);
}
always returns "key = undefined mouse button = 0"
Can you help?
You can differentiate between a click and a keyboard hit capturing and discarding the keydown event originated at the moment of the key press:
http://jsfiddle.net/NuP2g/
Handle the
mouseup
event.If you get a
click
right afterwards, it was probably done with the mouse.Could check if
event.screenX
andevent.screenY
are zero.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
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.