简体   繁体   中英

What could be the reason for .slideToggle() to work when .slideUp() and slideDown() doesn't

Background:

I ran into a problem that I find somewhat unexpected. I have a small jQuery module where I've been using .slideToggle() to show/hide an element and it has been working fine. Today I'm implementing two public methods for my plugin, to either show or hide the element with a sliding effect.

Simple as it sounds, I though I'd just use .slideUp() and slideDown() to accomplish the same thing. I was really surprised when I realized that nothing happened upon calling those methods on the element.

As a side note, calling .show() and .hide() works fine as well, but without the desired animation off course.

I always thought that .slideToggle() implemented the same functionality as .slideUp() and .slideDown() "under the hood", but apparently it doesn't.

My question:

In what way does .slideToggle() differ from .slideUp() and .slideDown() and what do I have to consider when using one compared to the others?

Update, example:

I've been able to break it down into the most crucial components needed to reproduce this error in this fiddle . You can comment out .slideToggle("slow") and .slideUp("slow") respectively to test it. With slideToggle it works, with slideUp it doesnt.

The problem is that slideUp is not the best name for the method. A better name would be "slideHide". If you change it to slideDown it works as expected, since that corresponds to show.

From http://api.jquery.com/slideUp/

Description: Hide the matched elements with a sliding motion.

It in fact works the same way. I believe you have reversed the order in which to call slideDown and slideUp . Here is an updated fiddle .

Code:

var flip = true;
$(".dockedHeader").on("click", function () {
    if (flip) {
        $(".content").slideDown("slow");
        flip = !flip;
    } else {
        $(".content").slideUp("slow");
        flip = !flip;
    }
    //$(".content").slideToggle("slow");
});

Initially your content is hidden so you should call sliderDown() instead of slideUp() to show it and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM