CSS transition width/position with long duration issue

184 Views Asked by At

Assume we want a transition for width/position

When using a long duration, an undesired behavior comes across, as the timing function will start from zero for the rest of the operation

    #test {
      border: solid 1px;
      width: 100px;
      height: 50px;
      transition: width 10s linear;
    }
    #test:hover {
      width: 1000px;
      transition: width 10s linear;
    }
<div id="test"></div>

When rehovering the div in any place during the transition say in the middle it will do the transition over 10s but for 500px not the original setups, even worse it will take 10s for the last 10px.

Any work around or I should use jQuery animate function?

1

There are 1 best solutions below

2
On

Here's a solution, if you don't mind scripting the animation. Essentially, you have to know the time left to cover the remaining width.

Of course, you can make this function to be used on any element, also you can pass in the desired width, but that's outside of this scope.

$("#test").on("mouseover", function(){
  var $el = $(this);  
  var time = 10000 - $el.width()*10; // This is the actual remaining animation time

  $el.stop().animate({"width": "1000px"}, time, "linear");
});

$("#test").on("mouseout", function(){
  var $el = $(this);
  var time = $el.width()*10; // This is the actual remaining animation time
  
  $el.stop().animate({"width": "100px"}, time, "linear");
});
#test {
  border: solid 1px;
  width: 100px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="test"></div>