I will try to keep this short. I’m trying to create boxes of text that hide or show when user clicks on a expand button. I’m using the toggle() method.
The markup is like this:
<span id="toggle0">+</span>
<div id="toggle0Container">
blablabla...
<div>
<span id="toggle1">+</span>
<div id="toggle1Container">
blablabla...
<div>
<span id="toggle2">+</span>
<div id="toggle2Container">
blablabla...
<div>
// etc
The #toggle0 is supposed to toggle the #toggle0Container, the #toggle1 toggles the #toggle1Container and so on. This is all generated by PHP so there can be any number of these containers.
Here’s the JQuery code:
$(document).ready(function() {
// array of numbers, it's pretty redundant, there will never be more than 30 containers
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 , 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36];
// hide all containers first
jQuery.each(arr, function() {
$('#toggle' + this + 'Container').hide();
});
// now the toggle buttons
jQuery.each(arr, function() {
$('#toggle' + this).click(function() {
// this line is not working
$('#toggle' + this + 'Container').slideToggle('slow');
// and this just changes the toggle button from + to -
if ($(this).html() == '+') {
$(this).html('-');
} else {
$(this).html('+');
}
});
});
});
It works except for the toggling part (I have added comment above the line that’s not working). Where’s the problem?
I would follow mgroves’s approach but if you really want to do the array thing, or just want to figure out how to use each() properly, here’s how you should use it: