Search code examples
javascriptonclickmouseeventkeypress

Differentiate between mouse and keyboard triggering onclick


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?


Solution

  • 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.