Switch the accordion to open or close

I am struggling to create an accordion menu that toggles open and close using the same button.

Right now, it only opens and I cannot figure out how to make it close as well.

Below is my current code, or you can view it on jsFiddle: http://jsfiddle.net/ndczc728/5/

//Accordion
(function($) {

var allPanels = $('ul.sub-level').hide();

$('.click-me').click(function() {
    $this = $(this);
    $target =  $this.next();

    if(!$target.hasClass('active')){
        allPanels.removeClass('active').slideUp();
        $target.addClass('active').slideDown();
    }

    return false;
});

})(jQuery);

Answer №1

To make it simpler, just incorporate the else statement into your existing If statement:

//Accordion
(function($) {

    var allPanels = $('ul.sub-level').hide();

    $('.click-me').click(function() {
      $this = $(this);
      $target =  $this.next();

      if(!$target.hasClass('active')){
         allPanels.removeClass('active').slideUp();
         $target.addClass('active').slideDown(); 
      }
      else
      {
         allPanels.removeClass('active').slideUp();
      }

    return false;
    });

})(jQuery);

Here is the working JSFiddle link for reference: http://jsfiddle.net/ndczc728/15/

Answer №2

You forgot to toggle it back up.

http://jsfiddle.net/ndczc728/8/

    if(!$target.hasClass('active')){
         $target.addClass('active').slideDown();
      }
      else
      {
         $target.removeClass('active').slideUp();
      }

Answer №3

Here is a quick solution to keep track of counts:

Check it out

(function ($) {
    $('ul.sub-items').hide();
    var counter = 1;
    $('.toggle-button').click(function () {
        counter++ % 2 == 0 ? $('ul.sub-items').slideUp() : $(this).next().slideDown();
        return false;
    });
})(jQuery);

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

Deciphering JSON strings using JavaScript

Here is a string that I am trying to parse using Json: {\"description\": \"PSY - Gangnam Style (\\uac15\\ub0a8\\uc2a4\\ud0c0\\uc77c) \\n\\u25b6 NOW available on iTunes: h ...

Responsive Bootstrap 5 table - occupies full width on mobile devices, adjusts automatically on desktop screens

Is there a way to create a table that is full width on mobile using pure bootstrap classes, but only auto width on desktop? I attempted to achieve this with the following code: <table class="table table-bordered w-md-auto w-100 text-start mb-2&quo ...

AngularJS provides a convenient way to manage content strings

As I embark on developing a large AngularJS application, I am faced with the need to manage UI text content. This is crucial as elements like contextual help will require post-launch editing by the client in response to user feedback. I am currently explo ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Heroku Foreman unexpectedly stops while using Express.js bodyParser() function

After running foreman start, the following message is displayed: > foreman start 20:38:55 web.1 | started with pid 3896 20:38:55 web.1 | Development 20:38:56 web.1 | connect.multipart() will be removed in connect 3.0 20:38:56 web.1 | exited with co ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

Using Rails to render partials with Ajax and buttons

I have a webpage that showcases a list of microposts along with different tabs like Most Recent, Most Discussed, and Most Viewed. I am looking for a way to dynamically render the various list orders of microposts without having to refresh the entire page u ...

Enhance the appearance of a tree node by applying style to the "li" element

Here is a tree structure that I am working with - http://jsfiddle.net/anirbankundu/wzEBW/ This tree may contain any number of nodes. The requirement is that when a user hovers over a single node, the background color of the node should change. This can be ...

Show a collection of pictures in an array when hovering over them

My goal is to make all images in an array fade in when a user hovers over the "Class of 2013" section. Currently, I can only display one image at a time upon hover... Is it possible to assign them all to the same <img src... tag? The issue is that I ...

Symfony2 allows for the creation of custom form field types that can be embedded

I am currently working with three main entities: Asset, Inventory and Item Asset has a collection of Inventories, Inventory has a collection of Items. My task is to design an embedded form for Asset. I decided to refer to the Symfony2 documentation fo ...

Creating Smooth Transitions Between Two Textures Using Three.js, Implementing Zoom and Blend Effects

I have been exploring ways to create a seamless transition between two panoramic cube images in order to achieve a walk-through effect within a room. Utilizing this example as a starting point, I have set up the Scene, Camera, and Mesh SkyBox. My current f ...

The view page encounters an issue when attempting to load a null element

I am currently working with a JavaScript function that generates links on my webpage based on the user's selection from a DropDown menu. I have implemented checks for this JavaScript function in two scenarios: when the user selects an option from the ...

Using CSS3 to target the final <li> element within the main list in a nested <ul> structure

I have a complex list structure: <ul> <li>Item</li> <li>Item</li> <li>Item</li> <li> <ul> <li>Nested Item</li> <li>Nested Item</li> <li>L ...

I'm having trouble getting the activeStyle to work properly with a <NavLink>

I'm facing an issue with setting activeStyle for the NavLink component when the URL is on the map route. Currently, when I click on a NavLink, I can navigate to the correct route, but only <NavLink to='/' is being highlighted as active. ...

Designing a personalized node for a D3 force-directed graph while incorporating drag, zoom, and pan functionality

I'm currently integrating the D3 library into my React web application to generate a graph that showcases data. I've successfully set up all the desired features like drag, zoom, and pan. The final step is to customize the node element to display ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Show Data on the Right-hand Side

Objective: Arrange the component names in two columns - left and right, with different objects like input textboxes based on a browser width of 981px. The desired layout is showcased in this link "https://jsfiddle.net/2w9kskr2/". Challenge: After impl ...

Issues with displaying Angular Material's ng-messages in a dialog box

While working on a login form within a dialog, I noticed that the ng-messages for the respective input are not appearing. The validation is functioning properly as the input turns red when there's an error, and the button remains disabled until the va ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...