I would like to detect a control key hit, without losing the user's current focus.
For example (see below) a user is writing something into a textarea, the textarea is the current element focused.
Then my end user moves his mouse on a div (just hovered, not clicked), and if he presses a control key I would like to execute a function (the keyDown
ones below).
To make it works I had to add a tabIndex
to my div
, and I had to uncomment the theDiv.focus()
line which makes me sad because it causes a loss of focus on my active textarea.
How can I simultaneously detect if someone hits a key when his mouse is on a specific element, without losing the current element's focus?
var theDiv = document.getElementById("theDiv");
function entered(e) {
theDiv.addEventListener("keydown", keyDown);
//theDiv.focus();
}
function keyDown(e) {
alert(e.key)
}
theDiv.addEventListener("mouseover", entered);
#theDiv {
width: 100px;
height: 100px;
border: 1px silver solid;
}
#theDiv:hover {
border: 1px silver dashed;
}
<div id="theDiv" tabindex="-1">
</div>
<div>
<textarea id="a">Click here, then hover the div above and hold "Shift" key</textarea>
</div>