Animation How to - Create animation with jQuery and CSS3








Question

We would like to know how to create animation with jQuery and CSS3.

Answer


<!--   w  w w. j  a v  a2  s  .c  om-->
Code revised from 
http://fiddle.jshell.net/martinwolf/m6xUQ/show/light/


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<style type='text/css'>
.btn {
  display: block;
  padding: 14px 0 0 13px;
  width: 45px;
  height: 40px;
  overflow: hidden;
}

.btn.is-active {
  background: red;
}

.dash, .dash-small {
  display: block;
  margin-bottom: 2px;
  width: 19px;
  height: 3px;
  text-indent: -99999px;
  background: #fff;
}

.dash-small {
  width: 13px;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
function animateDashs() {
    dash1 = $('.btn .dash-one');
    dash2 = $('.btn .dash-two');
    dash3 = $('.btn .dash-three');
    function animateDash1() {
        $(dash1).animate({
            width: 0,
            marginLeft: 34
        }, 500, function() {
            $(dash1).css('margin-left', 0).css('width', 0);
            animateDash2();
        });
    }
    function animateDash2() {
        $(dash2).animate({
            width: 0,
            marginLeft: 34
        }, 500, function() {
            $(dash2).css('margin-left', 0).css('width', 0);
            animateDash3();
        });
    }
    function animateDash3() {
        $(dash3).animate({
            width: 0,
            marginLeft: 34
        }, 500, function() {
            $(dash3).css('margin-left', 0).css('width', 0);
            animateDash12();
        });
    }
    function animateDash12() {
        $(dash1).animate({
            width: 19,
            marginLeft: 0
        }, 500, function() {
            animateDash22();
        });
    }
    function animateDash22() {
        $(dash2).animate({
            width: 19,
            marginLeft: 0
        }, 500, function() {
            animateDash32();
        });
    }
    function animateDash32() {
        $(dash3).animate({
            width: 13,
            marginLeft: 0
        }, 500, function(){
            animateDash1();
        });
    }
    // Start animation
    animateDash1();
}
$(document).ready(function(){
    $('.btn').live('click', function(){
        animateDashs();
    });
});
});//]]>  
</script>
</head>
<body>
  <a href="javascript:;" class="btn is-active"> 
      <span class="dash dash-one"></span> 
      <span class="dash dash-two"></span> 
      <span class="dash-small dash-three"></span>
  </a>
</body>
</html>

The code above is rendered as follows: