Josh H
Josh H

Reputation: 19

Having trouble toggling an animation when clicked on

I am trying to make a div that expands in height when clicked on, and then goes back to its original size when clicked on again. I have tried to use .toggle but whenever I do every div (with the related class) completely vanishes. I posted a code pen below so you can easily view the codes effects. http://codepen.io/JoshuaHurlburt/pen/JKqAPr

<div>
  <div class='box' id='emailVer'>
    <h2 id='payText'>PAYMENT</h2>
  </div>

  <div class='box' id='accCust'>
    <h2 id='acText'>ACCOUNT CUSTOMIZATION</h2>
  </div>

    <div class='box' id='pay'>
    <h2 id='evText'>EMAIL VERIFICATION</h2>

  </div>
</div>

JS:

var main = function(){
  $('.box').click(function() {
    $(this).animate({
      height: "300px"
    },200 );
  }
)}
$(document).ready(main);

I decided to leave out the CSS, but I will edit it in if anyone thinks it is important to the solution

Upvotes: 1

Views: 58

Answers (3)

iamtjg
iamtjg

Reputation: 64

The toggle functions in jQuery toggle the visibility of an element which is why they disappear.

I believe what you are looking for is .toggleClass. See http://api.jquery.com/toggleclass/. You can then create another class with the expanded height properties. Which will be toggled on and off on click.

Adding height to your existing transition property on box will handle the animation.

CSS

.box {
  width:300px;
  height:75px;
  margin:0 auto;
  -webkit-transition:box-shadow 1s, height 1s;
  transition: box-shadow 1s, height 1s;
}

.expanded {
  height: 300px;
}

JS

var main = function(){
  $('.box').click(function() {
    $(this).toggleClass('expanded');
  }
)};
$(document).ready(main);

Upvotes: 0

MPawlak
MPawlak

Reputation: 715

There's probably a better solution than this but here is one-

Replace your script file with this

var main = function(){
  $('.box').click(function() {
    var el = $(this); 
    if (!el.hasClass('selected')) {
      el.animate({
      "height": "300px"
    }, 200)
      el.addClass("selected");
    } else {
      el.animate({
      "height": "75px"
    }, 200);
      el.removeClass("selected");
    }
  }
)}
$(document).ready(main);

What you need is a way to track what has already been selected (and animated) and what has not. I chose to add a class (selected) and check to see if the element has that class. If it has not yet been selected, animate to 300px and add the class, else animate back to 75px and remove it.

Upvotes: 1

Vijai
Vijai

Reputation: 2509

Try .slideToggle

$( "#clickme" ).click(function() {
  $( "#book" ).slideToggle( "slow", function() {
    // Animation complete.
  });
});

Upvotes: 0

Related Questions