Key event detection when mouse is over DOM element

I know how to detect key events on document

. I also know how to detect events mousemove

on a DOM element.

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

My guess is that I could set a boolean to be set to true using mousemove

an to false using an mouseout

on the DOM element. But is there a better way to do this?

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

Detect shift key when already over element

+3


source to share


1 answer


Here's an extension 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 tell if the mouse is currently over the element or not.

Then add another event listener to the window for key presses. On key press, if our boolean is true then run your code, if 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 - ok for keystrokes to be noticed, you have to click on the panel first to focus it).

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

Hope it helps!

+1


source







All Articles