Troubleshooting problem with accordion card within a JavaScript array

I am currently facing an issue with my list display that fetches data from a database. The problem lies in the accordion feature not functioning properly when integrated into a JavaScript array, yet it works perfectly when directly inserted into HTML code. I'm perplexed about what might be causing this failure to execute the accordion feature. I would greatly appreciate any insights on why this isn't working and how to rectify it. Thank you.

Below is the JavaScript code snippet:

<script>
    var acc = document.getElementsByClassName("accordionList");
    var i;

    for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function() {
        this.classList.toggle("activeLink");
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
        } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
        } 
    });
    }

    $(function() {
        // AJAX call to retrieve data and dynamically create table rows
    });
</script>

HTML Code:

// Table structure with dynamic data insertion using HTML templating

// This will automatically populate table rows upon retrieving data.

CSS Styles:

/* Styling for the accordion functionality */

/* CSS styles for the accordion component */

Answer №1

  1. Upon page load, JavaScript dynamically adds a click event for elements with the class name: "accordionList"
  2. When new data is fetched and elements are created, the click event is not attached to them and thus does not work on those elements

If you are using jQuery, I recommend structuring your code like the example below: (Note: CSS styles have been modified for the .panel class and example data records are provided)

$(document).on('click', '.accordionList', function(){
  $(this).toggleClass('activeLink')
  $(this).next().toggle(200)
})
// Data Example
const records = [
  {
     logo: 'test',
     company : 'company',
     role: 'role',
     location: 'location',
     dateCreated: 'dateCreated',
     status : 'status',
     roleDescription: 'roleDescription',
     companyDescription: 'companyDescription'
  }
]
// Loop through records and append table rows dynamically
$.each(records, function (k, f) {
    let tblRow = "<tr>" + 
    "... more HTML structure here ..."
    $(tblRow).appendTo("#userdata tbody")
})
.accordionList {
        background-color: rgb(255, 255, 255);
        color: rgb(0, 0, 0);
        cursor: pointer;
        padding: 18px;
        width: 100%;
        border: none;
        text-align: left;
        outline: none;
        font-size: 15px;
        transition: 0.4s;
    }

... more CSS styles here ...
    
    .panel {
        ... panel CSS styles ...
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="userdata" style="width: 100%;">
    <tbody id="jobsData">
        <tr>
            <td>
                ... more HTML structure here ...
            </td>
        </tr>
    </tbody>
</table>

$(document).on('click', '.accordionList', function(){
  $(this).toggleClass('activeLink')
  $(this).next().toggle(200)
})

The click event is delegated from document to elements with the class .accordionList

Update: Please format your HTML structure according to this example image.

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

Link together a series of AJAX requests with intervals and share data between them

I am currently developing a method to execute a series of 3 ajax calls for each variable in an array of data with a delay between each call. After referring to this response, I am attempting to modify the code to achieve the following: Introduce a del ...

Populating a VBA array based on specific conditions

Recently, I've been dedicating time to creating a Word macro in VBA that aims to streamline the process of certain documents. The goal is to automate populating the second column of a table with procedures based on numbers listed in the first column. ...

Using jQuery idle timeout to abort jQuery AJAX calls in Laravel 5.2

Currently, I have implemented the jQuery Idle Timeout plugin in my Laravel 5.2 system. Everything works perfectly on my local setup using MAMP Pro, but upon uploading it to the development server, I encountered an "Aborted" error in the AJAX get request: ...

The shared service is experiencing difficulties in transferring data to the following component

I have developed two components along with a shared service. My goal is to transfer data from one component to another, but I am encountering an issue where the object appears empty. Below is the code for the first component: import { Component, OnInit } ...

Text that changes within a set-sized box

I'm working with a fixed-size div that contains dynamically generated text. Is there an easy method using DOJO or plain Javascript to truncate the text before the end of the div and add "..."? How can I accomplish this regardless of the font size bein ...

Locating the maximal value within a column of an array

This is the code from the first source file. #include<stdio.h> void main(void) { extern int transitTime[]; int time1; int i,j; int largest; printf("Please enter the time you left school.\n"); scanf("%d",&time1); ...

Create a repeating function that will show an image based on the specific class assigned to each individual element

Can someone help me create a function that automatically applies to all divs with a specific class on my document? I want the function to check for the presence of another class within those divs and display an image accordingly. document.getElementsByCla ...

You have encountered an error: [ERR_HTTP_HEADERS_SENT]. This means that you cannot set headers after they have already been sent to the client, even if a return

I've encountered a 'Cannot set headers after they are sent to the client' error with the /api/users/profile route and have been attempting to resolve it. I stumbled upon some solutions on stackoverflow suggesting to add a return statement - ...

Could the Google Font "Exo 2" be causing the size issue with HTML Canvas 2DContext.font?

As I work on creating a canvas and adding text to it, I have encountered an issue with the font Exo 2. Every other font works perfectly except for this one. Exo 2 is a Google font, and my suspicion is that the number "2" at the end of the name might be ca ...

I'm encountering a perplexing index out of bounds error and I can't seem to figure out the cause. I'm feeling completely stuck at

I encountered an index out of bounds exception while working in Scala, and I am puzzled as to why. val rawData = "4x23x21\n22x29x19\n11x4x11\n8x10x5" val data = rawData.split('\n') data.map(x => x.split('x')(1)) ...

Is jQuery .ajax not able to make CORS request while Native XMLHttpRequest() successfully does?

When I use the vanilla XMLHttpRequest() object to make a CORS request, it works perfectly fine. However, when I try using the jQuery.get() function, it tells me that cross-origin requests are not allowed. This is confusing because $.get() is built on top o ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

What is the best way to modify the state of an array of objects by applying a filter in Vue 3?

I am currently facing an issue with a component that is listening for an emit and then attempting to filter out a user with a specific userId from the users state. The challenge lies in the fact that assigning filteredUsers to users does not appear to be ...

Encountered ENOENT error while setting up create-react-app

Recently delved into the world of React by taking an online course on Udemy. However, I encountered a sudden issue with my create-react-app and received this error log. Installing packages. This may take a few minutes. Installing react, react-dom, and ...

Error encountered: Adding element to array failed due to index being out of array bounds

In my current project, I have an array where I append new options. These options are then displayed in a table that consists of 3 sections. The first two sections each have only one row, while the third section can have a variable number of rows depending ...

I am planning to create a test case using Postman to verify the following scenario

Can you suggest a test case in Postman to verify that the Material ID has a length of 14 and the material department is "OT" based on the provided JSON response? { "success": "true", "Result": { "Response": ...

Using ES6 Babel with multiple package.json files

For a large project, I am looking to break it down into multiple package.json files. This way, the dependencies for each part can be clearly defined and exported as separate entities. However, my goal is to compile all of these packages using webpack and ...

Create a PHP file with various functions and access them using jquery.post or jquery.get in a separate JavaScript file

Is there a way to call multiple PHP functions from my JavaScript file using Jquery.post? Typically, we use Jquery.post to call a PHP file and pass various values as post data. function new_user(auth_type, tr_id, user_name, email) { $.post("bookmark.p ...

Label it as submit ID rather than value or label

Check out this awesome plugin called https://github.com/aehlke/tag-it. It's really cool! Here is the issue I'm facing: <input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true"> Tags:<br ...