Search code examples
jqueryhtmlcsscss-transitionstranslate

How do I trigger successive CSS transforms with transitions using jQuery's .css()?


Here's a breakdown of what I'm trying to achieve.

  1. Translate the Y position of a box using CSS transform without a transition. e.g. translate Y - 200px.
  2. Translate the box back to the original position with a transition. e.g. translate Y - 0px.

Seems like the last translation is cancelling the first translation. I'm just not entirely sure how to chain this correctly.

See my attempt below:

$(document).ready(function() {
  $( 'body' ).on( 'click', '.box', function() {
    $( this ).css( 'transform', 'translate(0px, 200px)' );
    $( this ).addClass( 'animating' );
    $( this ).css( 'transform', 'translate(0px, 0px)' );
  } );
} );
.box {
  transform: translate(0px,0px);
  width: 50px;
  height: 50px;
  display: block;
  background: #0f0;
}

.box.animating {
  transition: all 2s ease-in-out;
  -webkit-transition: all 2s ease-in-out;
  -moz-transition: all 2s ease-in-out;
  -o-transition: all 2s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">Hello</div>


Solution

  • This should help you. Use show() to add a small timeout between two anoimations

    $(document).ready(function() {
      $( 'body' ).on( 'click', '.box', function() {
        $( this ).css( 'transform', 'translate(0px, 200px)' ).show().addClass( 'animating' ).css( 'transform', 'translate(0px, 0px)' );
      } );
    } );
    .box {
      transform: translate(0px,0px);
      width: 50px;
      height: 50px;
      display: block;
      background: #0f0;
    }
    
    .box.animating {
      transition: all 2s ease-in-out;
      -webkit-transition: all 2s ease-in-out;
      -moz-transition: all 2s ease-in-out;
      -o-transition: all 2s ease-in-out;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="box">Hello</div>