Creating an accordion using an array in JavaScript: A step-by-step guide

I'm experimenting with creating an accordion using HTML, CSS, and JavaScript. I've managed to set it up, however, the array text is only displaying in one accordion item and the buttons are not functioning for each individual accordion. Is there a way to display the text from each object in the array and make all buttons work independently? Any suggestions on how I can achieve this would be greatly appreciated. Thank you!

const datas = [ {
    title: "Can you accept all credit cards",
    content:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, ipsa? Nam nobis repudiandae ullam,",
},
{
    title: "Can you accept all credit cards",
    content:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, ipsa? Nam nobis repudiandae ullam,",
},
{
    title: "Can you accept all credit cards",
    content:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, ipsa? Nam nobis repudiandae ullam,",
}
];



let container = document.querySelector(".container");
let accordion = document.querySelector(".accordion");
let accordion__content = document.querySelector(".accordion__content");


let  accordion__show = document.querySelector(".accordion__show");


datas.map((data)=> {
accordion__show.addEventListener("click" , (e)=> {
    e.preventDefault();
accordion__content.classList.toggle("show_text");
accordion__content.innerHTML =  datas[0].content;

  if ( accordion__show.innerHTML === "+") {
     accordion__show.innerHTML = "-";
  } else {
accordion__show.innerHTML = "+"; 
 }

})
})
@import url('https://fonts.googleapis.com/css2?family=Quicksand&display=swap');

body  {
    padding: 0;
    margin: 0;
    background-color: #F2F7FE;
    font-weight: bold;
    font-family: 'Quicksand',sans-serif;
}

main {
        width: 100%;
    min-height: 500px;
        display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: column;
    justify-content: center;
}
.container {
    width: 100%;
    min-height: 500px;
        display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
}

.accordion__content {
    display: none;
}

.show_text {
    display: flex;
    align-items: center;
    justify-content: center;
     padding: 20px;
}




.accordion {
    width:calc(650px - 30px);
    background-color: white;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);

display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
flex-wrap: wrap;
}

.accordion__header {
    width: 100%;
    min-height: auto;
    display: flex;
    text-align: center;
    align-items: center;
    justify-content: space-around;
    flex-direction: row;
}

