Paolo Rossi
Paolo Rossi

Reputation: 2510

How to animate show / hide slide effect with jQuery?

I'm doing a simple steps page and would like to add a slide effect. My problem is the strange behavior of the effect slide. The div should enter is shown for a moment under the div that has to come out. I tried to work with the delay and with the execution time but have not been able to solve.

HTML

<fieldset>
   <div id="one"></div>
   <br />
   <a class="next">next</a>    
</fieldset>
<fieldset>
   <div id="two"></div>
   <br />
   <a class="prev">prev</a>
   <a class="next">next</a>    
</fieldset>
<fieldset>
   <div id="three"></div>
   <br />
   <a class="prev">prev</a>
</fieldset>

JS

$(".next").click(function(){
  current_fs = $(this).parent();
  next_fs = $(this).parent().next();
  //show the next fieldset
  next_fs.show("slide", { direction: "left" }, 0);
  current_fs.hide("slide", { direction: "right" }, 0);
});

$(".prev").click(function(){
  current_fs = $(this).parent();
  previous_fs = $(this).parent().prev();
  //show the previous fieldset
  previous_fs.show("slide", { direction: "right" }, 0);
  current_fs.hide("slide", { direction: "left" }, 0);
});

JSFIDDLE

How could I do? Thanks

Upvotes: 1

Views: 1404

Answers (1)

Tuan
Tuan

Reputation: 952

That is because of the async nature of animations. You have to chain animations to prevent them starting all at once.

The behavior comes because you are just executing two animations at once.

You have to

  1. Start hiding
  2. Wait for hiding to end
  3. Start showing

See my updated fiddle

Refer to: jQuery Documentation

Solution

$(".next").click(function(){
    current_fs = $(this).parent();
    next_fs = $(this).parent().next();
    next_fs.hide(); // this fixes your css
    current_fs.hide("slide", { direction: "right" }, function() {
        next_fs.show("slide", { direction: "left" });
    });
});

$(".prev").click(function(){
    current_fs = $(this).parent();
    previous_fs = $(this).parent().prev();
    current_fs.hide("slide", { direction: "left" }, function() {
        previous_fs.show("slide", { direction: "right" });
    });
});

Upvotes: 2

Related Questions