Search code examples
javascriptgoogle-chrome-extensiondom-eventsmouseeventonclicklistener

Event vs MouseEvent


I'm writing a chrome extension and I want to do something when shiftKey is pressed while clicking on an item. I know how to get the shiftkey:

event.shiftKey

But the problem is sometimes the event object passed to the click handler is of type Event and sometimes it's of type MouseEvent and there is no property of shiftKey when the event is of type Event.. This is when I add the eventListener:

elemet.addEventListener('click', handleOnClick);

Here is the handleOnClick function:

function handleOnClick(event) {
    console.log(event);
    if (event.shiftKey) {
        // do something
    }
}

Here is what I see in chrome console: Sometimes:

Event {isTrusted: false, type: "click", ...}

And the if statement is not executed in this case even when the shift key is pressed.

Sometimes:

MouseEvent {isTrusted: true, screenX: -1611, screenY: -91, clientX: 766, clientY: 90, …}

if statement is executed in this case when the shift key is pressed.

Can anyone help please?


Solution

  • Posting this in case someone else runs into the same problem. I fixed this by doing element.onmousedown = handleOnClick; instead of element.addEventListener('click', handleOnClick);. Now the event passed to handleOnClick is always MouseEvent and I can do event.shiftKey.