Reputation: 1791
A really simple question. How can I make the following script in a simple for loop:
jQuery(document).ready(function(){
jQuery("#toggle-0").click(function(){
jQuery("#toggle-list-0").slideToggle(500);
});
jQuery("#toggle-1").click(function(){
jQuery("#toggle-list-1").slideToggle(500);
});
jQuery("#toggle-2").click(function(){
jQuery("#toggle-list-2").slideToggle(500);
});
});
The for loop is intended as in Python:
for i in range(3): a, b = "#toggle-" + str(i), "#toggle-list-" + str(i)
Thanks!
Upvotes: 4
Views: 897
Reputation: 144659
Your code violates the DRY principle.
ready
block for each event handler.Here is an example using a comma separated selector:
jQuery(document).ready(function($){
$("#toggle-0, #toggle-1, #toggle-2").click(function() {
var num = this.id.replace('toggle-', '');
$("#toggle-list-" + num).slideToggle(500);
});
});
The above snippet is one way of minifying the original code but imagine you want to add 10 more IDs to the selector. Now you code is not maintainable and doesn't make any sense. Use classes instead.
Upvotes: 2
Reputation: 13676
$(document).ready(function(){
for(i = 0; i < 3; i++)
{
$('#toggle-'+i).click(function(){
$('#toggle-list-'+i).slideToggle(500);
});
};
});
But i'd strongly suggest to change id's to names;
Instead of having toggle0;toggle1;toggle2 just put one name = toggle Than you just get array of your toggles like this:
var toggles = $('toggle');
And work with it.
Upvotes: 0
Reputation: 82267
Iterate with a for loop inside of the document ready callback. Make sure to close over i
so that it doesn't change inside of the click event handler.
jQuery(document).ready(function(){
for(var i = 0 ; i < 3; i++){
(function(i){
jQuery("#toggle-"+i).click(function(){
jQuery("#toggle-list-"+i).slideToggle(500);
});
})(i)
}
});
Upvotes: 2