.accordion button {
    border:2px solid gray;
    background-color: transparent;
    padding: 10px 15px;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

        <div class="main">
        <div class="container">
            <div class="accordion">
<div class="accordion__header">
    <h1>Do you accept all credit cards?</h1>
    <button class="accordion__show">+</button>
</div>
            <p class="accordion__content"></p>
                </div>
                    <div class="accordion">
<div class="accordion__header">
    <h1>Do you accept all credit cards?</h1>
    <button class="accordion__show">+</button>
</div>
            <p class="accordion__content"></p>
                </div>
                    <div class="accordion">
<div class="accordion__header">
    <h1>Do you accept all nonsense cards?</h1>
    <button class="accordion__show">+</button>
</div>
            <p class="accordion__content"></p>
                </div>
        </div>
        </div>
    <script src="script.js"></script>
  </body>
</html>

Answer №1

I made a slight modification to your javascript code by replacing the map() function with forEach().

Furthermore, when referencing accordion__content and accordion__show, it is recommended to treat them as a collection using querySelectorAll():

let accordion__content = document.querySelectorAll(".accordion__content");
let accordion__show = document.querySelectorAll(".accordion__show");

const datas = [{
        title: "Can you accept all credit cards?",
        content: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, ipsa? Nam nobis repudiandae ullam.",
    },
    {
        title: "Can you accept all credit cards?",
        content: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, ipsa? Nam nobis repudiandae ullam.",
    },
    {
        title: "Can you accept all credit cards?",
        content: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Omnis, ipsa? Nam nobis repudiandae ullam.",
    }
];


let container = document.querySelector(".container");
let accordion = document.querySelector(".accordion");
let accordion__content = document.querySelectorAll(".accordion__content");
let accordion__show = document.querySelectorAll(".accordion__show");


accordion__show.forEach(function (current, index) {
    current.addEventListener("click", (e) => {
        e.preventDefault();
        accordion__content[index].classList.toggle("show_text");
        accordion__content[index].innerHTML = datas[0].content;

        if (current.innerHTML === "+") {
            current.innerHTML = "-";
        } else {
            current.innerHTML = "+";
        }

    })
})
@import url('https://fonts.googleapis.com/css2?family=Quicksand&display=swap');
body {
    padding: 0;
    margin: 0;
    background-color: #F2F7FE;
    font-weight: bold;
    font-family: 'Quicksand', sans-serif;
}

main {
    width: 100%;
    min-height: 500px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: column;
    justify-content: center;
}

.container {
    width: 100%;
    min-height: 500px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
}

.accordion__content {
    display: none;
}

.show_text {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.accordion {
    width: calc(650px - 30px);
    background-color: white;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
}

.accordion__header {
    width: 100%;
    min-height: auto;
    display: flex;
    text-align: center;
    align-items: center;
    justify-content: space-around;
    flex-direction: row;
}

.accordion button {
    border: 2px solid gray;
    background-color: transparent;
    padding: 10px 15px;
}
<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>repl.it</title>
      <link href="style.css" rel="stylesheet" type="text/css" />
   </head>
   <body>
      <div class="main">
         <div class="container">
            <div class="accordion">
               <div class="accordion__header">
                  <h1>Do you accept all credit cards?</h1>
                  <button class="accordion__show">+</button>
               </div>
               <p class="accordion__content"></p>
            </div>
            <div class="accordion">
               <div class="accordion__header">
                  <h1>Do you accept all credit cards?</h1>
                  <button class="accordion__show">+</button>
               </div>
               <p class="accordion__content"></p>
            </div>
            <div class="accordion">
               <div class="accordion__header">
                  <h1>Do you accept all nonsense cards?</h1>
                  <button class="accordion__show">+</button>
               </div>
               <p class="accordion__content"></p>
            </div>
         </div>
      </div>
      <script src="script.js"></script>
   </body>
</html>

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

Can the combination of pure HTML+JS applications with .NET webservices be both feasible and safe?

Our recent projects have utilized MVC5 with AngularJS, Ninject, Bootstrap, and various other technologies. However, we found that these applications required significant time to fix bugs and add features due to unnecessary complexity. Would it be feasible ...

Angular application experiencing issues with Bootstrap modal functionality

I'm attempting to utilize a Bootstrap modal within an Angular application by using classes in HTML, but it doesn't seem to be working - the modal is not displaying <div class="modal text-center" *ngIf="showmodal" tabindex=& ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

Organize Radio Selectors

My intention was to align the radio buttons as shown in the image below: https://i.stack.imgur.com/oPTjD.jpg However, the final result looked like this https://i.stack.imgur.com/Mixga.jpg Below is the code for your reference HTML <div class="form ...

Using Angular ng-token-auth to post to an incorrect localhost address

I have a Node.js server running on http://localhost:3000/, and a React Frontend running on http://localhost:8000/. I am setting up the user authentication feature with JWT. However, when posting the token, it goes to the incorrect localhost address: http ...

Shift visual elements using measurements

Let's say my image size is 960x960, but the height of the img element is set to 720px. <img class="imgs" src="~/test.jpg" /> Here are the styles for .imgs: .imgs { width: 100%; height: 45rem; object-fit: cover; } ...

Creating a node server with Express allows for the seamless injection of dynamic HTML content into the index.html file using the res

I set up a mock node.js server using express and have created a dummy Index.html. The HTML file contains a simple form: <form action="/results" method="post" enctype="multipart/form-data"> <input type=" ...

Having difficulty converting the string data to HTML using JavaScript in a Node.js Express application

In my app.js file, I will be sending data to an EJS file. app.get('/', function (req, res){ Blog.find({}, function(err, fountItems){ Blog.insertMany(defaultBlog, function(err){ }) } res.render( ...

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...

elements positioned next to each other with gaps in between

Why is it so challenging to position two divs next to each other with a small space between them? I've attempted <div class="wrapper"> <div class="box" style="background-color: pink;">First Div</div> <div class="spacer">& ...

Exploring Ruby Array Indexing

Similar Question: Understanding Array Slicing in Ruby and Its Behavior (from Rubykoans.com) Upon running the provided code on my Ruby interpreter, I noticed that arr[7..4] outputs nil while arr[6..4] doesn't output anything. arr = [1, 2, 3, 4, 5 ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

Create a JavaScript and jQuery script that will conceal specific div elements when a user clicks on them

Within my navigation div, there exists another div called login. Through the use of JavaScript, I have implemented a functionality that reveals additional divs such as login_name_field, login_pw_field, register_btn, do_login_btn, and hide_login upon clicki ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

Tips for placing a large image within a small div

I have an image with a ratio of 1920*1300 that I want to be displayed on any device the website is viewed and cover the entire div. Check out my code below: .carousel { width: 100vw; height: 80vh; position: relative; } .carousel a { width: 1 ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

How can I ensure that my rendering only occurs after a full input has been entered? Implementing a delayed render() in ReactJS

Im working on a form that includes Controlled Component text inputs: <input type="text" onChange={(e) => this.props.changeBusiness(e)}/> I'm thinking of rendering the above text input in a separate component. It would be great if I could re ...

Strange behavior observed in Google Maps when using multi-colored polylines

Take a look at the code snippet below : View Sample Html In the code, two Polylines are defined. Although the first one is set to display in red, both lines appear in yellow. If I swap the order of variable definitions like so: var route1 = var route ...

How can I implement the delete button in a recently appended table row using the clone() function in jQuery?

Whenever I click the Add button, a new row gets appended to the HTML table. You can check out the jsFiddle link for reference: http://jsfiddle.net/fgLHN/3/ The code above functions smoothly for me. However, I'm facing an issue when trying to add a de ...

java ArrayList

It's been a while since I worked with Java last, and I'm looking to refresh my memory on a few things. import java.util.*; public class bitStrings { public static void main(String [] args){ Scanner inputBitString = new Scanner(Syst ...