<div id="div1">d1</div>
<div id="div2">d2</div>
<div id="div3">d3</div>
window.addEventListener('scroll', e => {
console.log(e.target);
})
window.addEventListener('click', e => {
console.log(e.target);
})
div {
width: 100%;
height: 150px;
margin: 12px;
background: green;
text-align: center;
line-height: 150px;
color: white;
font-size: 2rem;
}
In the above code, when I trigger the scroll event when my cursor is over a div, event target always is the HTML document. I want to get the target element like the click event's target. It is for implementing a feature for triggering a scroll animation only when the cursor is over a div that I created for this purpose.
CodePudding user response:
You could use the :hover
selector to get all the elements that are currently being hovered. If you are only interested in a few of these then you can filter out this list (which will also contain the <body>
and <html>
elements) by using an other selector, like a specific class.
window.addEventListener("scroll", e => {
document.querySelector(".hovered")?.classList.remove("hovered");
document.querySelector(".target:hover")?.classList.add("hovered");
})
div.target {
width: 100%;
height: 150px;
margin: 12px;
background: green;
text-align: center;
line-height: 150px;
color: white;
font-size: 2rem;
}
.target.hovered {
background: yellow
}
<div id="div1">d1</div>
<div id="div2">d2</div>
<div id="div3">d3</div>
CodePudding user response:
Since your feature relies on a mouse hover and not any other devices, maybe you could use the wheel
event instead of scroll
?