jQuery Accordian malfunctioning for all elements except the first one in the list

Trying to implement an accordion feature that can be utilized across the entire website. The current logic seems to be partially functional... When I click on any of the accordions, it should open by adding a 'show' class, but this only works for the first accordion in the parent container.

Sometimes all the accordions open simultaneously, but the desired functionality is to allow users to individually open and close each accordion on the page.

(function ($) {

    $(".accord").on("click", function (e) {
    
    console.log(this);
    
      $(".accordian-content").toggleClass("show");

    });

})(jQuery);
.accord {
    background-color: $primary;
    color: #111;
    cursor: pointer;
    padding: 10px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
}
.accordian-content {
    display: none;
}

.accordian-content.show {
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<ul>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>

<!-- Repeat the above button code for other accordions -->

</ul>

Answer №1

Your code

$(".accordian-content").toggleClass("show");
scans the entire DOM structure for elements with the class '.accordian-content' and toggles the class show for all matching elements.

Since your content is always nested within the .accord element, you can utilize $(this) in the click event to target the clicked element. By doing this, you can then use .find(SELECTOR) to search for a specific child element, such as .accordian-content, resulting in the desired element being displayed.

(function ($) {

    $(".accord").on("click", function (e) {
    
    // Updated this Line to target the Accordian-content that is a child of the clicked 'accord'-button
      $(this).find('.accordian-content').toggleClass("show");

    });

  })(jQuery);
.accord {
    background-color: $primary;
    color: #111;
    cursor: pointer;
    padding: 10px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
  }
  .accordian-content {
    display: none;
  }

  .accordian-content.show {
    display: block;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<ul>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>
</ul>

Answer №2

Utilizing unique identifiers can be a more efficient approach when determining which item has been clicked and applying that ID to the accordian template.

By incorporating IDs into your text and adjusting the JavaScript code slightly, you can easily match the number from the clicked div with the corresponding accordian content control.

One added advantage of using unique IDs is the ability to target a specific accordian to open on page load by referencing the ID. This simplifies the process compared to not having an ID. Whether this functionality is necessary depends on your requirements.

(function ($) {

    $(".accord").on("click", function (e) {
    
    let accordian = this.id.replace('accord', 'accordian-content')
    
      $('#' + accordian).toggleClass("show");

    });

  })(jQuery);
.accord {
    background-color: $primary;
    color: #111;
    cursor: pointer;
    padding: 10px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
  }
  .accordian-content {
    display: none;
  }

  .accordian-content.show {
    display: block;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<ul>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer" id="accord1">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content" id="accordian-content1">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer" id="accord2">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content" id="accordian-content2">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>
<li>
    <button class="accord menu w-full my-[15px] cursor-pointer"  id="accord3">
        <div class="menu-item flex align-center p-2 justify-between gap-2 bg-primary">
            <div class="title uppercase text-white font-bold"><?php echo $title; ?></div>
            <span class="icon text-white scale-y-150 pr-[17.5px]">+</span>
        </div>
        <div class="accordian-content" id="accordian-content3">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos totam, explicabo deserunt eaque molestiae dolorem perspiciatis? Eius iure veniam nulla architecto necessitatibus culpa debitis maxime velit voluptatum eos nesciunt quidem eveniet deleniti deserunt vel nemo ipsa beatae, harum dolore eligendi sequi quo unde. Adipisci minima id iste in nostrum voluptatibus.</p>
        </div>
    </button>
</li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery navigation is experiencing issues due to conflicting buttons

I am currently developing a web application that features two buttons in the header: Share and Options. When a button is clicked, its related content expands and collapses when clicked again. The issue arises when the user clicks on the share button and th ...

Encountering difficulties when trying to set up popovers in Bootstrap

I'm currently working on enhancing an Angular application developed by someone else. My task involves adding a popover feature. The HTML code is located within an ng-include template and includes the following tag: <p class="filetracker-label" dat ...

Revamp your D3 interactive graph with real-time data updates from the server!

I am looking to enhance a graph in D3 (or another visualization library) by completing the following steps: When a user clicks on an item, like a node within the graph, New data is fetched from the server, The new data is then used to add new edges and n ...

I am unable to display the content even after setting `display: block` using the `.show()`

Hello there, I have attached my javascript and html code. While in debug mode, I can see that the CSS property 'display: none' changes to 'display: block', but for some reason, the popupEventForm does not open up. Any suggestions on why ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Is it possible for an ajax request to complete even if a page redirection occurs?

In my current project, I am attempting to generate a temporary URL for a local image and submit it to Google for an Image Search. I need this URL to be transient and automatically deleted after the search is complete. Here's the code snippet that I ha ...

Tips for creating an oval on Google Maps V3

I am struggling to create an oval shape on Google Maps V3. The current method I am using involves a series of polygons, but it is challenging to achieve a smooth oval shape as you can see in my JSFIDDLE. Is there a more efficient way to accomplish this? ...

What is the most effective way to save numerical information to a file?

Imagine a scenario where there is an array filled with one million random numbers: [ 0.17309080497872764, 0.7861753816498267, ...] The task at hand is to store these numbers onto a disk for future retrieval. While storing them in text formats like JSON or ...

Having trouble with spawning child processes asynchronously in JavaScript

I'm trying to figure out how to format this code so that when a user clicks a button, new input fields and redirect buttons are asynchronously inserted into the unordered list. Everything was working fine until I added the redirect button insertion fu ...

Executing several GET requests in JavaScript

Is there a more efficient way to make multiple get requests to 4 different PHP files within my project and wait for all of them to return successfully before appending the results to the table? I have tried nesting the requests, but I'm looking for a ...

JavaScript function using recursion returning an undefined value

I have created a function that generates a random number and checks if it already exists in an array. If it does, the function generates a new number until a unique one is found and adds it to the array. However, I am encountering an issue where the functi ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Sorting through an array of objects based on a key and value that match another object

Is it possible to filter or query an array with the following structure? [ { 'xml:id': 'Name1', sex: { '$t': 'M' }, occupation: { n: 1 ...

The Angular router seems to be refusing to show my component

My Angular 2 App includes a Module called InformationPagesModule that contains two lazy load components (Info1 Component and Info2 Component). I would like these components to load when accessing the following routes in the browser: http://localhost:4200/ ...

The JavaScript library known as Microsoft JScript Angular is not recognized

While integrating Angular into my .Net MVC website, I keep running into a runtime error that reads as follows: 0x800a1391 - Microsoft JScript Runtime Error: 'angular' is undefined. This essentially means that the 'angular' object ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

Steps to execute a JSON file once another JSON has been successfully loaded

I'm facing a similar challenge to the one presented in this question. However, I need to load an additional JSON file after the when() method is executed. Essentially, I want to retrieve JSON data within the when() function and then use that informati ...

The Full Screen Button on Google Maps isn't functioning properly in a third-party mapping application

Below you will see the '+' icon which is also supposed to function as the full screen button. https://i.stack.imgur.com/IMvHa.png However, when clicked on, it does not expand to full screen as intended. I have attempted using some basic jQuery ...

A little brain teaser for you: Why is this not functioning properly on Google Chrome?

Have you noticed that the code below works perfectly in Firefox, but fails in Chrome when trying to 'post' data? $("a").click(function() { $.post("ajax/update_count.php", {site: 'http://mysite.com'}); }); Hint: Make sure you are us ...

Automatically expanding PrimeNG Turbotable rows

I am using a PrimeNg turbotable that has a row expansion feature enabled. I am looking for a way to automatically expand the rows by default when the table loads. Shown below is my code: HTML <p-table [columns]="cols" [value]="cars" dataKey="vin"> ...