Is it possible for the Jquery Accordion to retract on click?

Hello everyone, I've created an accordion drop-down feature that reveals content when the header of the DIV is clicked. Everything works fine, but I want the drop-down to collapse if the user clicks on the same header. I am new to JQUERY and have tried implementing a logic, but it doesn't seem to work. I would appreciate any help or guidance on how to achieve this using JQUERY.

Here is my XHTML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>TEST</title>
    <meta name="viewport" content="width=device-width"/>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>

<div class="container">

    <h2 class="acc_trigger"><a href="javascript: void(0);">ONE</a></h2>
    <div class="acc_container">
        <div class="block">
            <h3>CONTENT 1</h3>
            </div>
    </div>

    <h2 class="acc_trigger"><a href="javascript: void(0);">TWO</a></h2>
    <div class="acc_container">
        <div class="block">
            <h3>CONTENT 2</h3>
            </div>
    </div>

    <h2 class="acc_trigger"><a href="javascript: void(0);">THREE</a></h2>
    <div class="acc_container">
        <div class="block">
            <h3>CONTENT 3</h3>
            </div>
    </div>

    <h2 class="acc_trigger"><a href="javascript: void(0); ">FOUR</a></h2>
    <div class="acc_container">
        <div class="block">
            <h3>CONTENT 4</h3>
            </div>
    </div>

</div>

</body>
</html>

Here is my CSS:

/* Your CSS code here */

And here is my JQuery:

$(document).ready(function(){

//Set default open/close settings
$('.acc_container').hide(); //Hide/close all containers

//On Click
$('.acc_trigger').click(function(){
    if( $(this).next().is(':hidden') ) { 
        $('.acc_trigger').removeClass('active').next().slideUp(); 
        $(this).toggleClass('active').next().slideDown();
    }
    else {
        $(this).removeClass('active').next().slideUp();
    }
    return false; 
});

});

I am trying to make the accordion collapse when clicking the same header again. Any suggestions or corrections are welcome. Thank you!

Answer №1

To solve this, simply include an additional 'else' statement in your code.

    else{
        $('.acc_trigger').removeClass('active').next().slideUp();
    } 

View the solution on JSFiddle

Answer №2

Check out this snippet of code I put together. It's running smoothly, just need to tweak the CSS a bit.

<script src="jquery.js"></script>
<style>
    ul{list-style:none;}
    p{border:1px solid;}
</style>
<script>
    $(document).ready(function(){

        $("#tab > p").hide();

        $("#tab h1").click(function(){
            $("#tab >p ").slideUp(0);
            //$(this).siblings("p").slideDown();            
            $(this).parent().children("p").slideDown(0);
        });

    });
</script>

<style>
    h1{
        float:left;
    }

    p{
        width:35%;
    }
</style>
    <div id="tab">
        <h1> Greetings! </h1>
        <p> Hello there! This is some text that needs styling for better readability. </p>
    </div>
    <div id="tab">
        <h1> Salutations!</h1>
        <p> Hey hey! More content here that could use some formatting adjustments.</p>
    </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

Developing a placeholder directive with AngularJS

