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

252
Visualizações
change an element back after eventlistener

I have an element (const catchMe = document.getElementById("catchMe") that "runs away" from the mouse, it does so by calling a "move" function catchMe.addEventListener('mouseenter', move) that simply sets it's css style.top etc. at random points on the page (the 'running' is done through css transition as well).

What I'm trying to do is to have the catchMe element move back to it's original position a few seconds after mounseleave, and so I added an eventListener catchMe.addEventListener('mouseleave',startPosition) that rewrites it's original css but has a setTimeout in it. But the problem is that if I mouseEnter again it won't wait a few seconds till it calls startPosition, since the previous mouseLeave is still active,

So the question is, is there a way to cancel the 'old' mouseLeave upon a new mouseEnter? Or is there an easier way to go about this in general?

I'm using simple javascript

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

0

const catchMe = document.getElementById('catchme');

let timeout;
catchMe.addEventListener('mouseenter', function(event){
  clearTimeout(timeout);
  this.style.backgroundColor = '#fff';
});

catchMe.addEventListener('mouseleave', function(event){
  timeout = setTimeout(() => {
    this.style.backgroundColor = '#888';
  }, 1000);
});
#catchme {
    background-color: #888;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <button id='catchme'>Catch me</button>
</body>
</html>

Maybe you mean like this? I put clearTimeout() on mouseenter

about 4 years ago · Juan Pablo Isaza Relatório

0

The best option that I could suggest you is to relay on the CSS classes.

Example :

CSS

#catchMe{
position: absolute;
}

.Move{
top:20px;
}

.startPosition{
top:0px;
}

JavaScript

catchMe.addEventListener('mouseenter', () => {
catchMe.classList.add('Move');
catchMe.classList.remove('startPosition');
})

catchMe.addEventListener('mouseleave', () => {
catchMe.classList.remove('Move');
catchMe.classList.add('startPosition');
})

Hope this method can help you out.

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