jQuery Animation How to - Animate div's width onclick








Question

We would like to know how to animate div's width onclick.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<style type='text/css'>
div {<!--from w ww.  jav a  2  s  .  c om-->
  background: red;
  width: 100px;
  height: 100px;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $('#foldit').click( function() {
        var toggleWidth = $(this).width() == 165 ? "100px" : "165px";
        $(this).animate({ width: toggleWidth });
    });
});
</script>
</head>
<body>
  <div id="foldit"></div>
</body>
</html>

The code above is rendered as follows: