简体   繁体   中英

having trouble with the slideUp method in jquery

I am using a show hide slider which works for the slide down but doesn't respond for the slide up, can anyone explain where Im going wrong with this:

var moreServicesList = $('#more-services-list').hide();

$('#more-services').on('click', function(e) {
    var flag = 0;
    if( flag === 0) {
        flag = 1;
        moreServicesList.slideDown('slow');
        $(this).html('Hide');
    } else {
        moreServicesList.slideUp('slow');
        $(this).html('Show');
        flag = 0;       
    }
    e.preventDefault();
}); 

Thanks in advance Kyle

You have to move var flag = 0; outside of the event listener - http://jsfiddle.net/Nnhz8/

var moreServicesList = $('#more-services-list');
var flag = 0;

$('#more-services').on('click', function(e) {

    if( flag == 0) {
        moreServicesList.slideDown('slow');
        flag = 1;
        $(this).html('Hide');
    } else {
        moreServicesList.slideUp('slow');
        $(this).html('Show');
        flag = 0;       
    }
    e.preventDefault();
});

you can use the toggle method for this like

$('#more-services').on('toggle', function(e) {
        $('#more-services-list').slideDown('slow');
        $(this).html('Hide');
    } function(){
        $('#more-services-list').slideUp('slow');
        $(this).html('Show');   
    }
});

var flag every time initializes to 0 in your case

You're resetting your flag each time the event handler is called:

$('#more-services').on('click', function(e) {
    var flag = 0;
}

To fix this, move the flag declaration in front of the event handler:

var flag = 0;
$('#more-services').on('click', function(e) {}

Here's a working example: http://jsfiddle.net/wMNtT/

Because you define your flag inside the function. It resets to zero every time the function is called.

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