Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the element my cursor positioned over when a window.scroll event occurs?

<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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="target" id="div1">d1</div>
<div class="target" id="div2">d2</div>
<div class="target" id="div3">d3</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading