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!
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)
Try this instead windows events:
var positionHovered = []
document.addEventListener('mousemove', (e) => {
positionHovered = [e.clientX, e.clientY];
})
document.addEventListener('keydown', () => {
console.clear();
console.log(document.elementFromPoint(positionHovered[0], positionHovered[1]).id);
});
div{
border: 1px solid black;
padding: 20px;
text-align: center;
margin: 5px;
}
div:hover{
background-color: #dedede;
}
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
You can add the mouseover event to the elements that you want to hover over, and then add the keydown event listener to call a custom function. In that function you can use a query selector to get the hovered element, and use it in your code. You can then remove the keydown event listener on mouseout.
window.focus();
document.querySelectorAll(`.hover-div`).forEach(elmnt => {
elmnt.addEventListener(`mouseover`, (event) => {
document.addEventListener(`keydown`, logElement)
});
elmnt.addEventListener(`mouseout`, (event) => {
console.clear();
document.removeEventListener(`keydown`, logElement)
})
});
function logElement() {
const elem = document.querySelector(`.hover-div:hover`);
console.log(elem.outerHTML)
}
body {
background: #e2e1e0;
}
div.container div {
background: white;
padding: 25px;
margin: 15px;
display: inline-block;
border: 1px solid black;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}
.hover-div:hover {
box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
}
<div class="container">
<div class="hover-div" title="div-1">1</div>
<div class="hover-div" title="div-2">2</div>
<div class="hover-div" title="div-3">3</div>
</div>