Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!