Begin by opening a single div for each instance

I want a functionality where opening one div closes all the others. I've searched around for solutions and only found jQuery options, not pure JavaScript ones.

Here is my code:

function openDescription(description_id) {
    var x = document.getElementById(description_id);
    if (x.style.display === "block") {
        x.style.display = "none";
    } else {
        x.style.display = "block";
    } 
};
.row_team_pic{
  text-align:center;
  margin:-72px;
  margin-top:0px;
  margin-bottom: 15px;
}
.container{
  background-color:silver;
    width:150px;
    display:inline-block;
  margin-top:0px;
  margin-left:10px;
}

.photo{
    min-height:125px;
    width:125px;
    margin:10px;
    padding-top:10px;  
}

.name{
  text-align: center;
    padding-bottom: 10px;
  cursor: pointer;
}
.description1{
  float:left;
  margin-left:0%;
  margin-top:10px;
  background-color:silver;
  width:322px;
}
.description2{
  float:left;
  margin-left:-57%;
  margin-top:10px;
  background-color:silver;
  width:322px;
}
.description3{
  float:left;
  margin-left:-57%;
  margin-top:10px;
  background-color:silver;
  width:322px;
}
.description4{
  float:left;
  margin-left:-114%;
  margin-top:10px;
  background-color:silver;
  width:322px;
}
<div class="row_team_pic" id="riga1">
    <div class="container">
  <div class="photo">
    <img src="#" alt="" width="125" height="125"/>
  </div>
  <div class="name" onclick="openDescription('description1')">Name1</div>
  <div class="description1" id="description1_id" style="display:none">
    It's ok. It's working. It's ok. It's working. It's ok. It's working. 
          It's ok. It's working. It's ok. It's working. 
  </div>
</div>

<div class="container">
  <div class="photo">
    <img src="#" alt="" width="125" height="125"/>
  </div>
  <div class="name" onclick="openDescription('description2_id')">Name2</div>
  <div class="description2" id="description2_id" style="display:none">
    It's ok. It's working. It's ok. It's working. It's ok. It's working. 
          It's ok. It's working. It's ok. It's working. 
  </div>
</div>

<div class="container">
  <div class="photo">
    <img src="#" alt="" width="125" height="125"/>
  </div>
  <div class="name" onclick="openDescription('description3_id')">Name3</div>
  <div class="description3" id="description3_id" style="display:none">
    It's ok. It's working. It's ok. It's working. It's ok. It's working. 
          It's ok. It's working. It's ok. It's working. 
  </div>
</div>

<div class="container">
  <div class="photo">
    <img src="#" alt="" width="125" height="125"/>
  </div>
  <div class="name" onclick="openDescription('description4_id')">Name4</div>
  <div class="description4" id="description4_id" style="display:none">
    It's ok. It's working. It's ok. It's working. It's ok. It's working. 
          It's ok. It's working. It's ok. It's working. 
  </div>
</div>

For instance, when I click on name2, it should display description2, but if I click on name3, it should close description2 and show description3 instead of overlapping them. How can I achieve this?

Answer №1

When working with the function, you need to reset the display = none for all div elements that have a class name starting with description, except for the one that was clicked. Then, only set the display = block for the div element whose id is passed to the function.

To accomplish this, include the following code within the function:

var allNames = document.querySelectorAll('[class^=description]');
allNames.forEach(function(d){
  if(d.getAttribute('id') != description_id){
    d.style.display = "none";
  }
});

Code in Action:

Answer №2

Introduce a fresh class named description to all div elements containing descriptions. Next, in your function, if the style of the element is not set to display: block, conceal all elements with the description class and only display the selected element by setting its property to display: block.

function openDescription(description_id) {
    var x = document.getElementById(description_id);
        
        if (x.style.display === "block") {
            x.style.display = "none";
        } else {
            var elements = document.getElementsByClassName('description');

            for (var i = 0; i < elements.length; i++){
                elements[i].style.display = 'none';
            }
            x.style.display = "block";
        } 
   };
.row_team_pic{
    text-align:center;
    margin:-72px;
    margin-top:0px;
    margin-bottom: 15px;
}
.container{
    background-color:silver;
    width:150px;
    display:inline-block;
    margin-top:0px;
    margin-left:10px;
}

.photo{
    min-height:125px;
    width:125px;
    margin:10px;
    padding-top:10px;  
}

.name{
    text-align: center;
    padding-bottom: 10px;
    cursor: pointer;
}
.description1{
    float:left;
    margin-left:0%;
    margin-top:10px;
    background-color:silver;
    width:322px;
}
.description2{
    float:left;
    margin-left:-57%;
    margin-top:10px;
    background-color:silver;
    width:322px;
}
.description3{
    float:left;
    margin-left:-57%;
    margin-top:10px;
    background-color:silver;
    width:322px;
}
.description4{
    float:left;
    margin-left:-114%;
    margin-top:10px;
    background-color:silver;
    width:322px;
}
<div class="row_team_pic" id="riga1">
  <div class="container">
    <div class="photo">
        <img src="#" alt="" width="125" height="125"/>
    </div>
    <div class="name" onclick="openDescription('description1_id')">Name1</div>
    <div class="description description1" id="description1_id" style="display:none">
        It's ok. It's working. It's ok. It's working. It's ok. It's working. 
        It's ok. It's working. It's ok. It's working. 
    </div>
