tags:

views:

299

answers:

6

I am using jQuery toggle with a link and a div. I will eventually have approx. 50 divs i want to toggle, and instead of creating a new function for each one, is there a way i can create a class and have it read unique ID's for each div? (if that makes sense)

For instance, i will have A1, A2, A3, B1, B2, B3..e.tc..

  $(document).ready(function() {

  $('#slickbox').hide();


  $('a#slick-toggleA1').click(function() {
    $('#A1').toggle(300);
    return false;
  });



});
+1  A: 

HTML

<a class="clicker" href="#box1">Box 1</a>

<div class="coolbox" id="box1">I'm hidden!</div>

JavaScript

$('.coolbox').hide();

$('.clicker').click(function(event){
    event.preventDefault();
    $($(this).attr('href')).toggle(300);
});
orokusaki
I think he wants to click a link that then toggles a <div>
Pickle
@Pickle, yea I edited it. I didn't see that in my haste at first.
orokusaki
Downvoting everyone else's valid answer to promote yours is not acceptable behavior, I'd advise you rethink that. Upvoted all other answers to correct this.
Nick Craver
A: 

Give the link a class, and stick the id of the div you want to toggle in the "rel" attribute - that's even standards compliant.

Then your function can look like this:

$('a.specialClass').click(function(){
  $('#'+$(this).attr('rel')).toggle(300);
  return false;
}
Pickle
A: 

If you give your links a class and used the href like this:

<a class="opener" href="#A1">Open A1</a>
<div id="A1">Content here</div>

With this jQuery:

$('a.opener').click(function() {
  $(this.href).toggle(300);
  return false;
});

If javascript was disabled, the anchors would still navigate to the divs on the page as well.

Nick Craver
Not sure why youre getting down votes for this. This is a good solution in that it will degrade. +1 from me.
prodigitalson
+2  A: 

you can iterate through wrapped sets with .each()

$('div').each(function(i){
  $(this).toggle(300);

});

of course you can limit a wrapped set through a selector. Alternativly, cou can use .filter() on all divs to find those divs you want to toggle.

Kind Regards --Andy

jAndy
+1  A: 

So lets add the class slick-toggle to your a tags. and lets change their id'to something more definitively parseable -slick-toggle-$ID` where $ID is the id of the div to toggle. then we do this in $.ready...

$('a.slick-toggle').click(function(){
   var divId = '#'+$(this).attr('id').split('-').pop();
   $(divId).toggle();
   return false;
});
prodigitalson
+1  A: 

you can use different selector for div's being toggeled. For instance class or custom attribute

$('.clicker').click(function(){
  $('[toggeled]').toggle(300);
  return false;
}

having in mind the following markup

<div class="clicker">Click Me</div>
<div id="first" toggled="true">First to hide</div>
<div id="second" toggled="true">second to hide</div>
<div id="third" toggled="true">third to hide</div>
vittore