When the button is clicked, HTML buttons toggle and collapse information while toggling all other buttons

As a beginner in HTML and CSS, I've successfully created buttons that display more information when clicked. However, I'm struggling to figure out how to collapse the information being shown by other buttons when a new one is clicked. I've tried researching and tweaking the code without much success. Any assistance would be greatly appreciated!


function toggleProject(id) {
  var x = document.getElementById(id);
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

<ul>
     <button class="button" onclick="toggleProject('Project1')">1st Project</button>
     <div id="Project1" style="display:none" align="right">Information about the first project...</div>
</ul>

<ul>
     <button class="button" onclick="toggleProject('Project2')">2nd Project</button>
     <div id="Project2" style="display:none" align="right">Information about the second project...</div>
</ul>

<ul>
     <button class="button" onclick="toggleProject('Project3')">3rd Project</button>
     <div id="Project3" style="display:none" align="right">Information about the third project...</div>
</ul>

I realize that having separate Javascript functions for each button is inefficient. It would be helpful to find a single function that can handle multiple IDs.

Answer №1

To hide all elements with an id starting with Project and then display only the next element after clicking a button, utilize Document.querySelectorAll() along with Array.prototype.forEach(). Here's how you can achieve this:

function project(btn) {
  document.querySelectorAll('[id^="Project"]').forEach(div => div.style.display = "none');
  btn.nextElementSibling.style.display = "block";
}
<ul>
  <button class="button" onclick="project(this)">1st Project</button>
  <div id="Project1" style="display: none;" align="right">Information about the first project...</div>

</ul>

<ul>
  <button class="button" onclick="project(this)">2nd Project</button>
  <div id="Project2" style="display: none;" align="right">Information about the second project...</div>
</ul>

<ul>
  <button class="button" onclick="project(this)">3rd Project</button>
  <div id="Project3" style="display: none;" align="right">Information about the third project...</div>
</ul>

Answer №2

The reason why the toggling is not working is due to the absence of brackets. You forgot to include brackets for the function in the onclick attribute.

For example : onclick="firstP()"

I have made changes to your code. Please review it. You can now use a single function to toggle all IDs by passing the ID variable to the function as I have shown below.

<ul>
  <button class="button" onclick="firstP(1)">1st Project</button>
  <div id="Project1" style="display:none" align="right">Information about the first project...</div>

  <script>
  function firstP(elementId) {
      var x = document.getElementById('Project'+elementId);
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>
  </ul>

  <ul>
  <button class="button" onclick="firstP(2)">2nd Project</button>
  <div id="Project2" style="display:none" align="right">Information about the second project...</div>

  <!-- <script>
  function secondP() {
      var x = document.getElementById("Project2");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script> -->
  </ul>

  <ul>
  <button class="button" onclick="firstP(3)">2nd Project</button>
  <div id="Project3" style="display:none" align="right">Information about the third project...</div>

  <!-- <script>
  function thirdP() {
      var x = document.getElementById("Project3");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script> -->
  </ul>

Answer №3

After exploring various solutions, I stumbled upon this particular one. If you find it useful, cheers :D

function displayDetails() {

  var elements = document.querySelectorAll(".info-div");
  elements.forEach(element => {
     element.style.display = 'none';
  });
  event.target.nextElementSibling.style.display = 'block'
}
<ul>
     <button class="button" onclick="displayDetails()">1st Project</button>
     <div class="info-div" style="display:none" align="right">Information about the first project...</div>
</ul>
<ul>
     <button class="button" onclick="displayDetails()">2nd Project</button>
     <div class="info-div" style="display:none" align="right">Information about the second project...</div>
</ul>
<ul>
     <button class="button" onclick="displayDetails()">3rd Project</button>
     <div class="info-div" style="display:none" align="right">Information about the third project...</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

Connecting a button's action to a specific element in an array using AJAX and Firebase

I am currently working on a project that involves making an AJAX request from a social API and then appending the results with a button inside the div. This button is meant to save the corresponding item in the array to my Firebase database. For brevity, ...

Determine if a given date falls within the previous 24 hours using Javascript

In my javascript code, I have a date time provided in the format dd.MM.yyyy HH.mm. I want to verify if this date falls within the last 24 hours or not. For instance: If the current date and time is 06.04.2017 18:26 (dd.MM.yyyy HH.mm), the earliest permis ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

The blur event triggers an infinite loop

Within a web form, there is a query that necessitates an answer from the user. Nonetheless, one issue arises with the code provided below: if the user opts to dismiss the alert, it activates the blur event once more, leading to an infinite loop. $('#s ...

JavaScript bug: receiving an 'undefined' error when using getElementsByClassName

How can I retrieve the children of a specific div that belongs to the "vid_div selected" class? First, I select the correct div using this code: var vid_div = document.getElementsByClassName('vid_div selected'); However, when attempting to acces ...

Creating a Sticky Top Navigation Bar with Bootstrap

I'm currently working on a Bootstrap website and trying to make the navbar stick to the top. However, it seems like the class sticky-top isn't working as expected. Below is the code for the navbar: <div class="row"> <div class="col ...

Manipulate state in parent component from child component using onClick function with React hooks

Hello, I am facing a challenge trying to store data from a modal (child function) within the main (parent) function. Depending on which button is clicked, the modal loads specific HTML content (all buttons perform the same action). export default function ...

Twitch Websocket loses connection abruptly

Currently, I am working on developing a program that can display messages from a Twitch chat using the Twitch WebSocket, similar to applications like Chatterino and Chatsen. To achieve this, I am utilizing a package available at https://www.npmjs.com/pack ...

What steps should I take to ensure that the getElementsbyName function works properly on both Internet Explorer and Firefox browsers

Encountering a JavaScript error in IE but not in FF ("document.getelementsbyname(...).0.innerhtml is null or not an object": var oldVal = parseInt(document.getElementsByName("outSL")[0].innerHTML); //value pulled from the database Here is the asp.net c ...

ng-admin fails to identify custom field view

I've been exploring ng-admin. After referring to the documentation, I decided to create a custom field. However, even though ng-admin recognizes the FooFieldType, it is not rendering the FoofieldView and instead using the original FieldView! Conf ...

Obtain information from YouTube and format it into a list item

Currently, I'm working on compiling a list of videos that includes the title, link, image, and creator of each video. It's been a bit challenging :S <script type="text/javascript"> $(document).ready(function(){ $.getJSON('http://gdata ...

Filtering an array based on two specified boundary conditions

I have an array containing numbers from 1 to 7 const num = [1,2,3,4,5,6,7]; and two boundary values: var first = 6 var second = 3 The desired output should be: [6,7,1,2,3] Explanation: The resulting array should combine two sub-arrays: Numbers greater ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

Using Typescript to change a JSON array of objects into a string array

I'm currently working with the latest version of Angular 2. My goal is to take a JSON array like this: jsonObject = [ {"name": "Bill Gates"}, {"name": "Max Payne"}, {"name": "Trump"}, {"name": "Obama"} ]; and convert it into a st ...

The orientation of my bootstrap navbar menu is vertical instead of horizontal

I've been struggling with this issue for hours now. Despite searching online for solutions, I haven't been able to make my navbar list go vertical or get the "logout" and "My Posts" options to drop down when "Author" is selected as it should. Her ...

Obscured painting surface appearance using Three.js

I am attempting to incorporate a blurred texture into my Three.js scene, but the results are not what I expected. Canvas: var c = document.getElementById("myCanvas"); var context1 = c.getContext("2d"); context1.filter = "blur(16px)"; context1.beginPath( ...

Refreshing Three.js Scene to its Initial State

I am in the process of developing a Visual Editor where I can manipulate objects by adding, deleting, and transforming them. Currently, my scene only consists of a 5000x5000 plane as the floor. I am looking for a way to reset the scene back to its origin ...

Three-column navigation menu featuring visuals

I'm currently working on the stylesheet for a website and trying to figure out the most effective way to design the navigation menu. Here's how the menu is structured: There are double vertical lines between column 1 and 2, as well as between co ...

"Troubleshooting JQuery: Dealing with Errors in Ajax Get

I'm attempting to make a call to a PHP script using a GET request and passing the data theaddress, but the results are displaying the source code of the page I'm trying to call. The page I'm trying to call can be found here. Here is my AJAX ...

Testing with Jest after establishing a connection with MongoDB: A step-by-step guide

I am currently in the process of setting up testing for various routes within my Express server that rely on connectivity to my MongoDB database. I am facing a challenge in structuring the Jest file to enable seamless testing. In my regular index.js file, ...