Search code examples
javascriptjquerygsap

Interchanging classes doesn't clear previous tween values


I am working on some sort of animation so I have prepared a demo which relates exactly to the task. I am inter-changing the classes after the first timeline completes and running another timeline when the user clicks the second time. The problem is when the second timeline is played, the tween adds the previous tween values to the element which I am tweening on the second click. If you look at the below example, when running second timeline i.e home_slide_2, the block_1 element is taking x value from the previous tween making animte both x and y values. Can anyone guide me on this that what I am doing wrong here.

$('.arrow').on("click",function() {
  
  var id = $(this).data('id');
    if(id == "slide_1"){

      // transition of first slide
      var home_slide_1 = new TimelineMax({paused:(true),onComplete:reset})
      .to(".block_1", 1.5, {y: 30,ease:Power4.easeOut},"s")
      .to(".block_2", 1.5, {x: 30,ease:Power4.easeOut},"s");

      function reset(){
        $(".block_1").addClass('block_2').removeClass('block_1').removeAttr("style"); 
        $(".av2").addClass('block_1').removeClass('block_2').removeAttr("style"); 
      };       

      home_slide_1.play();  
      $(this).data('id', "slide_2");
    }

  else if(id == "slide_2"){

    // transition of second slide
    var home_slide_2 = new TimelineMax({paused:(true)})
    .to(".block_1", 1.5, {y: 30,ease:Power4.easeOut});
 
    home_slide_2.play();         
  }

});
.arrow{
  float:right;
  width:50px;
  height:50px;
  background:red;
  curspor:pointer
}
.ar1{
  float:right;
  width:50px;
  height:50px;
  background:black;
  curspor:pointer
}

.block_1{
  background:green;
  float:left;
  width:100px;
  height:100px;  
}

.block_2{
  background:blue;
   float:left;
  width:100px;
  height:100px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
<div class="arrow" data-id="slide_1"></div>


<div class="block_1 av1"></div>
<div class="block_2 av2"></div>


Solution

  • You can use clearProps to clear the tween values

    else if(id == "slide_2"){
    
       //clearing the tween values in block_1
       TweenMax.set(".block_1", {clearProps:"all"}); 
    
       // transition of second slide
       var home_slide_2 = new TimelineMax({paused:(true)})
       .to(".block_1", 1.5, {y: 30,ease:Power4.easeOut});
    
       home_slide_2.play();      
     }