Pascal Lindelauf
Pascal Lindelauf

Reputation: 4872

Transitionend called before transition even finished?

I'm completely puzzled by the seemingly random behavior of the transitionend event. I'm trying to create news-ticker-like functionality with CSS3. I have put the core of the code that goes wrong in jsFiddle. Here is the HTML for testing:

<div class="container">
    <div class="el" id="el1">Text 1</div>
    <div class="el" id="el2">Text 2</div>
    <div class="el" id="el3">Text 3</div>
</div>

The elements are all absolutely positioned on a horizontal line next to each other. Now I want to slide them to the left until the first item is out of sight. I can then remove that first item and continue the translation for the rest of the divs.

var moveEm = function() { 
  var elements = $(".el");
  var firstEl = $(".el").first();

  firstEl.on("webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd", function(e){
    $(".el").first().remove();

    $(".el").each(function() {
      $(this).css("left", $(this).position().left);
      $(this).css({ transform: "none", transition: "none"});
    });

    moveEm();
  });

  elements.css({ transform: "translate(-100px,0px)", transition: "all 500ms linear"});
};

moveEm();

However oftentimes, the transitionend fires for the first item (as expected) but also for the second (and sometimes the third) immediately as well! Try the jsFiddle code and see that this sometimes happens and sometimes it doesn't.

Does anybody know what is causing this behavior?

P.S. It seems to happen sometimes in Safari, always in Chrome and almost never in Firefox...

Upvotes: 0

Views: 491

Answers (1)

dc5
dc5

Reputation: 12441

In this case, because you are calling moveEm inline, you are effectively listening to the transitionEnd event with a transition time of 0ms.

If you change your logic to either delay the call to moveEm() or the event binding (as you mentioned in your comments) your transitionEnd events will be triggered as expected Working fiddle:

window.setTimeout(moveEm, 10);

Upvotes: 1

Related Questions