Search code examples
javascriptcsscss-animations

activating a keyframe animation based on a click event that adds & removes a css class


I'm trying to use keyframe animations to move a block up and down based on adding or removing a class using jquery click. However, this seems to "jiggle" the orange div on first click, and then does absolutely nothing after that.

I've added the colors to show that the click event is indeed being activated and the classes added properly, but they're not important for the example.

What am I doing wrong? I feel like I've followed tutorials on this type of thing very closely. I do want to use css animation for this (not jquery animation), and I would like to use the css "reverse" animation feature.

CSS:

.swipeable {
  background: orange;
  position: absolute;
  bottom: 0;
  width: 100%;
}

@keyframes updown {
  0% {
    transform: translateY(0px);
  }
  100% {
    transform: translateY(40px);
  }
}

.swipeable-open {
  animation: updown;
  animation-direction: normal;
  animation-duration: 0.5s;
  background: red;
}

.swipeable-close {
  animation: updown;
  animation-direction: reverse;
  animation-duration: 0.5s;
  background: yellow;
}

jQuery:

$(document).on('click', '.swipeable', function() {
    const swipeable = $(this);
  
  if (swipeable.hasClass('swipeable-open')) {
    swipeable.removeClass('swipeable-open');
    swipeable.addClass('swipeable-close');
  } else {
    swipeable.addClass('swipeable-open');
    swipeable.removeClass('swipeable-close');
  }
})

HTML:

<div class="swipeable swipeable-close">
<h1>
  This is a header
</h1>
<p>
  Clicking on this orange area should move the orange area up. Clicking on it again should move the orange area down.
</p>
</div>

Fiddle:

https://jsfiddle.net/darrengates/67e3L948/


Solution

  • It would be simpler to just use JQuery's toggleClass and a transition.

    $(function() {
      $(".swipeable").click(function() {
        $(this).toggleClass("close");
      });
    });
    div {
      background: orange;
      position: absolute;
      bottom: 0;
      width: 100%;
      transform: translateY(0px);
      transition: transform 0.5s, background-color .5s;
    }
    
    .close {
      transform: translateY(40px);
      background: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <div class="swipeable">
      <h1>
        This is a header
      </h1>
      <p>
        Clicking on this orange area should move the orange area up. Clicking on it again should move the orange area down.
      </p>
    </div>