Search code examples
jqueryslidetoggle

isolating jquery toggle multiple buttons


How do I use class names with JQuery slideToggles, but only toggle the clicked trigger?

Super simplistic mockup of layout: JSFiddle here

$(document).ready(function() {
$('.togbar').on('click', function() {
$('.togcon').slideToggle('slow');
$('i', this).toggleClass('fa-angle-up');
});
});

What I want to achieve: JQuery slide toggles to show/hide content when clicked. Only the clicked trigger should reveal its contents.

Problems I'm having: This is for miniprofile information on a JCINK forum. There will be a miniprofile on every post. I must use class names, not IDs (IDs are automatically generated and I cannot realistically initiate the script for every post number). Using class names, however, makes every instance of the miniprofile show or hide on click.

What I've done to solve the problem: Scoured stack overflow. I've seen some similar questions answered, but none of the solutions have worked for me (most likely due to user failure. I don't understand all of the answers I've seen, and the most simplistic answers that I can wrap my mind around have not worked as anticipated when I tried incorporating them).

The closest I've come to solving the problem was via this question & answer

I apologize in advance if this is not a good question. I'm comfortable with HTML and CSS, but not proficient by any means. Javascript and JQuery are entirely out of my comfort zone. This is my first attempt to ask for help on stackoverflow. Please be gentle. I'm happy to edit my question if you can help me phrase it better.


Solution

  • Your selector is too broad: $('.togcon') is getting everything on the page with that class name. So you're executing the .slideToggle('slow') method on all of them too.

    You can use the siblings() selector to keep it in the context of the clicked .togbar element.

    https://api.jquery.com/siblings/

    Example:

    $(document).ready(function() {
      $('.togbar').on('click', function() {
    
        // $(this) is a reference to the specific .togbar element that was clicked.
        // .siblings('.togcon') gets the element at the same level as the .togbar with the class='togcon'
        $(this).siblings('.togcon').slideToggle('slow');
        $('i', this).toggleClass('fa-angle-up');
      });
    });
    

    Updated Fiddle: http://jsfiddle.net/zf7b0e9m/