user4609276
user4609276

Reputation:

Firing event listeners inside a transitionend event listener?

I'm trying to get a mouseover event listener to fire only when a css transition has ended. I tried alerting a random message when the css transition ends, and it does work as intended (only showing the message when it ends). But for some reason, the mouseover event works even before the transition ends.

Below is my javascript. Thanks in advance guys.

mapContainer.addEventListener("transitionend", function(){
    mapContainer.addEventListener("mousemove", function(e){ 
        if(e.clientX >= 200 && e.clientX <= 600){
            removeClass(mapContainer, "map-right");
            addClass(mapContainer, "map-left");
        } else if (e.clientX >= 900){
            removeClass(mapContainer, "map-left");
            addClass(mapContainer, "map-right");        
        } else {
            removeClass(mapContainer, "map-left");
            removeClass(mapContainer, "map-right");
        }
    });
});

UPDATE: I used a Z-Index hack heh... which surprsingly works... at least for what I'm trying to achieve. Not sure if it's good in practice. But basically I apply a Z-Index of 0 on the map container in CSS, and when the container is active, I use setTimeout() to increase the Z-Index, and set the interval to 3 seconds so the Z-index doesn't kick in until the transition ends.

Javascript

setTimeout(function(){
    campaignContainer.style.zIndex = "3";
    mapContainer.style.zIndex = "3";
}, 3000);

CSS

.map-container {
    height: 100%;
    opacity: 0;
    position: absolute;
    transform: scale(2) rotate(30deg);
    transition: all 1.2s linear;
    width: 100%;
    z-index: 0;
}

Upvotes: 0

Views: 1177

Answers (1)

wscourge
wscourge

Reputation: 11291

Here's something which will work once per transition:

var transitioned = document.getElementById("transition");
var show = document.getElementById("show");
var hasEnded = false;

transitioned.addEventListener("transitionend", function(evt){
	console.log("end")
    hasEnded = true;
});

transitioned.addEventListener("mousemove", function(evt){
    if(hasEnded) {
        console.log("Mousemoving");
    }
});
#transition {
  background: yellow;
  padding: 10px;
  transition: all 1s linear;  
  -webkit-transition: all 1s linear;
}
#transition:hover {
  background: red;
}
<div id="transition">
Hover me!
</div>

Also, for IE10 and above exlusively, you can also add

transitioned.addEventListener("transitionstart", function(evt){
    hasEnded = false;
});

Read about polyfill for transitionstart:

Upvotes: 1

Related Questions