JQuery accordion fails to hide content upon second click

I have successfully implemented a jQuery accordion script that functions as intended.

However, I am looking to enhance the functionality by making it so that the opened content can be closed on the second click.

You may have seen a similar behavior in the Bootstrap accordion here, but I cannot use this due to the dynamic nature of my menu and having only one 'ID'.

Unfortunately, my current script does not close the opened content like the Bootstrap example.

If you would like to see the code in action, you can check out this JSfiddle Link.

Do you have any suggestions on how I can achieve the smooth collapsing functionality of the Bootstrap accordion?

Here is a snippet of my HTML code:

 <div id="wrapper">
    <div class="accordionButton">monday</div>
    <div class="accordionContent">sunny<br /><br /><br /><br /><br /><br /><br /><br />more weather</div>
    <div class="accordionButton">tuesday</div>
    <div class="accordionContent">sunny<br /><br /><br /><br /><br />more weather</div>
    <div class="accordionButton">wednesday</div>
    <div class="accordionContent">sunny<br />more weather</div>
    <div class="accordionButton">thursday</div>
    <div class="accordionContent">sunny<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />more weather</div>
</div>

Included below is the Javascript code for reference:

 $(document).ready(function() {

//ACCORDION BUTTON ACTION   
$('div.accordionButton').click(function() {
    $('div.accordionContent').slideUp('normal');    
    $(this).next().slideDown('normal');
});

//HIDE THE DIVS ON PAGE LOAD    
$("div.accordionContent").hide();

 });

Any assistance or recommendations on improving this functionality would be greatly appreciated.

Answer №1

To reveal, attempt to stretch solely when concealed

     if(!$(this).next().is(':visible'))
    {
        $(this).next().slideDown('normal');
    }

Experiment here

Answer №2

Here is a simplified code snippet for an accordion functionality:

$(document).ready(function() {
$('.accordionBtn').click(function(){
    $('.accordionContent').slideUp(200);
    if(!$(this).next('.accordionContent').is(':visible')) {                  
        $(this).next('.accordionContent').slideDown(200);
    }
}); });

Answer №3

Take a look at the updated version of the fiddle here: JSFiddle

I made some changes to the script below.

$('div.tabButton').click(function() {
    if($(this).hasClass("expanded")){
        $(this).next().slideUp('normal');
        $(this).removeClass('expanded');
    }
    else{
        $(this).addClass("expanded");
        // $('div.tabContent').slideUp('normal');  
        $(this).next().slideDown('normal');
    }
});

// HIDE THE DIVS ON PAGE LOAD    
$("div.tabContent").hide();

});

Answer №4

If you're looking to add Expand All/Collapse All functionality to your site, give this solution a try.

Check it out here:

Answer №5

Yes, this code snippet should do the trick!

$(document).ready(function() {

//ACCORDION BUTTON ACTION   
$('div.accordionButton').click(function() {
    $('div.accordionContent').removeClass('active').addClass('inactive');      
    $(this).next().removeClass('inactive').addClass('active').slideDown('normal');
    $('div.inactive').slideUp('normal');

}); 
//HIDE THE DIVS ON PAGE LOAD    
$("div.accordionContent").hide();

});

You can also find a working example on this fiddle jsfiddle.net/wTLLP/

Answer №6

Implemented data attributes to validate conditions.

$(document).ready(function() {

    //TOGGLE ACCORDION BUTTON   
    $('div.accordionButton').click(function() {
        if($(this).data("slided") === true) {
            $(this).next().slideUp('normal');
            $(this).data("slided", false);
        } else {
            $('div.accordionContent').slideUp('normal');    
            $(this).next().slideDown('normal');
            $(this).data("slided", true);
        }
    });

    //HIDE THE DIV ELEMENTS ON PAGE LOAD    
    $("div.accordionContent").hide();

});

Check out the demo - JSFIDDLE

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

Utilizing a Logarithmic Motion Effect

When working with an object in Psuedocode, if you want to transform it in a non-linear fashion based on a delta range from 0 to 1, how can you incorporate concepts like Ease in / Ease out? The idea is for the object to start animating slowly and then grad ...

Modifying Table Cell Background Color in ReactJS: A Guide to Conditionally Updating Cell Color Without Affecting the Entire Row

I am working on changing the background color of a cell based on its value. Currently, I am utilizing the following library: react-data-table-component Procedure: If the value is above 0, then the cell's background color will be red. Otherwise, th ...

CSS border-image negative positioning (no HTML required)

