styler
styler

Reputation: 16481

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

Upvotes: 0

Views: 73

Answers (4)

Kamran Ali
Kamran Ali

Reputation: 5954

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

Upvotes: 1

dierre
dierre

Reputation: 7210

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

Upvotes: 1

ThatOtherPerson
ThatOtherPerson

Reputation: 834

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/

Upvotes: 1

Zoltan Toth
Zoltan Toth

Reputation: 47667

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();
});

Upvotes: 1

Related Questions