Create a function that allows users to toggle and display only one div within a group at a time using

The following code successfully toggles individual divs, but it displays active divs in a stack when toggling. I am trying to achieve the functionality of "showing only one at a time". Any suggestions?

function toggle_visibility(id) {
  var e = document.getElementById(id);
  if (e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
}
<ul class="post-advanced-menu">
  <li><a href="#" onclick="toggle_visibility('source');">Source</a></li>
  <li><a href="#" onclick="toggle_visibility('share');">Share</a></li>
  <li><a href="#" onclick="toggle_visibility('report');">Report</a></li>
</ul>

<div id="post-advanced-content">
   <div id="source" style="display: none;">Source</div>
   <div id="share" style="display: none;">Share</div>
   <div id="report" style="display: none;">Report</div>
</div>

Thank you,

Answer â„–1

Make sure to hide all other elements before showing the selected one.

function toggle_visibility(id) {
  const target = document.getElementById(id);
  if (!target) return;

  // Hide all other div elements.
  const divs = document.querySelectorAll('.div');
  for (const div of divs) {
    div.style.display = 'none';
  }

  // Show selected one
  target.style.display = 'block';
}
div {
  width: 20px;
  height: 20px;
}

#source {
  background: red;
}

#share {
  background: blue;
}

#report {
  background: green;
}
<ul class="post-advanced-menu">
  <li><a href="#" onclick="toggle_visibility('source');">Source</a></li>
  <li><a href="#" onclick="toggle_visibility('share');">Share</a></li>
  <li><a href="#" onclick="toggle_visibility('report');">Report</a></li>
</ul>

<!-- Source -->
<div id="source" class="div" style="display: none;"></div>

<!-- Share -->
<div id="share" class="div" style="display: none;"></div>

<!-- Report -->
<div id="report" class="div" style="display: none;"></div>

Answer â„–2

One effective approach I suggest is using unobtrusive script with class and data attributes:

window.addEventListener("load",
  () => document.querySelectorAll(".post-advanced-menu").forEach(
    ele => ele.addEventListener("click",
      e => {
        var tgt = e.target;
        var id = tgt.getAttribute("data-id");
        document.querySelectorAll(".toggle").forEach(
          ele => ele.style.display = ele.id == id ? "block" : "none")
      })
  )
)
.toggle {
  display: none
}
<ul class="post-advanced-menu">
  <li><a href="#" data-id="source">Source</a></li>
  <li><a href="#" data-id="share">Share</a></li>
  <li><a href="#" data-id="report">Report</a></li>
</ul>

<!-- Source -->
<div id="source" class="toggle">Source</div>

<!-- Share -->
<div id="share" class="toggle">Share</div>

<!-- Report -->
<div id="report" class="toggle">Report</div>

Answer â„–3

To ensure a seamless user experience, consider hiding other items before allowing users to click on a specific item.
This approach also involves hiding the clicked item if it is already visible.

For easier management, assign a unique class to each div element, such as class="item".

<ul class="post-advanced-menu">
  <li><a href="#" onclick="toggle_visibility('source');">Source</a></li>
  <li><a href="#" onclick="toggle_visibility('share');">Share</a></li>
  <li><a href="#" onclick="toggle_visibility('report');">Report</a></li>
</ul>

<!-- Source -->
<div id="source" class="item" style="display: none;">1</div>

<!-- Share -->
<div id="share" class="item" style="display: none;">2</div>

<!-- Report -->
<div id="report" class="item" style="display: none;">3</div>

function toggle_visibility(id) {
  var e = document.getElementById(id);
  if (e.style.display == 'block') {
    e.style.display = 'none'
  } else {
    document.querySelectorAll('.item').forEach(function(div) {
       div.style.display = 'none';
    })
    e.style.display = 'block';
  }
}

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

Vue fails to detect changes in an Array

Hey everyone, I'm currently working on a Vue project and I have been attempting to create a recursive tree from a flat list. My goal is to toggle the expanded property of each item when clicked, but for some reason, it's not updating. The issue ...

What is the quickest and most effective method for toggling more than 10,000 checkboxes using Javascript/jQuery?

I am facing a challenge with a div that contains over 10000 checkboxes. Due to technical limitations, I have no choice but to work with this large number of checkboxes. This is not related to any academic task. <div class="well well-sm" style="min-hei ...

Placing an HTML element inside a div using CSS in Vue

Here is the code for a component I am working on: <div class="wrapper"> <div horizontal-group class="filter-container"> <comp-form-item :label="Date"> <comp-datesrange ref="dataRange ...

