tags:

views:

50

answers:

2

I am using some jQuery to toggle the visibility of some div's. The toggle occurs on click and should only affect one div. The problem is that if there are multiple divs, they are all toggled on/off instead of just the one a user is trying to toggle. I think I need to use the 'next' function but can't get it working. Here is my jQuery:

jQuery(function(){
 jQuery(".toggle").click(function(){
  jQuery(".hiddenText").slideToggle("fast");
        jQuery(this).html(function(i,html) {
            if (html.indexOf('More') != -1 ){
               html = html.replace('More','Less');
            } else {
               html = html.replace('Less','More');
            }
            return html;
        }).find('img').attr('src',function(i,src){
        return (src.indexOf('plus.gif') != -1)? '/minus.gif' :'/plus.gif';
    });
});
});

html:

<p class="toggleText">More Info &nbsp;<img src="/plus.gif"></p>
<div class="hiddenText">
blah blah
</div>

Any tips? Thanks!

+3  A: 

For what it's worth, you were right, you do have to use1 next():

$(document).ready(
    function(){
        $('.toggleText').click(
            function(){
             $(this).next('.hiddenText').toggle();   
            }
            );
    }
    );

Demo at JS Fiddle.


As pointed out, by @Polyhedron, in the comments, next() would work, possibly better, without the selector, targetting the next sibling element of $(this).

Demo of the plain ol' next(), at JS Fiddle.


  1. Well, you don't have to, but you can.
David Thomas
FYI, you don't have to use .next('.hiddenText') for this to work. What this snippet is actually saying is "select the next sibling element iff it has a class name of hiddenText". If you remove the '.hiddenText', you will just select the next sibling element. No matter what it's name/id/selector/attr is.
polyhedron
+1  A: 

I believe the problem stems from the use of classes as your selector

jQuery(".toggle").click() says when an element with the class to toggleText is clicked jQuery(".hiddenText").slideToggle //Select all elements with a class of .hiddenText and slideToggle this is why all you’re the divs are opening.

Instead of jQuery(".hiddenText").slideToggle("fast");

Try $(this).next(".hiddenText").slideToggle("fast");

Sam Plus Plus