tags:

views:

48

answers:

3

Hi

Had a good crack at this, quite a few articles around but I can't make sense of them. Any help appreciated.

When I click 'slide-toggle', I need 'slickbox' to expand, but ONLY that instance of 'slickbox' within 'slide' (i.e. there is more than one slickbox element on the page).

I have tried to use this to denote that it should only expand the relevant div, but not working so far. Thanks :)

My html:

<div class="slide">
  <a class="slick-toggle" href="#">Toggle the box</a>
  <div class="slickbox">
  <p>Hello</p>
  </div>
</div>

My jquery:

$('a.slick-toggle').click(function() {
$('.slickbox',this).slideToggle(400);
return false;
});
+1  A: 

See Working Example


You can use next() like this:

$('a.slick-toggle').click(function() {
  $(this).next('.slickbox').slideToggle(400);
  return false;
});

The next() gets you the next element with class slickbox for the relevant link clicked. This way, it will always slideToggle the relevant div with class of slickbox.

Sarfraz
Simple and effective - many thanks for all the answers!
Tom Hoad
A: 

If your change your .slickbox selector to .slide .slickbox it should apply to only those "slickboxes" inside "slide". However, you seem to be using classes as IDs here - is this what you want? That is, do you want this code to apply to multiple items like this on the page? If there is only one "slide" you should probably make "slide" an ID instead. The selector would then become #slide .slickbox

Evgeny
-1? Is this incorrect? If so, please explain why, so that I can learn as well.
Evgeny
+1  A: 

With the following line:

$('.slickbox',this).slideToggle(400);

your search for the element with the class of .slickbox within the scope a.slick-toggle

What you need to do is remove the this keyword from the second parameter, so your code should look like so:

$('a.slick-toggle').click(function(){
    $('.slickbox').slideToggle(400);
    return false;
});

Live Example: http://jsfiddle.net/nwuWd/

I you have several entites on one apge and you want to match the closest, as stated above you can use the next() method like so:

$('a.slick-toggle').click(function(){
    $(this).next('.slickbox').slideToggle(400);
    return false;
});
RobertPitt
Why exactly the down-vote ?
RobertPitt
@RobertPitt: Blind down vote is always bad +1 :)
Sarfraz