Tips for switching back and forth with JQuery

I have an accordion element that opens on each click, but I am wondering how to close it back again?

Here is an example of the HTML structure:

<ul class="accordion">
<li id="one" class="files">
        <a href="#one">Calendar 1<span>10</span></a>
<ul class="sub-menu">
<li><a href="#"><em>01</em>Sub Menu<span>1</span></a></li>
        </ul>
    </li>
<li id="two" class="mail">
        <a href="#two">Calendar 2<span>20</span></a>
<ul class="sub-menu">
<li><a href="#"><em>01</em>Sub Menu<span>2</span></a></li>
        </ul>
    </li>
<li id="three" class="cloud">
        <a href="#three">Calendar 3<span>30</span></a>
<ul class="sub-menu">
<li><a href="#"><em>01</em>Sub Menu<span>3</span></a></li>
        </ul>
    </li>
<li id="four" class="sign">
        <a href="#four">Calendar 4</a>
<ul class="sub-menu">
<li><a href="#"><em>01</em>Sub Menu</a></li>
        </ul>
    </li>
</ul>

And here is the corresponding Javascript code:

$(document).ready(function() {
  // Store variables
  var accordion_head = $('.accordion > li > a'),
      accordion_body = $('.accordion li > .sub-menu');

  // Open the first tab on load
  accordion_head.first().addClass('active').next().slideDown('normal');

  // Click function
  accordion_head.on('click', function(event) {
    // Disable header links
    event.preventDefault();

    // Show and hide the tabs on click
    if ($(this).attr('class') != 'active') {
      $(this).next().stop(true,true).slideToggle('normal');
      $(this).addClass('active');
    }
  });
});

You can view a live demo on this link.

Answer №1

Instead of explicitly checking for the active class and then deciding whether to add or remove it, you can simplify your code with the use of toggleClass:

accordion_head.on('click', function(event) {
 event.preventDefault();
  $('.sub-menu').not($(this).next()).slideUp('normal').prev().removeClass('active');
  $(this).next().stop(true,true).slideToggle('normal');
  $(this).toggleClass('active');
});

Check out the Working Demo here

Answer №2

To simplify the code, you can eliminate the need for the if statement by utilizing both slideToggle and toggleClass like this:

$(this).next().stop(true,true).slideToggle('normal');
$(this).toggleClass('active');

Check out the Updated Fiddle

Answer №3

    if ($(this).attr('class') !== 'active'){
        //accordion_body.slideUp('normal');
        $(this).next().stop(true,true).slideToggle('normal');
       //accordion_head.removeClass('active');
        $(this).addClass('active');
    } else {
        $(this).next().stop(true,true).slideToggle('normal');
        $(this).removeClass('active');
    }

Check out the latest fiddle version: http://jsfiddle.net/9ev31v6w/

Answer №4

When using a tutorial, it's important to take the time to learn from it and not simply copy and paste the code without understanding it. It really is that simple:

http://jsfiddle.net/fuuLh494/1/

In this case, I included an else statement at the end of the script:

      else {
            $(this).next().stop(true,true).slideToggle('normal');
            $(this).removeClass('active');
        }

Answer №5

Switch every occurrence of addClass to toggleClass and eliminate the need for checking if the class is active.

By using toggleClass(), we can now remove the class even if it is already added without the necessity of an if condition block.

accordion_head.first().toggleClass('active').next().slideDown('normal'); // Updated
$(this).toggleClass('active'); // Updated

View the code in action on 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

What is the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

Unable to locate the CSS for the selected dropdown button in Bootstrap

Seeking help to locate the CSS code responsible for the blue border on a select dropdown button in Bootstrap. It seems simple, but I'm unable to find it. If anyone knows where this specific class is located in the CSS file, please share your insights ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

Issue: Module '/Users/MYNAME/Desktop/Projects/MYPROJECTNAME' not found

I am currently in the process of compiling Node using TypeScript, and I'm still getting acquainted with it. An issue I encountered was that my /src files were not being updated when I made changes and restarted the server. To troubleshoot, I decided ...

Is utilizing getStaticProps the best approach for handling offline data in Next.js?

My current project in Next.js involves offline static data for the webpage content. I am using an array to store the data for later mapping. Do you recommend using getStaticProps in this scenario? For example, here is a snippet of my code: import { data } ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

We're facing some technical difficulties with the form for the school project. Furthermore, I need to ensure that the answers are

Upon inspection, it seems that the HTML code is fine, but there appears to be an issue with the JavaScript. I also need to store the answers in an array, which is a task for later. <form> <fieldset> <legend>Content:</lege ...

Error message in Typescript: "Property cannot be assigned to because it is immutable, despite not being designated as read-only"

Here is the code snippet I am working with: type SetupProps = { defaults: string; } export class Setup extends React.Component<SetupProps, SetupState> { constructor(props: any) { super(props); this.props.defaults = "Whatever ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

Retrieve various forms of information using Ajax

Currently, I am working on developing a social networking website similar to Facebook using PHP. On one of the pages titled showdetails.php, I have implemented a search bar that should display a dropdown list of user names from the database as the user typ ...

There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { i ...

Hide a header and bring it back after a 2-second delay

I REPLIED BELOW Is there a way to make the header of my webpage fade out when scrolled and then be hidden using style.display? Here's what I have so far: <script type="text/javascript> function Scroll() { var head = document.getEl ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Determine the presence of a JSON Value/Array in a web application using JavaScript and visualize the information in a dynamic

Utilizing the Ticketmaster API has provided me with a sample dataset from their platform, Data 1 - Including information on "presales." "sales": { "public": { "startDateTime": "2019-11 ...

Is it possible to generate a PNG blob using binary data stored in a typed array?

I have a piece of binary data that is formatted as a PNG image. I am looking to convert it into a blob, generate a URL for the blob, and then showcase it as an image in various places where an image URL can be used, such as CSS. My initial approach invol ...

Implement a jQuery loading animation triggered by scrolling down the page

Can anyone offer guidance on how to trigger an animation as you scroll down a webpage? I've come across this feature while browsing through this website: I would love to include code examples, but I'm unsure of where to start with implementing t ...

Glitch in Safari 6: Round Corners Issue

Greetings! Upon observing the image provided, an unusual behavior can be noticed in Safari 6 concerning round corners. { border-radius: 5px 5px 5px 5px; } Upon hovering over the elements, a thin line appears that seems to accumulate with each subsequent ...

The background color should only cover a specific percentage of the element

Here is the current structure I have: <li class="myclass" ng-class="myAngularClass"> <div> div1 <div> div2 </div> </div> </li> The li element has dynamic dimensions and width. The class "myAngularClass" i ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

With a GroupAvatar, my Avatar named "max" likes to dance to the beat of its own drum rather than following the rules of my

I am currently working on creating an AvatarGroup using MaterialUi. I have successfully applied a style to all my avatars, except for the avatar that is automatically generated by AvatarGroup when the "max" parameter is defined. const styles = makeStyl ...