Reputation: 113
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?
Upvotes: 0
Views: 228
Reputation: 11750
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
Upvotes: 1