views:

37

answers:

2

Is there a way to have many, many instances of jquery-based show/hide (toggle link followed by container with hidden content; toggle text changes depending on state) on a page using only classes and not IDs? I haven't found a reasonably well-documented, functional example anywhere. Thanks for any and all help! --cg

A: 

Something like:

<div class="toggleset">
  <a class="toggler" href="#">Hide</a>
  <div class="container">
    Data to show/hide
  </div>
</div>

$('.toggler').click(function(evt) {
  var $toggler = $(this);
  var $container = $toggler.siblings('.container');

  $container.toggle();
  $toggler.text($container.is(':visible') ? "Hide" : "Show");
  evt.preventDefault();
});

You don't need the outer div if you use next() instead of siblings, but it ties the script tighter to the markup.

Rob
A: 

Thanks a lot, Rob. Works well! I've managed to make it so secondary classes can control what the toggle text is in both states:

<script type="text/javascript">
<!--
$(document).ready(function() {

$('.toggler.show').click(function(evt) {
  var $toggler = $(this);
  var $container = $toggler.siblings('.container');

  $container.toggle();
  $toggler.text($container.is(':visible') ? "Show less" : "Show more");
  $(this).toggleClass('active');
})

$('.toggler.read').click(function(evt) {
  var $toggler = $(this);
  var $container = $toggler.siblings('.container');

  $container.toggle();
  $toggler.text($container.is(':visible') ? "Read less" : "... Read more");
  $(this).toggleClass('active');
})
evt.preventDefault();
});
-->
</script>

How would I take advantage of jquery "slide" toggle? I tried changing

$container.toggle();

to something like

$container.slideToggle('fast');

but that breaks the text change on the toggle. --cg

The text change is broken because the visibility of the container isn't final until the animation is complete.To fix this, check $container.is('visible') before you do the slideToggle and anticipate that the state will change. i.e., $container.is(':visible') == true would imply text of "Read more" because we're about to hide the container. You can then hide using an animation (jquery implements slide by changing css attributes over time, but at the end it will be hidden).If this answer is correct, could you upvote and mark it as the answer? Thx and good luck!
Rob