Search code examples
htmlcsscss-transitionscss-transforms

CSS 3 : Correct "transition-property" for translate operation


I am using the following code to achieve a simple translation of an object when its clicked.

$('#div1').on('click', function () {
    $(this).toggleClass('pushObject');
});
#div1 {
    width:30px;
    height:30px;
    background-color:green;
    cursor:pointer;
    transition: all 0.5s ease;
}
#div1:hover {
    background-color:red;
}

.pushObject {
    transform: translate(250px, 0px);
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="div1"></div>

It works as expected, and I get a smooth 0.5 second animation for all the transitions(in this case translate as well as hover) as I have set the transition-property value in css to all.

What I want is to limit this 0.5s Transition to translate only, and not to hover.

This can be achieved by setting the correct transition-property in css, but I am unable to find the correct value.

So what will be the correct value of transition-property here so that the animation applies to translate only and not to any other transition.

Here is a JsFiddle.


Solution

  • In your transform: translate(250px, 0px) declaration, the property is called transform and the value of that property is the translate(250px, 0px) function.

    The correct value of transition-property is therefore transform:

    #div1 {
        width:30px;
        height:30px;
        background-color:green;
        cursor:pointer;
        transition: transform 0.5s ease;
    }
    

    Updated fiddle

    $('#div1').on('click', function () {
        $(this).toggleClass('pushObject');
    });
    #div1 {
        width:30px;
        height:30px;
       
        background-color:green;
        cursor:pointer;
        -webkit-transition: -webkit-transform 0.5s ease;
        -moz-transition: -moz-transform 0.5s ease;
        -o-transition: -o-transform 0.5s ease;
        transition: transform 0.5s ease;
    }
    #div1:hover {
        background-color:red;
    }
    
    .pushObject {
        transform: translate(250px, 0px);
        -webkit-transform: translate(250px, 0px);
        -ms-transform: translate(250px, 0px);
        -o-transform: translate(250px, 0px);
        -moz-transform: translate(250px, 0px);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <div id="div1"></div>