Search code examples
jquerycssanimationhoverscale

How do I keep an element scaled in CSS3 in-till mouseleave? Then on mouseleave scale the element back to it's original size


When I use mouseenter on a button I want the scale command in CSS3 animation to be triggered on a separate element.

My code currently does this, however I need the scale to stay at it's finished point in-till mouseremove, then the element that's scaled needs to scale back to initial dimensions.

How do I do this?

Here's my code:

$("#button").mouseenter(function() {
$('.transform').toggleClass('classname');
});

CSS:

.transform {
-webkit-transition: all 2s ease;  
-moz-transition: all 2s ease;  
-o-transition: all 2s ease;  
-ms-transition: all 2s ease;  
transition: all 2s ease;
}

.classname {
-webkit-animation: cssAnimation 1.000s 1 ease;
-moz-animation: cssAnimation 1.000s 1 ease;
-o-animation: cssAnimation 1.000s 1 ease;
}
@-webkit-keyframes cssAnimation {
from { -webkit-transform: scale(1.000) }
to { -webkit-transform: scale(0.800) }
}

Thank you.


Solution

  • Use the .hover() event handler instead.

    change mouseenter to hover

    $("#button").hover(function() {
        $('.transform').toggleClass('classname');
    });
    

    Which is the same as

    $("#button").on('mouseenter mouseleave', function() {
        $('.transform').toggleClass('classname');
    });
    

    The first part was based on how to remove the class..

    But you do not need to use animations for the scaling.. just transitions will do.

    And since transition go both ways by default it will handle the scale up automatically once you remove the class.

    Demo at http://jsfiddle.net/3tsuS/