Question

I'm trying to animate the height of an element after a class has been applied, here's the simplified code:

HTML

<div class="section">
  <div class="panel">
    <a href="#" class="toggle">Click</a>
    <div class="panel-content">
      Some content...
    </div>
  </div>
</div>

CSS

.section {
  position: relative;
  width: 500px;
  height: 200px;
  margin: 100px auto;
  background: #ccc;
}

.panel {
  width: 65%;
  position: absolute;
  left: 0;
  bottom: 0;
}

.toggle {
  display: inline-block;
  height: 15px;
  background: #ddd;
}

.panel-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 1s;
}

.active .panel-content {
  max-height: 9999px;
}

JS

$(function() {
  $('.toggle').on('click', function (e) {
    e.preventDefault();
    $(this).closest('.panel').toggleClass('active');
  });
});

When I click the .toggle link an active class is set on the .panel element to animate the .panel-content height, however when the class is first added the content is shown without animation and when it's removed the element takes one second (the transition's duration) to start animating. You can see a live demo here: http://codepen.io/javiervd/pen/bLhBa

I tried to play with the position and overflow properties as well but I couldn't make it work, maybe there's another way of achieving the same effect?

Thanks in advance.

Was it helpful?

Solution

You need to do a transition when something happens. This isn't what you want, but let me show you something:

.pannel-content{
  height:0;
}
.pannel-content:hover{
  height:50px; transition:height 2s;
}

This is how transition works. You have not created an action. There is no click Pseudo Class, and you don't want to effect the same element anyways. Try using jQuery, like.

<html>
  <head>
    <style type='text/css'>
      .active .pannel-content{
        display:none; height:9999px;
      }
    </style>
  </head>
<body>
  <div class='section'>
    <div class='panel'>
      <a href='#' class='toggle'>Click</a>
      <div class='panel-content'>
        Some content...
      </div>
     </div>
  </div>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
  <script type='text/javascript'>
    $('.toggle').click(function(){
      $('.active .pannel-content').show('slow');
    });
  </script>
</body>
</html>

You could also use jQuery's .animate() method. Of course I would recommend that you use declair a DOCTYPE and use <meta> tags. Also you should use external CSS, as it would be cached in your users Browser memory.
Visit http://api.jquery.com/show/ and http://api.jquery.com/animate/ for details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top