简体   繁体   中英

jQuery fadeToggle - Not setting visibility correctly

I have a jQuery toggle question. The following code works fine.

// unhide the more when clicked
$(".more").click(function () {
    $(this).next(".moreDetails").toggle();
    // check state of the toggle
    if ($(this).next(".moreDetails").is(":visible")) {
        $(this).html('Show Less Details ... <img src="images/smallarrowup.png" />');
    } else {
        $(this).html('Show More Details ... <img src="images/smallarrowdown.png" />');
    }
})

When someone clicks the .more class DIV it toggles the .moreDetails DIV and then changes the HTML within the .MORE DIV. It works because when it toggles the .moreDetails DIV it must then set somewhere in the .moreDetails :visible, and vice-versa, when it is toggles again it must set somewhere in the .moreDetails :hidden.

This is all great, however the toggle is a show/hide effect. I am wanting a nice fade effect. but as soon as I change

$(this).next(".moreDetails").toggle();

to

$(this).next(".moreDetails").fadeToggle();

it breaks. It does not seems at each toggle the visibility of the .moreDetails DIV is always true even though you cannot see it on the DOM.

Any ideas? Thanks

This is because you are checking :visibility before finishing fade in / out effect.

Try this : put if / else inside fadeToggle function

// unhide the more when clicked
$(".more").click(function () {
    var $this = $(this);
    $(this).next(".moreDetails").fadeToggle( "fast", function() {
    if ($(this).is(":visible")) {
        $this.html('Show Less Details ... <img src="images/smallarrowup.png" />');
    } else {
        $this.html('Show More Details ... <img src="images/smallarrowdown.png" />');
    }
   });
});

You can use "slow" / "fast" as per requirement.

For more details on fadeToggle click here .

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