-1

So I have this problem that I guess is a walk in the park to fix.

I'm using the JS snippet below on a website I'm building and what the snippet does is it creates accordions for some HTML elements where the class .bapf_head is the header (control) of the accordion and the .bapf_body is the expand/collapse.

I wrote the if logic where the function checks if the .bapf_body is opened or not and will then add or remove a class to the .bapf_head depending on the state. This then results in a +/- symbol that indicates open/close depending on the state.

So the problem is that I have multiple Div's that uses the same class names and all of them gets updated with the .open class name when one of the accordions are opened or closed. So let's say I have three accordions and I open one of them, then all three gets the class .open added and hence all gets the '-' symbol even though only one accordion is open.

Anyone knows how to make sure only the clicked accordion gets the updated class-name rather then all of the accordions at the same time?

Code below;

jQuery(document).ready(function($) {
    $(".bapf_head").click(function () {
        $header = $(this);
        $content = $header.next();
        $content.slideToggle(300, function () {
            $header.text(function () {
                if ($content.is(":visible")) {
                    $(".bapf_head").addClass("open");
                } else {
                    $(".bapf_head").removeClass("open");
                };          
            });
        });
    });
});
Luca
  • 9,259
  • 5
  • 46
  • 59
Edvin Uddfalk
  • 381
  • 3
  • 13
  • Does this answer your question? [Apply function to only one div class, not all](https://stackoverflow.com/questions/6347016/apply-function-to-only-one-div-class-not-all) – Heretic Monkey Apr 05 '21 at 22:15
  • The logic inside `text(function)` has nothing to do with text. – charlietfl Apr 05 '21 at 22:22

1 Answers1

1
     if ($content.is(":visible")) {
         $(this).addClass("open");
     } else {
         $(this).removeClass("open");
     };  

you need to reference the event-related DOM element, not select all the ones with that class

also, .click() is long deprecated afaik, you should use .on('click', ...

Luca
  • 9,259
  • 5
  • 46
  • 59