Interface key error caused by the TypeScript template literal

Version 4.4.3 of Typescript Demo Playground Example -- interface IDocument { [added_: `added_${string}`]: number[] | undefined; } const id = 'id'; const document: IDocument = { [`added_${id}`]: [1970] } My Attempts: I made sure that id in ...

Uploading and updating your YouTube channel banner is made easy with the help of the Node.js Googleapis client

I'm currently developing an application that involves uploading and updating the YouTube channel banner. I'm utilizing node.js along with the Google API client. Upon reviewing the official API documentation, I noticed a lack of examples specifica ...

Issue with Material-UI: Inability to Activate the onChangeCommitted Event while Testing

I am encountering issues while testing the onChangeCommitted event with the slider from Mui. I have set up a basic implementation of the slider in a code sandbox environment. You can view the code in this sandbox. The main problem lies in my inability to ...

Having issues with JQuery.Ajax() function, not entirely certain if the script is loading correctly

Attempting to utilize an API for sending emails through MailChimp without needing a backend. Unsure if Jquery script file is configured properly. $(document.ready(function () { $('#survey').click(function() { $.ajax({ type: “POSTâ ...

Ways to add elements to an array nested within services and append to an object within another object

<pre lang="HTML"> <ul> <li data-ng-repeat="q in QuizObj"> <fieldset><legend>All Quizes </legend> <h1>{{q.Quiz }}</h1> <h3>options</h3> <h3>answer</h3> &l ...

Updating the names of keys within an object that includes nested child objects

I am looking to update the keys in an object that contains nested objects with similar structures. Initially, my object looks like this: objs = { "one":{ "title":"bla", "amount":5, "children":[ { "title":"bla", ...

Sort out the DIVs containing card elements

Is there a way to filter DIVs containing cards based on their categories? I seem to be encountering an issue where the filtering only works with letters. I suspect the problem lies in the Javascript code, but I can't pinpoint it. Can you help me ident ...

Pressing the different buttons on a form does not result in the form being submitted

I have a form with multiple buttons that, when submitted, will redirect to a different page and pass along some variables. echo " <form method=\"POST\" action=\"sightWordsTest.php\"> ...

Make sure to wait for the complete loading of all content in the AJAX response before showing it on

I am currently working on a search function that sends a json request to the server for results every time a character is entered. Although this part is functioning correctly, I am trying to figure out how to add a loading class to .search-load > .conta ...

Create a stylish accordion in asp.net with custom arrow buttons using CSS

Can anyone help me find the proper CSS for an asp.net ajax accordion menu with a vertical orientation that includes arrow buttons on each pane? I need the arrows to change when the menu is expanded versus collapsed. ...

Tips for Moving an h1 Tag to the Beginning of a Div

As a beginner in HTML, I have encountered an issue with my code. My div element contains an image and an h1 tag, but the h1 is currently positioned below the image. How can I center the h1 on top of the image? <div class="headwrap"> <div clas ...

Updating the CSS class for a particular text segment enclosed in a <p> or <span> element

My <p> tag is set to contain several lines of text with a specific CSS class, but I am looking to modify the text format within certain parts of the paragraph. In the past, I would achieve this using the <font> tag, however it seems that HTML5 ...

Problems arise when attempting to load a JSON file using the d3 library installed through npm

I recently added d3 through npm. In my package.json file, the dependencies section shows "d3": "^4.11.0". I attempted to load a simple JSON file using the following code: const d3 = require('d3') d3.json('jsonfile.json', (err, data) ...

By stopping clearInterval, the setInterval operation becomes solely dependent on time

I'm new to JS/jQuery and struggling with understanding how to stop a setInterval function after a certain time interval or number of executions using clearInterval. I know this question has been asked before, but I still can't figure it out. Cur ...

What is the best way to center text in the middle of a button?

Can someone help me center the text in the middle of a button like the image below? I tried using the class provided but it doesn't seem to be working. https://i.sstatic.net/EK0Mf.png <div class="row text-center"> <div class="col-lg-6 a ...

Adjust the burger menu color based on the background color of the section

Currently, I am working on creating a hamburger menu component with fixed positioning using the 'fixed' property. The menu icon consists of three white lines by default, but I want them to change to black when placed in a white section. I have tr ...

Tips for displaying a refresh indicator while making an ajax call for refreshing data:

I have successfully implemented jQuery code that refreshes a specific div every 10 seconds without reloading the entire page. However, during this refresh process, the user does not visually perceive any changes happening in the browser. While there are n ...