owwwerr
owwwerr

Reputation: 13

Jquery If Else Statement Issue

I have multiple buttons and when I click each one I want an element associated with that button to slide down and then when I click the same button the same element slides back up. The code below works but if I click one button it slides down then I click the second button nothing happens because it runs the else if part of the code. How would I fix this?

var moreOption = 1;
$(".more-button").click(function(){
        var buttonNumber = $(this).attr('buttonNumber');
        if (moreOption === 1) {
            $("#more"+buttonNumber).slideDown();
            moreOption = 2;
        } else if (moreOption === 2) {
            $("#more"+buttonNumber).slideUp();
            moreOption = 1;
        }
    });

Upvotes: 1

Views: 35

Answers (1)

Tyr
Tyr

Reputation: 2810

Just use a data-attribute on the button and switch the state manually like this:

<button class="more-button" data-showMore="1" data-buttonNumber="1"/>

$(".more-button").click(function(){
        var buttonNumber = $(this).data('buttonNumber');
        var moreOption = $(this).data('showMore');
        if (moreOption == '1') {
            $("#more"+buttonNumber).slideDown();
            $(this).data('showMore', '2');
        } else if (moreOption == '2') {
            $("#more"+buttonNumber).slideUp();
            $(this).data('showMore', '1');
        }
    });

Upvotes: 2

Related Questions