Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one.

Check out my code snippet below:

$( document ).ready(function() {
$( ".faq-question" ).click(function() {

$(this).toggleClass('open');
$(this).parent().next('.field-faq-answer').toggle();
});

});
.field-faq-answer{
display:none;
}
.faq-antwoord{
border-bottom: 1px solid #ccc;
margin-top:10px;
padding-bottom:10px;
}
.faq-antwoord p{
margin-bottom:0px;
padding-left: 10px;
    border-left: 2px solid #3395d3;
margin-left:10px;
}
.field-faq-question-first{
border-top: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="faq-container">
    <div class="field-faq-question field-faq-question-first">
      <h3 class="faq-question">
        Title 1
      </h3>
    </div>
    <div class="field-faq-answer">
      <div class="faq-antwoord"gt;
        <p>
          TEST 1
        </p>
      </div>
    </div>
</div>
<div class="faq-container">
    <div class="field-faq-question field-faq-question-first">
      <h3 class="faq-question">
        Title 2
      </h3>
    </div>
    <div class="field-faq-answer">
      <div class="faq-antwoord">
        <p>
          TEST 2
        </p>
      </div>
    </div>
</div>
<div class="faq-container">
    <div class="field-faq-question field-faq-question-first">
      <h3 class="faq-question">
        Title 3
      </h3>
    </div>
    <div class="field-faq-answer">
      <div class="faq-antwoord">
        <p>
          TEST 3
        </p>
      </div>
    </div>
</div>

Currently, you can click on Title 1 and Title 2, and both contents will be displayed. However, I would like only one answer to show while hiding the others.

Answer №1

If you want to achieve this, you can use the hide() function on all other elements with the class .field-faq-answer, except for the one that was clicked. Here's how you can do it:

$(document).ready(function() {
  $(".faq-question").click(function() {
    $(this).toggleClass('open');
    var $target = $(this).parent().next('.field-faq-answer').toggle();
    $('.field-faq-answer').not($target).hide();
  });
});
.field-faq-answer {
  display: none;
}

.faq-antwoord {
  border-bottom: 1px solid #ccc;
  margin-top: 10px;
  padding-bottom: 10px;
}

.faq-antwoord p {
  margin-bottom: 0px;
  padding-left: 10px;
  border-left: 2px solid #3395d3;
  margin-left: 10px;
}

.field-faq-question-first {
  border-top: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="faq-container">
  <div class="field-faq-question field-faq-question-first">
    <h3 class="faq-question">
      Title 1
    </h3>
  </div>
  <div class="field-faq-answer">
    <div class="faq-antwoord">
      <p>
        TEST 1
      </p>
    </div>
  </div>
</div>
<div class="faq-container">
  <div class="field-faq-question field-faq-question-first">
    <h3 class="faq-question">
      Title 2
    </h3>
  </div>
  <div class="field-faq-answer">
    <div class="faq-antwoord">
      <p>
        TEST 2
      </p>
    </div>
  </div>
</div>
<div class="faq-container">
  <div class="field-faq-question field-faq-question-first">
    <h3 class="faq-question">
      Title 3
    </h3>
  </div>
  <div class="field-faq-answer">
    <div class="faq-antwoord">
      <p>
        TEST 3
      </p>
    </div>
  </div>
</div>

Answer №2

Give this a shot:

$( document ).ready(function() {
    $( ".question-answer" ).click(function() {

        $('.field-question-response').toggle();
        $(this).toggleClass('open'); 
    });

});

Answer №3

You have the ability to focus on all elements except for the ones currently being edited and close them

$( document ).ready(function() {
    var inquiries = $( ".faq-question" ).on('click', function() {
        $(this).toggleClass('open');
        inquiries.not(this).removeClass('open');

        var response = $(this).parent().next('.field-faq-answer').toggle();
        $('.field-faq-answer').not(response).hide();
    });
});

Answer №4

One approach is to employ the nextAll() function for the parent of the parent element, known as faq-container, followed by using find to target the field-FAQ-answer and toggle its visibility.

$(this).parent().parent().nextAll('.faq-container').find('.field-faq-answer').toggle();

Answer №5

$( document ).ready(function() {

$( ".faq-question" ).click(function() {
  $('.faq-container .field-faq-answer').hide();
$(this).toggleClass('open');
$(this).parent().next('.field-faq-answer').toggle();
});
  

});
.field-faq-answer{
display:none;
}
.faq-antwoord{
border-bottom: 1px solid #ccc;
margin-top:10px;
padding-bottom:10px;
}
.faq-antwoord p{
margin-bottom:0px;
padding-left: 10px;
    border-left: 2px solid #3395d3;
margin-left:10px;
}
.field-faq-question-first{
border-top: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="faq-container">
    <div class="field-faq-question field-faq-question-first">
      <h3 class="faq-question">
        Title 1
      </h3>
    </div>
    <div class="field-faq-answer">
      <div class="faq-antwoord">
        <p>
          TESTING 1
        </p>
      </div>
    </div>
</div>
<div class="faq-container">
    <div class="field-faq-question field-faq-question-first">
      <h3 class="faq-question">
        Title 2
      </h3>
    </div>
    <div class="field-faq-answer">
      <div class="faq-antwoord">
        <p>
          TESTING 2
        </p>
      </div>
    </div>
</div>
<div class="faq-container">
    <div class="field-faq-question field-faq-question-first">
      <h3 class="faq-question">
        Title 3
      </h3>
    </div>
    <div class="field-faq-answer">
      <div class="faq-antwoord">
        <p>
          TESTING 3
        </p>
      </div>
    </div>
</div>

Give it a try to see the results.

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

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

Improving the functionality of the JavaScript key press function

I have a small javascript snippet on my website that allows me to navigate the site using the arrow keys on my keyboard. document.onkeydown = function(evt) { evt = evt || window.event; switch (evt.keyCode) { case 37: ...

Choose the content in the second column

Can anyone help me with CSS selectors? I've been trying to target the second .col_content element in my code to apply a specific background image, but I haven't had any luck so far. Adding a second class would be an easy fix, but I'm curious ...

Modify the color of a sub division's background using CSS when hovering over

As I work on this Fiddle, my goal is to change the background of each div section individually when moused over. However, currently, hovering over one section triggers the background change for all sections. Is there a way to ensure that only the specific ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

I'm having trouble grasping the issue: TypeError: Unable to access the 'subscribe' property of an undefined object

I've been working on a feature that involves fetching data from API calls. However, during testing, I encountered some errors even before setting up any actual test cases: TypeError: Cannot read property 'subscribe' of undefined at DataC ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

The functionality of the jQuery tablesorter() plugin seems to be malfunctioning!

I've been working on sorting columns in a GridView by clicking on the header, but I'm facing some issues. Despite trying various solutions I found on Google and tweaking the tablesorter() settings, my problem remains unresolved. Can anyone here p ...

How about this: "Using jQuery, we detached the element with the class 'myClass', then cloned it. But wait, where did my nested table go?"

I'm facing an issue where I have a div containing a table that I want to reuse for multiple entries in a JSON database. <div class="myButton"> <table> <tr id="currentVersion"> ...

What is the best way to implement data loading on scroll in HTML with AngularJS?

I'm working with a HTML Dynamic Table <div class="clearfix reportWrapper" > <div class="reportTable"> <table class="table table-bordered footerBGColor"> <thead fix-head class="headerTable"> ...

Struggling with passing values to onClickHandler because of MUI

I'm looking to create a category navigation menu that includes icons and labels. I attempted to do this using Chips: {categories.map((category) => ( <Chip key={category._id} ...

Error: Node requires the use of 'import' to load ES modules

Here is the code snippet that I am currently working with: import { toString } from 'nlcst-to-string'; import { retext } from 'retext'; import retextPos from 'retext-pos'; import retextKeywords from 'retext-keywords' ...

What is the method for transferring AJAX response data to PHP variables?

Is there a way to pass the result value from my code to a PHP variable? Here's what I have so far... billingCoffee.php $("#linkAddSize").click(function(e){ e.preventDefault(); var txtCoffeeName = document.getElementById("txtC ...

Utilizing PHP to send arrays through AJAX and JSON

-I am facing a challenge with an array in my PHP file that contains nested arrays. I am trying to pass an integer variable (and may have to handle something different later on). -My objective is to make the PHP file return an array based on the incoming v ...

Ways to determine if new data has been added to a MySQL table

Can anyone explain how the Facebook notification system operates? Here is my code snippet: (function retrieve_req() { $.ajax({ url: 'request_viewer_and_its_utilities.php', success: function(data) { $('.inte ...

Angular provides the capability to sort through data using various criteria

I have received an array of objects in a specific format from the server, which may contain more than 2 objects. [ {processId : 1, processName : "process1", country : "germany", companyCode:"IB" , companyHiringType:"FRE", masterClauses:[ {cl ...

Activating the CSS :active selector for elements other than anchor tags

How can I activate the :active state for non-anchor elements using JavaScript (jQuery)? After reading through Section 5.11.3 of the W3C CSS2 specification in relation to the :hover pseudo selector in hopes of triggering the activation of an element, I stu ...

Evaluating the DateTime between the client browser and the remote server using C#

Let's consider a scenario: I'm working on an ASP.NET MVC website with a form that allows clients to input an expiry date (using JQuery datepicker). After the form submission, I need to validate on the server if the entered date is past the curre ...

The computed value failing to refresh

I'm facing an interesting issue. I am currently developing a simple time tracking application. Here is the form I have created: <form class="form" @submit.prevent="saveHours"> <div class="status"> <div class="selector" v-f ...