When a single piece of content is exposed, it has the power to bring down all

I've been working with some code where clicking on a specific button toggles the visibility of certain contents. It's functionality is satisfactory, but I want to take it a step further. In addition to showing and hiding content, I also want to ensure that only one piece of content can be open at a time. This means that when one content is opened, any other open content should automatically close. However, my attempts to achieve this have failed so far. How can I accomplish this?

This is my current code:

var coll = document.getElementsByClassName("colps");
for (let i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
      coll[i].innerHTML = 'open';
    } else {
      content.style.display = "block";
      coll[i].innerHTML = 'close';
    }
  });
}
.container {
  width: 30%;
}
.colps {
  background-color: lightblue;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  outline: none;
  font-size: 15px;
}
.active,
.colps:hover {
  background-color: dodgerblue;
}
.cont {
  padding: 10px;
  margin: 0;
  display: none;
  background-color: #f1f1f1;
}
<div class="container">
  <button type="button" class="colps">open</button>
  <p class="cont">Lorem ipsum dolor sit amet</p>
  <button type="button" class="colps">open</button>
  <p class="cont">Lorem ipsum dolor sit amet</p>
  <button type="button" class="colps">open</button>
  <p class="cont">Lorem ipsum dolor sit amet</p>
</div>
I've searched through various questions and answers in an attempt to solve this issue myself, but I haven't found the solution I'm looking for. Any assistance would be greatly appreciated.

Answer №1

Here is a solution you can try out. The code utilizes nested iteration using forEach and collapses all other elements when one button is clicked.

var coll = document.querySelectorAll(".colps");

coll.forEach(p => {
  p.addEventListener("click", function(e) {
    coll.forEach(p2 => {
        p2.nextElementSibling.style.display = "none";
        p2.innerHTML = 'open';
    });
    
    p.classList.toggle("active");
    var content = p.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
      p.innerHTML = 'open';
    } else {
      content.style.display = "block";
      p.innerHTML = 'close';
    }
  });
});
.container {
  width: 30%;
}

.colps {
  background-color: lightblue;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  outline: none;
  font-size: 15px;
}

.active,
.colps:hover {
  background-color: dodgerblue;
}

.cont {
  padding: 10px;
  margin: 0;
  display: none;
  background-color: #f1f1f1;
}
<div class="container">
  <button type="button" class="colps">open</button>
  <p class="cont">Lorem ipsum dolor sit amet</p>
  <button type="button" class="colps">open</button>
  <p class="cont">Lorem ipsum dolor sit amet</p>
  <button type="button" class="colps">open</button>
  <p class="cont">Lorem ipsum dolor sit amet</p>
</div>

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

The Model.findOneAndRemove() method has been updated and can no longer accept a callback function, resulting in

const express = require('express') const mongoose = require('mongoose') var app = express() var Data = require('./noteSchema') mongoose.connect('mongodb://localhost/newDB') mongoose.connection.once("open" ...

How can I implement user account functionality with only JavaScript in an Angular frontend and Node.js/Express server?

Many resources I've come across utilize php or a similar language. With an Angular frontend and Node/express server code in place, but no backend yet, I'm uncertain about how to approach user sign-up. ...

Guide on comparing an object against an array and retrieving a specific output

If I were to create a data structure like this: const carObj = {"1234":"Corvette","4321":"Subaru","8891":"Volvo"}; And also have an array that contains the IDs: const myArray = [1234, 4321, 8891, ...

Unifying flex and position:fixed

I'm having difficulties when it comes to displaying a modal dialog with a fixed position within a flex layout. The header and footer of the dialog need to be set in height, while the content section should have overflow with scrollbars. I chose the fl ...

What is the best way to incorporate a custom event listener into my React Native component?

Hello everyone, I am currently working with React Native+Expo and have created a custom component called a stepper. Here's how it looks: https://i.sstatic.net/CfQcl.png Below is the code for this custom stepper: import React, { useState } from ' ...

Show information stored in Angularjs2 file (.ts) within an HTML document

Here is the code snippet from my .ts file: constructor( private config : ConfigService, private http: Http){ this.getWS('ngoName') .do((data) => { console.log(data); this.saveObj(data); }).to ...

Arrange your HTML pages using the Bootstrap 4 Navigation Bar

Inquiry: What is the standard or best practice for organizing multiple HTML sites or files with a navigation bar that should be visible on all pages? Background: As a beginner in website creation, I am working on a project to run on an ESP using Bootstrap ...

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

Does WebSVG struggle with producing sharp, defined lines in its inline format?

Upon page load, my SVG background starts as separated and then smoothly transitions into forming the background. However, I noticed that a large triangle with poor quality and choppiness appears at the beginning. What could be causing this issue? For an e ...

Unexpected results from CSS nth-child selector

Creating a dynamic table and updating its cell values accordingly while handling asynchronous returns brings about some challenges. The number of columns can vary, but the rows remain constant within this section of the table (7 rows). When trying to upda ...

Ways to enlarge the font size of a hyperlink

I am just starting out with coding and I need to figure out how to increase the font size of my link. <!DOCTYPE html> <html> <head> <style> /* unvisited link */ a:link { color: #FFFFFF; } /* visited link */ a:visited { color: #FF ...

What could be causing the browser.get method to fail to redirect to the specified URL?

I have organized my files in a folder structure that looks like this: project structure Currently, I am following the steps outlined in this particular tutorial The contents of my package.json file are as follows: { "name": "node_cucumber_e2e", "ver ...

Ways to dismiss a Modal popup instantly without having to wait for an ajax response

I am currently facing an issue with sending email attachments through ajax. The process takes too long to send and close the email modal window. I am looking for a solution where the modal window closes immediately after clicking the send email button, all ...

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...

unable to retrieve the properties of req.user

Currently, I am working on developing a multiplayer game that involves a login system. Within my app.js file, the following code snippet allows me to access user information: app.use(function (req, res, next) { res.locals.success_msg = req.flash('s ...

What is the best way to manipulate an input field in a controller if the input is not connected to an ng-model?

Received some backend-rendered HTML code. Here is the HTML code: <form name="mk" ng-submit="submit()"> First name:<br> <input type="text" name="firstname" value="Mickey"> <br> Last name:<br> <input ty ...

tips for incorporating margin without sacrificing responsiveness

Having an issue with three cards in a row, they are too close together without any margin. It doesn't look good, so I tried adding margin, but it messes up the responsiveness that Bootstrap provides. So, I decided to add padding only. Any suggestions ...

Crafting a unique datalist from an XML file with the help of jQuery

<mjesta> <mjesto>Zagreb</mjesto> <mjesto>Split</mjesto> <mjesto>Ploce</mjesto> <mjesto>Pula</mjesto> <mjesto>Pazin</mjesto> <mjesto>Daruvar</mjesto> <mjesto>Bjelovar</mj ...

Technique for ensuring consistent kerning across various browsers

Seeking advice on implementing kerning technique for a logotext in the <header>, ensuring cross-browser compatibility. Using this helpful tool created by Mr. Andrew (special thanks), I found a solution. Prior to the modification, the <header> ...

When a npm package consists of multiple files, what is the best way to import them?

I have an npm package that consists of three files in the dist folder, generated by webpack: https://i.sstatic.net/td5Us.png Within the package.json file, I have designated the sample.js file as the main one: "main": "dist/sample.js", ...