Jquery - animate height toggle

We're All Scholars picture We're All Scholars · Feb 11, 2011 · Viewed 177.6k times · Source

I have a 10px bar along the top of the screen that, when clicked, I want it to animate to a height of 40px and then if clicked again, animate back down to 10px. I tried changing the id of the div, but it isn't working. How could I get this to work, or is there a better way to do it?

body html:

<div id="topbar-show"></div>

css:

#topbar-show { width: 100%; height: 10px; background-color: #000; }
#topbar-hide { width: 100%; height: 40px; background-color: #000; }

javascript:

$(document).ready(function(){
  $("#topbar-show").click(function(){
    $(this).animate({height:40},200).attr('id', 'topbar-hide');
  });
  $("#topbar-hide").click(function(){
    $(this).animate({height:10},200).attr('id', 'topbar-show');
  });
});

Answer

Ian Christian Myers picture Ian Christian Myers · Feb 11, 2011

Give this a try:

$(document).ready(function(){
  $("#topbar-show").toggle(function(){
    $(this).animate({height:40},200);
  },function(){
    $(this).animate({height:10},200);
  });
});