2

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>
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
Fractaliste
  • 5,777
  • 11
  • 42
  • 86
  • Don't you ask the same thing? https://stackoverflow.com/questions/18108205/how-to-detect-a-keypress-and-a-mouseover-at-the-same-time – Kamran Poladov Aug 23 '18 at 14:24
  • Why don't you just check if the mouse is inside the div when the user presses the defined key? Update a variable when mouse enters div (also when mouse laves) so when user presses key, check that var and do what you need – Huangism Aug 23 '18 at 14:26

1 Answers1

2

You can add mouseover event listener to the document to store the element that is being hovered over in a global variable. When there is a keydown event on the document, prevent the default action if the div if being hovered over (so no text will be printed into the textarea).

var theDiv = document.getElementById("theDiv");
var hoverTarget = document.body;
var res = document.getElementById("result");
document.addEventListener("mouseover", function(e){
  hoverTarget = e.target;
});
function keyDown(e) {
 res.innerText = "Key: "+e.key+" KeyCode: "+e.keyCode;
}
document.addEventListener("keydown", function(e){
  if(hoverTarget===theDiv){
    e.preventDefault();
    keyDown(e);
  }
});
#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>
<span id="result">

</span>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80