Angel Politis Angel Politis - 6 months ago 16
jQuery Question

How to fix jQuery SlideToggle Animation hitch?

I am trying to create a FAQ page and I want the question block to slide down on click. Although I have achieved what I wanted, when it slides back up, the animation has some sort of a hitch which is very obvious and annoying as the title of the second block snaps up towards the title of the first one.

I have searched all across stackoverflow for this topic, but despite having checked out many questions and their answers but not a single one worked for my case.

I have a made demo for you here.

Screencast requested by @twxia

HTML:

<div id = "FAQ" class = "tab">
<h1 id = "faq_title">FAQ</h1>
<h4 id = "general_questions_title">Questions:&nbsp;
<i class = "fa fa-eye eye-show-hide"></i>
</h4>
<div class = "questions" id = "general_questions"></div>
<h4 id = "financial_questions_title">Questions:&nbsp;
<i class = "fa fa-eye eye-show-hide"></i>
</h4>
<div class = "questions" id = "financial_questions"></div>


jQuery:

// Show category on click
$(".eye-show-hide").on("click", function() {
// Toggle eye icon and make the others default
$(this).toggleClass("fa-eye fa-eye-slash");
$(this).parent().siblings("h4").children().removeClass("fa-eye-slash").addClass("fa-eye");

// Toggle category and close the others
$(this).parent().next().slideToggle(500).css("display", "inline-block");
$(this).parent().next().siblings(".questions").slideUp(500);
});

// Show answer on question click
$(".questions ol li p").on("click", function() {
$(this).parent().next().slideToggle(500).css("display", "block");
$(this).parent().next().siblings("p").slideUp(500);
});

Answer

slideToggle is animate by mathematical way, it'll control the element's height, padding, margin ... so it's difficult to maintian if your DOM tree is complex, sometimes will cause this problem(like forget to reset default margin or padding).

If you don't want to see that snap problem.

you need to use element to wrap it and set a min-height on it. It just a dirty hack to prevent the animating element don't influence other element. There may be some padding or margin in these complex structure cause this problem. (on the animating element, its child or somewhere)

like this: https://jsfiddle.net/9r5akuxt/8/

It'll be great by using css3 transform to animate it.