Animation doesn't complete with jQuery TransitionEnd event

401 Views Asked by At

Situation

  • .rightnav.front is clicked for DIV1.
  • DIV1 moves to the right, and opacity is lowered
  • DIV1 moves back left, and at completion opacity is 0
  • DIV1 gets class .hidden and .offset to hide it and to move it off screen, so it's not clickable anymore..
  • The next DIV (DIV with id 2 for test-purposes) has it's hidden and offset classes removed, and is the target for the next click-event.

Problem

The DIV moves right, but doesn't move left (back again) before it's hidden. See Codepen at the bottom for a try-out.

I'm only posting the JavaScript code here.. CSS and HTML you'll find in the codepen.

Here is the jQuery code

$(document.body).on('click','.rightnav.front', function () {
      var x = $(this).parent().parent();
      x.addClass('moveright')
      .one('transitionend', function() {
        x.removeClass('moveright')
      })
      .one('transitionend', function(){
        x.addClass('moveleft');
      })
      .one('transitionend', function() {
        x.addClass('hidden').addClass('offset');
        $('.rightnav.front').removeClass('front');
        var nextId = Number(x.attr('id')) + 1;
        var nextWidget = $('#' + nextId);
        nextWidget.removeClass('hidden');
        nextWidget.children().find('.rightnav').addClass('front');
      }) 
    });

CodePen

Here is the CodePen.IO link for a live test: http://codepen.io/nygter/pen/QbpegM

1

There are 1 best solutions below

1
Garrett On BEST ANSWER

Take a look at this solution, maybe (sure) it's not ideal, but should work as expected. As I mentioned in comment I've moved animation from jQuery to @keyframes.

Magic cames from:

.widget.moveright{
  left:450px;
  margin-left:-100px;
  opacity:0.5;
}

and

x.addClass('moveright')
      .one('transitionend', function() {
        x.removeClass('moveright')
      })
      .one('transitionend', function(){
        x.addClass('moveleft');
      }) //...

Transformed into:

@keyframes moveright{
  50% {
    left:450px;
    margin-left:-100px;
    opacity:0.5;
  }
  100% {
    opacity: 0;
  }  
}

.widget.moveright{
  animation: moveright 1s ease;
  -webkit-animation: moveright 1s ease;
}

and

x.addClass('moveright')
      .one('animationend', function() {
        $(this)
          .removeClass('moveright')
          .addClass('hidden offset');
        //...

See it in action at Codepen. To understand CSS animations take a look.