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

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Ways to transfer a value from a JavaScript file to a PHP file?

Is there a way to transfer data from a JavaScript file to a PHP file? Code: var year = (year != null) ? year : '".$this->arrToday["year"]."'; var month = (month != null) ? month : '".$this->ConvertToDecimal($this>arrTod ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

The use of event.returnValue in jQuery has been marked as deprecated

Every time I create a webpage using jQuery version , I encounter a warning message in the Console of Google Chrome. Is there a specific piece of code I can use to avoid this warning? Note that I am currently learning jQuery. The warning reads: event.retu ...

Leveraging variables from views.py in JavaScript

My approach to populating a user page has evolved. Initially, users would choose a value from a drop-down and an AJAX call would retrieve data. Here is the code that was functioning: HTML: <h3>Experimenter: {{ request.user }}</h3> <h3>R ...

When adjusting window size, the input shifts towards the left

Is there a way to prevent my input and login button from moving to the left when resizing the window? I am new to HTML and CSS and would appreciate any tips on keeping them in place. Below is my CSS code: #absolute { position: absolute; top: 411px; le ...

Vue.js Class-based Decorator not Transmitting Event from Child to Parent Component

I'm fairly new to working with Vue.js and I've encountered an issue with the child to parent emit functionality. Essentially, I have a Box component that contains a Search component. In the Search component, I attempted the following: @Watch("se ...

Attempting to Create a New User and Display the Resulting Page Using JavaScript and Handlebars Templates

I've implemented a form that allows users to input data. Once the user hits "Add User", they are successfully added to the database. However, instead of transitioning to the next page as expected, the form remains populated on the current page. The h ...

How can scripts be used to enable fullscreen in PhoneGap?

Can JavaScript in PhoneGap enable fullscreen mode and hide the status bar? While I know it can be pre-defined in config.xml, I'm unsure if it can be changed dynamically. I've come across resources suggesting that plug-ins are necessary here, but ...

Utilizing arrays in JavaScript alongside jQuery's methods such as $.inArray() and .splice()

I am currently dealing with an array that is limited to containing 12 values, ranging from 1 to 12. These values can be in any order within the array. My task is to iterate through the array and identify the first unused value, assigning it to a variable. ...

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

Dealing with Asynchronous JavaScript code in a while loop: Tips and techniques

While attempting to retrieve information from an API using $.getJSON(), I encountered a challenge. The maximum number of results per call is limited to 50, and the API provides a nextPageToken for accessing additional pages. In the code snippet below, my i ...

Position footer at the bottom of the webpage and adjust the height to be filled with main content using Bootstrap 4

I am currently in the process of designing a bootstrap layout that includes a header navbar along with a footer. My goal is to ensure that the footer is always at the bottom of the page, even if there is limited content. Here's what I have implemente ...

How do you trim a string and display the final 3 characters?

When dealing with a list of objects, I want to ensure that the chain of tasks does not become too long and break the table or appear aesthetically unpleasing. Therefore, my goal is to trim the tasks and display only the last 3. In the image below, multiple ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Is there a way to instruct npm to compile a module during installation using the dependencies of the parent project?

I am curious about how npm modules are built during installation. Let me give you an example: When I check the material-ui npm module sources on GitHub, I see the source files but no built files. However, when I look at my project's node_modules/mate ...

Setting the base path for a statically exported NextJS app

I am in the process of developing and deploying a React / NextJS application to a Weblogic J2EE server with a specific context. While I have some experience with React, I am relatively new to NextJS. The current steps for building and verifying the app ar ...

Providing input through the URL bar in PHP and HTML

I have a simple form on my website's HTML page. <form action="post.php" method="post"> Message: <input type="text" name="message" /> &nbsp; <input type="submit" name="submit" value="send"> </form> After submitti ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...