简体   繁体   中英

JQuery: How do I determine if a slideToggle has been toggled?

How do I do the following pseudo code in JQuery?

$(document).ready(function(){
    $(".btn-slide").click(function(){
        $("#divToSlide").slideToggle("fast");
        if ($(this).isToggled) {  // <---- DOESN'T WORK -------
            // do something when toggled
        } else {
            // do something different when not toggled
        }
    });  
});

Or you could just use the toggle function: http://api.jquery.com/toggle/

$('#target').toggle(function() {
    alert('First handler for .toggle() called.');
}, function() {
    alert('Second handler for .toggle() called.');
});

Note: You can have as many toggles as you want, just add more functions:

$('#target').toggle(function() {
    alert('1 handler for .toggle() called.');
}, function() {
    alert('2 handler for .toggle() called.');
}, function() {
    alert('3 handler for .toggle() called.');
}, function() {
    alert('4 handler for .toggle() called.');
}, function() {
    alert('5 handler for .toggle() called.');
});

[EDIT]

$('a.toggleButton').toggle(function() {
    $("#divToSlide").slideDown("fast");
    // do something when toggled
}, function() {
    $("#divToSlide").slideUp("fast");
    // do something when toggled    });
});

Try using a callback function for slideToggle

$(document).ready(function(){
    $(".btn-slide").click(function(){
        $("#divToSlide").slideToggle("fast", function(){
            if ($(this).is(":visible")) {  // <---- DOESN'T WORK -------
            // do something when toggled
            }
            else {
            // do something different when not toggled
            }
        });
    });            
 });  
$(document).ready(function(){
    $(".btn-slide").click(function(){
        if ('#divToSlide').is(':visible')) {
            // do something when toggled
        } else {
            // do something different when not toggled
        }
    });  
});

try:

$(document).ready(function(){
    $(".btn-slide").click(function(){
        $("#divToSlide").toggle(
        function() {  
            // do something when toggled
            $(this).slideUp();
        },
        function(){
            // do something different when not toggled
            $(this).slideDown();
        }
    );  
});

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