omukiguy omukiguy - 17 days ago 5
Javascript Question

add a variable counter to jquery id

I have the code below currently and it works fine.

$('.clickable').click(function(e){
e.preventDefault();
$('#toggle').slideToggle();
});

$('.clickable1').click(function(e){
e.preventDefault();
$('#toggle1').slideToggle();
});


I need to refactor it to work miracles for me in terms of looping. I want to have one statement that add a number to the id toggle and class clickable using a loop for a maximum number 5 times.

Something like below

for(i = 0; i < 8; i++) {
$('.clickable'.' + i + ').click(function(e){
e.preventDefault();
$('#toggle'.' + i + ').slideToggle();
});
}

Answer

If you want a more flexible solution, without limiting to a certain number of object, you could use another approach.

Using a common class for al clickable elements (ie clickable), and an attribute to set the clickable target slide.

Html:

<a href='#' class='clickable' data-target='1'>Slide</a>

Javascript:

$('.clickable').click(function(e){
   e.preventDefault();
   $('#toggle' + $(this).data('target')).slideToggle();
});
Comments