Josh H Josh H - 3 months ago 10
HTML Question

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

Answer

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.

Comments