Are you looking to create a unique element in AngularJS to facilitate nested ng-repeats? Take a look at the example below: data.test = [{h:1, d:[11,12]}, {h:2, d:[21,22]}]; ---------------------- <custom ng-repeat="a in data.test"> <h3>{{a ...

Troubleshooting problem with Ajax responseText

Can an ajax responseText be received without replacing the existing content? For instance: <div id="content"> <p>Original content</p> </div> Typically, after running an ajax request with a responseText that targets id="conten ...

Accessing this.href from the ASP.NET code behind using Javascript

I'm trying to pass this.href from my asp.net code behind to JavaScript. When I run the code, the value appears as 'undefined' in the alert message. Can anyone help me with this issue? Page.ClientScript.RegisterStartupScript(this.GetType(), ...

Does shutting down a window with code in Jquery Post/AJAX impact the server script?

Let me start by acknowledging that this may not be the most straightforward question to address. I've got a PHP script that typically takes around 5-10 minutes to complete. I'd prefer not to make the user wait for it to finish. So, if I initiate ...

How to overcome the issue of Vue.js mobile router-link being blocked by v-on:mouseover

Here is a for list snippet: <li class="projects-item" v-for="project in filteredProjects" :key="project.id" v-on:mouseover="displayHoverInfo($event, project)" v-on:mouseleave="hover = false" > <router-link v-bind:to="'/project/ ...

Steps to display the leave site prompt during the beforeunload event once a function has finished running

While facing a challenge with executing synchronous Ajax methods in page dismissal events, I discovered that modern browsers no longer support this functionality in the "beforeunload" event. To work around this issue, I implemented a new promise that resol ...

Exploring the Depths with a Javascript Canvas Deep Zoom Library

I am faced with the task of creating a detailed zoom mosaic using an HTML5 Canvas Element, consisting of thousands of roughly 512x512 images. However, I am striving to minimize reinventing the wheel in the process. Instead of merging numerous large images ...

Utilizing HighChart in ASP.NET MVC for Dynamic Data Visualization from a Database

I am completely new to ASP.NET MVC and I am trying to show data from a database in a Highchart using Visual Studio 2015. In my controller, I have the following code to retrieve data from the database: namespace HelloWorld.Controllers { public class Se ...

How to Enhance Angular ui-router nested views with Resolve?

I have been working on creating a customized version of my Angular 1.4.12 application with nested views. The main purpose behind this customization is to accommodate sections within the app that require a header/content/footer structure, while others do no ...

In Angular2, you can dynamically show or hide previous and next buttons based on the contents of the first and last div

I need a solution to dynamically hide or show previous and next buttons based on the div tags created. Each value in a list is being used to generate individual div tags using ngFor loop in Angular 2. The list being utilized is: appUlist:string[] = ["Cal ...

What is the best way to send JSON data from a DooPHP Controller?

Currently, I am in the process of setting up an AJAX system and I need to create a controller that returns JSON data. While going through examples, I noticed that all controllers end with a call to the view: $this->renderc( 'interest', $d ...

How do I store the result of an Ajax request as a variable in a different function within a React component?

One of the challenges I'm facing involves making an ajax call that retrieves a list of movies, and then running another function with a separate ajax call to fetch the genre names. Since the first call only provides the genre IDs, I need to match each ...

Updating the browser URL after a successful Get request with MVC Ajax.BeginForm

I am working with an Ajax form that looks like this: @using (Ajax.BeginForm("AjaxSerchResult", "Search", new { area = string.Empty }, new AjaxOptions() { HttpMethod = "Get", UpdateTargetId = "Results", LoadingElementId = "Loading" }, new { id = "Search" } ...

What is the correct way to invoke a function from a different file?

Having trouble calling a function from another file in my JS code. I am unable to call a function from another js file. I suspect there is an issue with linking the two files. Code snippet from my first JS file const { response } = require('expre ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

After applying 'all: unset;' to remove all styles, the CSS hyphens property does not work as expected in Chrome

After applying this CSS code to remove all styles: * { all: unset; display: revert; } The issue arises in Chrome browser where CSS Hyphens are not taking effect. This can be seen with the following example: div { font-size: 3rem; -webkit-hy ...

Following the recent update to IntelliJ IDEA 2022.1.3, the use of ::ng-deep has been marked

After updating the version of IntelliJ, I noticed that the ::ng-deep angular material selector is now marked as deprecated. Here's an example: <mat-form-field class="register-custom-select"> <mat-select formControlName="gende ...

What is the process of invoking the POST method in express js?

I've been diving into REST API and recently set up a POST method, but I can't seem to get it to work properly. The GET method is running smoothly in Postman, but the POST method is failing. Can someone lend a hand in figuring out where I'm g ...

Encountering a problem with ng-repeat when working with a JSON

Having a bit of trouble displaying the keys and values from a JSON object in an HTML table using ng-repeat. The JSON object is coming from the backend, but for some reason, it's not showing up on the frontend. I know there must be a simple mistake som ...

When incorporating SQL statements into JavaScript code, it fails to function properly if the NVARCHAR attribute contains a line break

I am currently utilizing a PHP app generator (Scriptcase if that is relevant), while developing a webpage that involves a mix of vanilla JavaScript and SQL queries. After encountering an issue, I have finally identified the root cause. The problem arises ...