Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality partially - when I click on a new question, the previous one hides and the new answer is displayed. However, if I revisit a previously opened question, it does not expand again.

Below is the code snippet I've been using:


$(document).ready(function() {

  $("#container li").click(function() {

    $("#container p").slideUp();
    var text = $(this).children('div.panel');

    if (text.is(':hidden')) {
      text.slideDown('200');
      $(this).children('span').html('-');
    } else {
      text.slideUp('200');
      $(this).children('span').html('+');
    }

  })

});

#container {
  list-style: none;
  font-family: arial;
  font-size: 20px;
}
#container li {
  margin: 10px;
  border-bottom: 1px solid #ccc;
  position: relative;
  cursor: pointer;
}
#container h3 {
  margin: 0;
  font-size: 24px;
}
#container span {
  position: absolute;
  right: 5px;
  top: 0;
  color: #000;
  font-size: 18px;
}
#container .panel {
  margin: 5px 0;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="container">
  <li>
    <h3>First Question</h3>
    <span>+</span>
    <div class="panel">
      <p>Hello</p>
    </div>
  </li>
  <li>
    <h3>Second Question</h3>
    <span>+</span>
    <div class="panel">
      <p>helelo</p>
    </div>
  </li>
  <li>
    <h3>Third Question</h3>
    <span>+</span>
    <div class="panel">
      <p>How are you</p>
    </div>
  </li>
</ul>

Answer №1

If you want to achieve this functionality, you can utilize the slideToggle() and slideUp() methods as shown below:

$("#container li").click(function(){
    $(this).find('div').slideToggle();
    $(this).children('span').html('-');
    $("#container li").not(this).find('div').slideUp();
    $("#container li").not(this).children('span').html('+');
});

You can view a live demo of this code here.

Answer №2

If you want to optimize your jQuery code, you can utilize the find() function in conjunction with the slideToggle() method:

 $(document).ready(function() {
  $("#container li").click(function() {
    $('#container li div').slideUp();
    $('#container li span').text('+');
    $(this).find('.panel').slideToggle();
    $(this).find('span').text('-');
  });
});

Live Demo:


$(document).ready(function() {
  $("#container li").click(function() {
    $('#container li div').slideUp();
    $('#container li span').text('+');
    $(this).find('.panel').slideToggle();
    $(this).find('span').text('-');
  });
});
#container {
  list-style: none;
  font-family: arial;
  font-size: 20px;
}
#container li {
  margin: 10px;
  border-bottom: 1px solid #ccc;
  position: relative;
  cursor: pointer;
}
#container h3 {
  margin: 0;
  font-size: 24px;
}
#container span {
  position: absolute;
  right: 5px;
  top: 0;
  color: #000;
  font-size: 18px;
}
#container .panel {
  margin: 5px 0;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<body>
  <ul id="container">
    <li>
      <h3>this is first</h3>
      <span>+</span>
      <div class="panel">
        <p>Hello</p>
      </div>
    </li>
    <li>
      <h3>this is second</h3>
      <span>+</span>
      <div class="panel">
        <p>helelo</p>
      </div>
    </li>
    <li>
      <h3>this is third</h3>
      <span>+</span>
      <div class="panel">
        <p>how are you</p>
      </div>
    </li>
  </ul>


</body>

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

What is the best way to activate an onchange function when using a <select> element?

Is there a way to automatically trigger a JavaScript function without the need for user input, while still having a default option selected? <select class="custom-select" name="" id="timer1numbers" onchange="getSelecte ...

Modify the class of a div as you scroll through the page between anchor points

I have been working on implementing a feature for my website where when I scroll to an anchor, the corresponding menu item adds or removes a specific class. However, I am facing an issue with making the first menu item remove the class when scrolling to t ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

Acquiring JSON data from Node.js within Angular

After searching everywhere, I finally managed to retrieve all the data from my database using node and saved it into a file. The data is simple JSON chat logs that can be accessed through my browser with ease. Here's a snippet of how it looks: [{ " ...

Using a PHP variable to dynamically change the style sheet by connecting to a MySQL database

My goal is to have the stylesheet URLs stored in a database and be able to change the stylesheets' href using variables in HTML tags. However, when I tried the following code, nothing happened: global $theme_addresss; global $showdetail_dbtadbiruse ...

The Vue component fails to respond to updates in plugin data

I am currently working on implementing a feature where a component reacts to data changes in a custom Vue plugin. To achieve this, the plugin creates a new instance of a Vue object in its constructor: this._vm = new Vue({ data: { obj: null, stat ...

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

I am unable to produce sound by clicking on the drum machine

My goal is to develop a basic react drum machine project that I discovered on freecodecamp. The objective is to display 9 drumpads and trigger sound upon clicking. Update: I have successfully rendered all the keys but I am facing issues with the function ...

Retrieving an array from PHP to JS through AJAX

I need assistance with modifying my code. When I click the "Add New" button in the data table, I want to replace the text boxes with a dropdown menu that retrieves values from a database. Here is my current code: // Function to add new row function addedi ...

What is the best way to strip the text from a link that encompasses both text and an image using jquery?

I have a website with a list of items. Each item in the list has a link that includes both text and an image. Here is an example of the HTML structure: <li class="li-one" style=""> <a href="#" onclick="return ...

Strikeout list on click of a mouse

Is there a way to apply strikethrough formatting to text with just a mouse click? The CSS for lists is beyond the form field margin. I've tried multiple methods without success. No matter how many times I change the code, I can't seem to get it r ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

JavaScript makes Chrome Hard Reload a breeze

We've created a browser-based app using AngularJS and are currently testing it with a group of clients. One major challenge we're facing is explaining how to "Empty Cache and Hard Reload" using the Chrome browser (by pressing F12, then clicking o ...

Save the outcome of an ArrayBuffer variable into an array within a Javascript code

I'm in the process of developing an offline music player using the HTML5 FileReader and File API, complete with a basic playlist feature. One challenge I'm facing is how to store multiple selected files as an ArrayBuffer into a regular array for ...

Unveiling the enigma of unresponsive Bootstrap dropdowns

I'm working on creating a custom navigation bar using Bootstrap v5. I found the code on the Bootstrap website and copied it into my project. However, I also added some JavaScript code to enhance its functionality, but unfortunately, it's not work ...

Download files from Firebase storage to a user's device

I have a variety of files such as images, videos, and audio stored in my firebase storage. My goal is to provide users with the ability to download these files to their computers by clicking on a download button. After reviewing the firebase documentation ...

Initialization of directive failed to occur properly

Utilizing the angular-ui-bootstrap tabs directive, I tried to create tabs. However, upon logging each controller and link function, the initialization order appears incorrect. Expected Order outer - controller Inner - Controller Inner - Link Inner - C ...

reveal.js: Upon a fresh installation, an error has been encountered: ReferenceError - 'navigator'

Currently, I am attempting to integrate reveal.js into my React.js/Next.js website using the instructions provided at However, upon implementation, I encountered the following error: Server Error ReferenceError: navigator is not defined This error occurr ...

Ways to extract information from PayFast

One issue I'm facing with my online store is that although PayFast does call my notify_url, it appears that no data is being posted. Below are the codes I've been using: Code for purchasing: <button id="cCart" type="submit" class="bt ...

Error with the Knockout framework's inability to bind to the model

I seem to be encountering an issue with binding Knockout to a model in my code. Despite the code firing and returning a JSON object, the table appears empty. Any advice or suggestions would be greatly appreciated. HTML <table style="border: double"& ...