0

I have a page that's going to have 30 or so id's. I want to toggle them open/closed without having to write the following 28 more times. How would I do this?

First one:

$(document).ready(function(){
    $("#one").hide();
    $("#hide1").click(function(){
        $("#one").slideToggle(2000);
    });
});

Second one:

$(document).ready(function(){
    $("#two").hide();
    $("#hide2").click(function(){
        $("#two").slideToggle(2000);
    });
});

Would it make more sense to change the id's to something like #toggle1 and then use the starts-with selector ^= or something of the like?

4
  • 3
    use a class man a CLASS Commented May 6, 2016 at 11:59
  • 1
    post some part of html Commented May 6, 2016 at 11:59
  • Post your html code. Commented May 6, 2016 at 11:59
  • Here's a codepen with HTML and CSS and JS. codepen.io/kiddigit/pen/EKGBoB Commented May 6, 2016 at 13:18

1 Answer 1

1

I would recommend this markup:

<!-- The element to click -->
<button id="one" class="button">Button</button>

<!-- The element to toggle -->
<div class="target-button" data-trigger="one">...</div>

jQuery

// Attach an event listener for .button class
$(document).on('click', '.button', function() {
   // Find the .target-button element
   // that has a 'data-trigger' attribute value equal to the clicked element's id
   $('.target-button[data-trigger="' + $(this).attr('id') + '"]').slideToggle(2000);
});

NOTE

  • this returnes the clicked element (javascript DOM element).
  • $(this) is just the jQuery object of this
Sign up to request clarification or add additional context in comments.

2 Comments

This is good. I'm going to have to play with it so content starts hidden. It also seems to hide all the IDs. I appreciate your help. I'll work with it and see what I can do.
This is going to make me look like a noob, but what is (this) doing? Can you point me to documentation on that?

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.