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