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

Align an image in the middle with a heading

I am currently working on aligning a picture and heading in a header section. My goal is to center both elements, with the picture being twice as tall as the heading. So far, I have them stacked one above the other: .body { font: 15px/1.5 Arial, Helveti ...

Cover the entire screen with a solid background color and adjust the text size accordingly

I'm encountering two issues. Despite my efforts to adjust multiple containers, the background colour #eee simply won't reach the bottom of the screen. I've even tried setting the HTML height to 100%, but to no avail. Even though I&apos ...

Angular 2 ngFor generates a collection of rows and columns forming a single large column

It seems that ngfor is generating divs one by one, resulting in a poor design where they are stacked on top of each other. I would like to achieve a layout like this: [1] [2] [3] [4] [5] [6] However, the current outcome looks like this: [ 1 ] [ 2 ] [ 3 ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

Iconic Side Navigation with collapsed button malfunctioning due to negative positioning

I'm facing two issues with my webpage. First: I have three buttons on the right side of my page that are supposed to behave like the buttons on this example. However, when you scroll, you can see that their position is incorrectly displayed "outside" ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Is it possible to truly halt the execution of the readline function?

Exploring a scenario with the code snippet provided below, along with an input file and the resulting output. The setTimeout function is utilized to simulate an external call like an http get request. What would be the most effective or straightforward met ...

The HTML 5 Validation is unsuccessful due to the presence of the "Attribute addthis:url not allowed on element a at this point." error

I am currently facing an issue on my MVC4 Project web page where I have implemented the ShareThis plugin to display share count for various posts. The code snippet looks like this: @{ string strShareThisURL = "addthis:url=\"" + mainURL +" ...

The two-word string is failing to pass through the query string

I've been working on passing multiple values through the query string. So far, I have successfully passed single-word values to a PHP page using jQuery. However, I encountered an issue when trying to pass a user's name like "Vishal Deb" as it onl ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Consistency in table cell formatting

What is the best way to ensure all my table cells have a consistent height and width, regardless of their content? I am working on a crossword puzzle game where some cells are empty, some contain letters as the user fills in words, and others display butt ...

Ensuring a div remains perfectly centered

Currently, I am new to HTML and still in the process of learning. I am facing a challenge in centering a button within a div, and I have been using margins to position it. While this method works well when the window is fullscreen, the button's positi ...

What is the best way to toggle between rendering two components or updating two outlets based on a route in React Router?

There is a React application I am working on that utilizes React-Router. My layout component has the following structure: import React from 'react'; import Header from './components/Header/Header'; import Footer from './components/ ...

Vue automatically refreshes momentjs dates prior to making changes to the array

I am dealing with a situation where my child component receives data from its parent and, upon button click, sends an event to the parent via an event bus. Upon receiving the event, I trigger a method that fetches data using a Swagger client. The goal is ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Click to Resize Window with the Same Dimensions

I have a link on my website that opens a floating window containing more links when clicked. <a href='javascript:void(0);' onclick='window.open("http://mylink.html","ZenPad","width=150, height=900");' target='ZenPad'>&l ...

Troubleshooting: Why is Angular2 ngClass malfunctioning?

I am having trouble adding a class based on a condition <tr *ngFor="let time of times; let i = index"> <td [ngClass]="{'red-time':checkInvalid(time['Proles Arrive'])}">{{time['Proles Arrive']}}</td& ...