Daniel
Daniel

Reputation: 3711

Detect key event while mouse over DOM element

I know how to detect key events on the document. I also know how to detect mousemove events in a DOM element.

But I don't know how to detect a key event when it happens with the mouse over an element and the mouse it not moving.

I guess I could set a boolean that will set to true by mousemove an to false by mouseout on the DOM element. But is there a more proper way to do this?

I have found a question that is directly relevant but unanswered (and the comments don't really help):

Detect shift key while already over element

Upvotes: 4

Views: 1205

Answers (1)

Runny Yolk
Runny Yolk

Reputation: 1164

Here's an expansion of my comment above.

Using vanilla JavaScript you can set event listeners on an element for onmouseover and onmouseleave. These event listeners toggle a boolean variable, which is just a flag to say whether the mouse if currently over the element or not.

Then add another event listener on the window for key presses. On key press, if our boolean is true, then run your code, if it's not, do nothing.

var mouseOn = false;

document.getElementById('div').onmouseover = function() {
    console.log('mouseover');
    mouseOn = true;
}

document.getElementById('div').onmouseleave = function() {
    console.log('mouseleave');
    mouseOn = false;
}

window.onkeypress = function(e) {
    if(mouseOn == true) {
    console.log(e.key)
  }
}

Here's the fiddle: https://jsfiddle.net/6wpeLbx9/ (note: the window object in the fiddle is just the panel containing the red square - in order for key presses to be noticed you first have to click on the panel to focus it)

I'm sure my code can be more concise...

Hope that helps!

Upvotes: 3

Related Questions