</div>

<div class="container">
    <div class="photo">
        <img src="#" alt="" width="125" height="125"/>
    </div>
    <div class="name" onclick="openDescription('description2_id')">Name2</div>
    <div class="description description2" id="description2_id" style="display:none">
        It's ok. It's working. It's ok. It's working. It's ok. It's working. 
        It's ok. It's working. It's ok. It's working. 
    </div>
</div>

<div class="container">
    <div class="photo">
        <img src="#" alt="" width="125" height="125"/>
    </div>
    <div class="name" onclick="openDescription('description3_id')">Name3</div>
    <div class="description description3" id="description3_id" style="display:none">
        It's ok. It's working. It's ok. It's working. It's ok. It's working. 
        It's ok. It's working. It's ok. It's working. 
    </div>
</div>

<div class="container">
    <div class="photo">
        <img src="#" alt="" width="125" height="125"/>
    </div>
    <div class="name" onclick="openDescription('description4_id')">Name4</div>
    <div class="description description4" id="description4_id" style="display:none">
        It's ok. It's working. It's ok. It's working. It's ok. It's working. 
        It's ok. It's working. It's ok. It's working. 
    </div>
</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

Display loading icon in AngularJS during template retrieval

Imagine I have this specific directive: angular .module('app.widgets') .directive('myCalendarRange', myCalendarRange); function myCalendarRange () { var directive = { link: link, templateUrl: '/template/is/located ...

What is the process for exporting/importing a variable in Node.js?

What is the correct way to export/import a variable in Node.js? I attempted to use export and import methods, but I received an error message stating that it should be a module. After changing the type to module in the JSON file, it then told me that requ ...

Ways to verify if a web URL is contained within an HTML textbox

In the process of developing a frontend form for WordPress, I have incorporated a basic HTML textbox for users to input a web URL. My goal now is to ensure that the entered value is indeed a valid URL and not just arbitrary text. Is there a way to perfor ...

I am looking to retrieve information from mongodb and then transform it into a JSON object using node.js. Can you guide

I am on a mission to retrieve data from a MongoDB database and transform it into a JSON object in Node.js. The goal is to be able to easily manipulate this data as if it were a simple JSON object. Here's the current code snippet I'm working with: ...

Error: Execution time limit of 30 seconds has been surpassed, causing a fatal issue on line 64

I am attempting to style text retrieved from a SQL database, but when I try to preview it, I encounter a Fatal error: Maximum execution time of 30 seconds exceeded on line 64 . I tried setting the maximum execution time to 300 with `ini_set('max_execu ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

The background color of the columns is overwhelming

I would like to create a TV remote control design using bootstrap, but I am encountering some issues. The background color is overflowing and I'm unsure how to fix it. Please take a look at the code and feel free to offer any suggestions! @media scre ...

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

What is the best way to implement material theme colors into my Angular2 CSS?

Suppose I want to utilize the mat-primary color as a background for a div using a CSS/SASS class, how should I reference it? My initial thought was: @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; .my-class{ background-colo ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

A text box will appear when you click on the edit button

When the edit button is clicked, I need to display text boxes and list boxes. Can someone please provide suggestions on how to accomplish this? HTML: <div class="textboxes"> <ul> <li><input type="text" id="txt" /></li> ...

Drag and Drop in Angular with Dragula - Trigger Confirmation on Drop Event

I need to implement a confirm modal dialog (UI Kit) when an element is dragged into a new bag using angular 1.4.8 and angular-dragula. If the user clicks ok, the process should continue, but if they click NO, the element should return to its original bag. ...

Utilize a fluid AJAX endpoint for the Vue Select2 encapsulated component

I have customized the Wrapper Component Example based on VueJS documentation by adding the AJAX data source feature. You can view my modified code here. My goal is to dynamically set the ajax url property of my select2 component, like this: <select2 :o ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Updating a component with React JS setState() must be done on a mounted or mounting component

I encountered an issue where I am getting the error message setState(...): Can only update a mounted or mounting component., but I am struggling to find a solution. import React, { Component } from 'react'; import Loading1 from '../images/ ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

Encountering the error "undefined object" while using the yield keyword in JavaScript

var pi = document.getElementById("pi"); function * calculatePi(){ let q = 1; let r = 0; let t = 1; let k = 1; let n = 3; let l = 3; while (true){ if (4*q+r-t < n*t){ alert(n); yield n; ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...

What is the best method for exporting a MapboxGL map?

I am currently utilizing mapboxGL to display maps on a website, and I am interested in exporting the map as an image with the GeoJSON data that has been plotted. I attempted to use the leaflet plugin for this purpose, but it was unable to render clusters ...

Running CesiumJS is a straightforward process that can be done by

After diligently following the provided instructions, I managed to get cesium running locally. I then attempted the hello world example as shown: However, despite clicking on "open in browser," I couldn't see anything. It has been a constant struggl ...