Ciaran Gaffey Ciaran Gaffey -4 years ago 80
CSS Question

On hover add / remove class - not always working

I'm implementing some animation by adding and removing classes to an element on mouseover and mouseout. I'm using this method as I found using CSS alone was not reliable; the animation would not complete if the mouse exited the element before the animation finished.

So I have the following code:

<div class="one flip-container">
<div class="flipper">
<div class="front">
<!-- front content -->
</div>
<div class="back">
<!-- back content -->
</div>
</div>
</div>

<script>
jQuery(".flip-container").hover(function () {
jQuery(this).addClass("hover");
},function () {
jQuery(this).delay(2000).queue(function(){
jQuery(this).removeClass("hover");
});
});
</script>

<style>
.flip-container.hover .flipper {
transform: rotateY(180deg);
}

.flipper {
transition: 0.6s;
transform-style: preserve-3d;
position: relative;
}
</style>


This works but sometimes the class 'hover' is not removed, it stays, leaving the element in its animated state. Any idea how to make this more reliable?

Answer Source

Try using mouseenter and then set a timeout function to remove the class that way you wont be adding and removing classes except once each time the mouse enters the area. Also you may want to check to see if the area already has the class to avoid the function from being executed too many times like so:

jQuery(".flip-container").mouseenter(function () {
    var el = jQuery(this);
    if(!el.hasClass("hover")){
        el.addClass("hover");
        setTimeout(function(){ 
            el.removeClass("hover");
        }, 2000);
    }
});

Here is a working fiddle Fiddle Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download