0

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;
        }
    });
3
  • You cannot track status of two buttons with a single variable. You need one variable per button. Commented Jun 21, 2017 at 20:13
  • @jsalonen Yes, I know. How would I use a different variable for each button so a new button can easily be added? Thanks. Commented Jun 21, 2017 at 20:14
  • Use $(this).data() to track the value directly on the element, then it doesn't matter how many elements you have as they track themselves. I'd go one step further and match your '#more' by data attributes rather than IDs as I don't generally agree with mixing IDs and variables. Commented Jun 21, 2017 at 20:31

1 Answer 1

2

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');
        }
    });
Sign up to request clarification or add additional context in comments.

4 Comments

When running alert($(this).data('buttonNumber')) and alert($(this).data('showMore')) I get undefined.
I switched the .data('foo') for .attr('data-foo') and it worked. Thanks.
@owwwerr which version of jquery are you using?
@freedomn-m 2.2.4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.