Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

Since your feature relies on a mouse hover and not any other devices, maybe you could use the wheel event instead of scroll ?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda