UX Design and Development course

jQuery Animations

HTML

.block
  button
    | click me and win!

jQuery

$('.block').on('click', 'button', function() {
  var el = $(this).parent();

  el.toggleClass('highlighted');

  // this will simply execute inline CSS
  // el.css('top', '0px');

  // using jQuery animate() method - weird syntax when adding raw values
  // When only doing this, it will only animate up - that's no good.
  el.animate({'top': '0px'});

  // the better solution is to make this function state aware using if statements.
  // if ( vacation has class highlighted ) {
  // We can use the method of hasClass() to retrieve the append class in the DOM
  if (el.hasClass('highlighted')) {
    // animate up
    // to adjust the time signature, add the time argument
    el.animate({'top': '0px'}, 600);  // 'fast' = 200, 'slow' = 600
  } else {
    // animate down
    el.animate({'top': '100px'}, 'slow');
  }

  // now that we learned how to examine the DOM for a class to create a jQuery animation, we are going to throw away all that code.
  // the preferred method is to use pure CSS
  // by adding the CSS below, we will use the CSS transition function and simply reply on
  // the added/removed highlighted class to manage the animation
});

CSS

.block {
  position: relative;
  transition: all 1s;
  top: 100px;
  width: 70%;
  background-color: orange;
  text-align: center;
  padding: calc(25% - 25px) 0
}

button {
  text-align: center;
  height: 50px;
  font-size: 1.3em;
}

.highlighted {
  background-color: blue;
  top: 0;
}

Play with code

JS Bin