javascriptjqueryjquery-eventsdom-traversal

Multiple Functions Into One


I am trying to take these functions and combine them into one:

$(".a h3").click(function() {
   $(".a .collapse-this").slideToggle("slow");
});

$(".b h3").click(function() {
   $(".b .collapse-this").slideToggle("slow");
});

$(".c h3").click(function() {
   $(".c .collapse-this").slideToggle("slow");
});

Something like this, but this causes everything to collapse, would like it to open one at a time:

$(".repeatingClass h3").click(function() {
      $(".collapse-this").slideToggle("slow");
});

I have searched for a solution and came across using $(this) but I am a little stuck. So hopefully someone can help.


Solution

  • Hard to tell without knowing your markup, but you should give a common class for your .a, .b etc. elements. Then you could use:

    $(".repeatingClass h3").click(function() {
         $(".collapse-this", $(this).closest('.repeatingClass')).slideToggle("slow");
    });
    

    .closest() will find the first parent that matches the selector (.repeatingClass), and then I'm using it as the context of the .collapse-this lookup. This means that it will search only in the given context, and its equivalent to $(this).closest('.repeatingClass').find('.collapse-this').

    jsFiddle Demo to see I'm not lying ;)