Coolguy
Coolguy

Reputation: 2285

Sliding effect using jquery animate

below is my code:

html:

<div>
    <div id="div1">12345</div>
    <div id="div2">67890</div>
    <div id="div3"><a href="#" id="slide">abcde</a></div>
    <div id="pad" style="display:none;">1234567890</div> 
</div>

css:

#div1{width: 150px; height:50px; background-color: red;}
#div2{width: 150px; height:100px; background-color: yellow;}
#div3, #pad{width: 150px; height:20px; background-color: grey;}
#pad{height: 50px;}

js:

        $("#slide").click(function(e) {
         e.preventDefault();
          if($("#div2").hasClass("toggled")) {
             $("#div2").animate({"height": "100px"}, function() {
                 $("#pad").hide();}).removeClass("toggled"); 
          } 
          else {
            $("#div2").animate({"height": "40px"}, function() {
            $("#pad").show();}).addClass("toggled"); 
          }
       });

JSFIDDLE

When I press the link, a grey div will slide up. Kinda like a keypad sliding up when user press the link.

But it kinda look weird. The "pad" div only show after the grey div slide up. And it only will hide after sliding down. What I want is for the "pad" to have a slide up and slide down effect, like opening and closing a drawer. Any ideas?

Upvotes: 2

Views: 51

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

Use slideDown/Up to show the pad element and don't wait for the slide animation to finish to start the animation of pad

$("#slide").click(function(e) {
  e.preventDefault();
  if ($("#div2").hasClass("toggled")) {
    $("#div2").animate({
      "height": "100px"
    }).removeClass("toggled");
    $("#pad").slideUp();
  } else {
    $("#div2").animate({
      "height": "40px"
    }).addClass("toggled");
    $("#pad").slideDown();
  }
});
#div1 {
  width: 150px;
  height: 50px;
  background-color: red;
}
#div2 {
  width: 150px;
  height: 100px;
  background-color: yellow;
}
#div3,
#pad {
  width: 150px;
  height: 20px;
  background-color: grey;
}
#pad {
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div id="div1">12345</div>
  <div id="div2">67890</div>
  <div id="div3"><a href="#" id="slide">abcde</a></div>
  <div id="pad" style="display:none;">1234567890</div> 
</div>

Upvotes: 2

Related Questions