Home > Net >  Trigger click on keypress on hovered element
Trigger click on keypress on hovered element

Time:01-25

I'd like to know if there is any way that I can get the element the mouse is currently hovering over when pressing any key.

I didn't seem to find anything like that. Thanks!

CodePudding user response:

There is a semi good working work around by combining two events

First you need the mousemove event on the window to track the cursor position:

window.addEventListener('mousemove', (e) => {
       window.pos = [e.clientX, e.clientY]; // here we just save the last cursor position inside the window object in a new property, so we can access it globally
})

Then we will need another Event Listener for triggering a keyboard event, like keydown:

window.addEventListener('keydown', () => {
       // using the elementFromPoint method to determine what the element is under the cursor, by accessing our saved position
       console.log(document.elementFromPoint(window.pos[0], window.pos[1]))

});

This in combination is working alright, but i dont know what the browser support is for the method elementFromPoint(x,y)

CodePudding user response:

var hovered;
document.onmouseover = function(e) {
    hovered = e.target.id;
}
document.addEventListener('keypress', (event) => {
  console.log(hovered);
});
div{
  border: 1px solid black;
  padding: 20px;
  text-align: center;
}

div:hover{
  background-color: #dedede;
}
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>

  •  Tags:  
  • Related