Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 728
Daniel Avatar asked Oct 15 '25 15:10

Daniel


1 Answers

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!

like image 162
Runny Yolk Avatar answered Oct 17 '25 04:10

Runny Yolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!