isar
isar

Reputation: 1791

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!

Upvotes: 4

Views: 897

Answers (3)

Ram
Ram

Reputation: 144659

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.

Upvotes: 2

Fabjan
Fabjan

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

Travis J
Travis J

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

Related Questions