views:

433

answers:

6

Really quick jQuery question...

I have this function:

$(document).ready(function() {

  $('a#show1').click(function() {
    $('.item1').toggle(1000);
    return false;
  });

  $('a#show2').click(function() {
    $('.item2').toggle(1000);
    return false;
  });

  // And it goes on...
});

The page the script runs on has any number of show and item divs, all unique and identified as itemX

How can I rewrite the repeated and identical functions for show1 and show2 so that it ends up essentially like this:

$('a#showX').click(function() {
    $('.itemX').toggle(1000);
    return false;
});
A: 

If you know how many you have, you can just use a for loop and append the variable.


for(var i=1;i<=whatever;i++)
{
     $('a#show' + i).click(function() { // ... etc ... // });
}
mgroves
A: 

This is an idea:

$('a#show1', 'a#show2').click(function() {
    id = ".item" +  this.id.substr(4);
    $(id).toggle(1000);
    return false;
});
kgiannakakis
+2  A: 
$("a[id^=show]").click(function(){
 var id = $(this).attr("id");
 var num = id.substring(4);
 $(".item" + num).toggle(1000);
});

I hope it works, I didn't test it.

usoban
ah, beat me to it, although id in your case would be ".itemshow1"
David Hedlund
You may need to make this: $(".item" + $(this).attr("id")).toggle(1000);
Keith
@d, Keith: you're right, corrected ;)
usoban
That was perfect. All I had to do was add "return false;" to the end so it wouldn't flicker. Thanks!
Andrew
A: 
$('a[id^=show]').click(function() {
    var id = $(this).attr('id');
    id = id.substring(id.length-1);
    $('.item'+id).toggle(1000);
    return false;
});
David Hedlund
Nice approach, but will break when the number exceeds 9 :)
karim79
substring(4) or substring("show".length) won't break
kgiannakakis
+1  A: 

I usually try to keep the items in consistently relative positions in the DOM:

//all <a> with class .show-extra
$('a.show-extra').click(function() {
  //get the next element with the class .show-extra-panel
  $(this).next('.show-extra-panel').toggle(1000);
  return false;
});

This would make anything like this work:

<a href="#" class="format-link show-extra">text</a>
<div class="info-panel show-extra-panel">extra toggle text</div>
Keith
+1  A: 

@usoban has the right approach - the 'starts with' syntax in the first selector will find all of the 'show' items, no matter how many there are. You just need to adjust the code so that it extracts just the numerical part of the 'id' rather that using all of it, or it will be looking for elements with a class of '.itemshow1' instead of '.item1'

$("a[id^=show]").click(function(){
    $(".item" + this.attr("id").substr(4)).toggle(1000);
});

EDIT @Keith also has a good approach - using a class to mark the 'show' elements - so that the numerical part of the identifier isn't required - and then relying on the relative location of the 'item' to locate it.

belugabob