isar isar - 4 months ago 18
jQuery Question

Simple loop iterator in jQuery

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!

Answer

Your code violates the DRY principle.

  1. There is no need to have one separate ready block for each event handler.
  2. You should consider using classes and a class selector instead of the ID selectors and use the power of DOM traversing methods of jQuery for selecting the target elements.
  3. Using a loop here is a bad option/not necessary. Most jQuery methods have been designed to iterate through the collection behind the scenes.

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.

Comments