We are on the lookout for a way to apply a specific border style to nearly all img tags within the content area of a CMS (such as Wordpress or Joomla). Our goal is to achieve this solely using CSS without having to access any parent tags: The initial step ...

Is there a way to determine the orientation of an image in React-Native, whether it is horizontal or vertical

When working with react-native, I aim to utilize the 'contain' feature for vertical images and the 'stretch' feature for horizontal images. What would be the best way to determine the orientation of an image as either horizontal or vert ...

Leveraging Jest for mocking "import * as" operations

Is there a way to effectively mock this specific type of import using jest? import * as some from 'some-package'; ...

I'm facing a MongooseServerSelectionError: when trying to connect to 127.0.0.1:27017. Despite trying all the solutions provided on StackOverflow, the issue persists

MongooseServerSelectionError: Failed to connect to 127.0.0.1:27017 at NativeConnection.Connection.openUri (/mnt/d/Ecommerce/node_modules/mongoose/lib/connection.js:802:32) at /mnt/d/Ecommerce/node_modules/mongoose/lib/index.js:341:10 at ...

Tips for concealing a div when clicking outside of the div

I have an HTML division that I need to conceal whenever the user clicks anywhere outside of it on the page. What specific element should I target in order to trigger the onclick event? ...

Angular @Input set function not being activated during unit testing

Within my Component @Input('price') set setPrice(price) { this.price = price; this.modifyTotalAmount(); } Unit Testing (component.spec.ts) it('should execute function ', () => { spyOn(fixture.componentInstance, ' ...

Accessing Data from the Controller using JQuery

Just starting out with Jquery and looking for help. How can I retrieve data from my controller and then compare it to a specific string using JQuery? $(".select"+increment).change(function () { if("here i need the value from m ...

@html.BeginForm with jquery Ajax is not functioning properly

My task involves implementing Ajax in an ASP.NET MVC form without using @Ajax.BeginForm at the request of my manager. Instead, I have to utilize Ajax with jQuery methods. The issue I'm facing is that although my code appears to be functioning properly ...

Maximizing the Width of a Background Image in Wordpress Elementor for a Full Screen Effect

UPDATE: Issue Resolved! See the comments for details. Thanks to the helpful Dev! I'm facing a challenge with my website's homepage design. I'm trying to incorporate a background image that spans the full width of the screen. My website is b ...

A webpage styled with w3.css featuring text without any underline

I am currently using w3.css but I'm facing an issue where some of my hyperlinks have underlines while others do not. My goal is to remove all underlines from the hyperlinks in the content below: <ul class="w3-ul w3-white"> <a class="" href=" ...

Issue encountered while exporting a variable in Node.js

Issue with exporting a variable. First File const commander = require('discord.js-commando'); const ytdl = require('ytdl-core'); class exportCommand extends commander.Command { constructor(client) { super(client,{ ...

Execute a JavaScript function when an HTML list element is clicked

As a beginner in web development, I have a question that might seem obvious to some. I want to create a menu where each item, when clicked, triggers a JavaScript function with the item's ID as an argument. I plan to display the menu items in an unorde ...

Is XPath applicable to data that has been labeled?

I am looking to access the data within the second div: <div class="my-3"> <div class="d-flex justify-content-between">Monthly:</div> <div>0 / 30,000</div> </div> Within the code above, I want to t ...

What is the best way to style multiple classes within the same element (specifically an ordered list ol

Using CSS counters, I have created various styles for an ordered list <ol> by applying different classes and adjusting the styles accordingly. Now, I want the counters to adjust based on screen size, displaying smaller numbers on smaller screens. To ...

Can anyone identify the jQuery effect on this website? Whenever I zoom out, the circle mysteriously vanishes

Is there a way to create a triangle effect instead of a circle? Could you provide guidance on how to animate this shape? ...

Finding the index number of a DIV element when it is clicked

Here is an example of the HTML structure I am working with: <div id="preview-wrapper"> <div class="dz-preview dz-image-preview"> <a class="rotate-a" href="javascript:void(0);"> <img class="rotate" src="public/a ...

I am interested in displaying or hiding a table depending on a specific condition in MVC 4

Looking at this MVC 4 Razor code snippet: <h4>You have @Model.Count() items up for sale currently. @Html.ActionLink("Add a new listing by clicking here", "Create")</h4> <br /> <table style="visibility: hidden"> .... I am seeking ...

Struggling to transfer information from Express backend to React frontend using Axios, facing obstacles

I'm attempting to transfer data from my Express backend to the React frontend using Axios, but I'm encountering difficulties. The data I'm trying to transmit is sourced from a text file. Backend: const express = require('express') ...