How can I collapse an open accordion slide in jQuery when clicking on another slide that is already open?

Here is a functional codepen link: https://codepen.io/boingloings33/pen/PoXpLWR

I have created an accordion that works well, but I am having trouble with auto-collapsing the open slide when clicking on the next one. Any assistance would be highly appreciated, thank you.

HTML:

<body>
    <div class="container">
      <div class="accordion" id="accordion-1">
        <div class="head">
          <h2>Title 1</h2>
        </div>
        <div class="content">
          <p> lorem ipsum </p>
        </div>
      </div>

      <br />

      <div class="accordion" id="accordion-2">
        <div class="head">
          <h2>Title 2</h2>
          <i class="fas fa-angle-down arrow"></i>
        </div>
        <div class="content">
         <p> lorem ipsums </p>
        </div>
      </div>
</body>

JS:

jQuery(function () {
  $(".head").on("click", function () {
    $(this).toggleClass("active");
    $(this).parent().find(".arrow").toggleClass("arrow-animate");
    $(this).parent().find(".content").slideToggle(280);
  });
});

CSS:

.accordion {
  box-shadow: 0px 1px 7px #dbdbdb;
}

.accordion .head {
  background-color: #ffffff;
  color: #563e6e;
  padding: 20px 30px;
  cursor: pointer;
  transition: 0.2s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.accordion .head:hover,
.accordion .active {
  background-color: #ffe77aff;
}
.accordion .content {
  background-color: #ffffff;
  display: none;
  padding: 20px 30px;
  color: #333333;
}

Answer №1

Make a substitution of the JavaScript code with the following snippet

jQuery(function () {
            $(".header").on("click", function () {              
                let isActive = $(this).hasClass('active');
                $(".header").removeClass('active');
                $(".header").parent().find(".content").slideUp(280);
                $(".header").parent().find(".icon").removeClass("icon-animate");
                if (isActive == false) {
                    $(this).addClass('active')
                    $(this).parent().find(".icon").addClass("icon-animate");
                    $(this).parent().find(".content").slideDown(280);
                }
            });
        });

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

Get the QR code canvas image with a customized background by downloading it

I am having trouble with downloading a QR code canvas image with a background. The download works fine, but my device is unable to scan the code properly due to an incomplete border. I need to add a white background behind it to make it larger. Current im ...

Display the icon exclusively when hovered over

I have a table with a column containing icons that I want to hide by default. I would like the icons to only appear when hovered over. Here is the HTML code: <table class="table table-hover"> <tr> <th>From</th> <th> ...

Prevent HTML from being escaped in data-binding while utilizing repeat-templates in Polymer

Hey there! <template repeat="{{item in items}}"> <div layout horizontal> <div>{{item['content']}}</div> <div>{{item['more_content'])}</div> ...

Iterate over the HTML elements within a class and retrieve a specific property in JSON

Currently, I am in the process of developing a straightforward application that involves making an Ajax request to retrieve a Json object and then passing it to an HTML document. Essentially, this application functions as a vending machine where the produc ...

Vue.js - Single file component - Custom element not recognized

I have a straightforward single-file component named "MobileApps.vue: <template> <div class="grey-bg about-page"> <p>{{ greetings }}</p> </div> </template> <script> export default { ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...

What is the best way to add a transition to a list element so that it expands in size without impacting its background image or the surrounding list items?

Lately, I've been working on revamping a flat design website and my focus has mainly been on the navbar. The original plan was to incorporate simple icons on a colored background that would darken when hovered over by the user's mouse. To achieve ...

Error message: Unexpected end of input found in HTML, CSS, or JavaScript files

I am currently working on a card game project but I keep encountering an error that says "unexpected end of input". This error is completely new to me, so any assistance or guidance would be greatly appreciated. Additionally, the codepen isn't display ...

Steps to eliminate a horizontal scrollbar

It appears that I am working with CSS 2.1 as the style "overflow-x" is not present in my code. In the snippet below, I have defined headings for a grid and set the Id "pageLength" to introduce a vertical scrollbar for the grid's contents. However, thi ...

Transferring Parameters to EJS Template in Node.js

Hey guys, I'm having an issue with rendering a MongoDB record in my .ejs file. Strangely, when I console.log the variable before the end of my route, I get the expected value. However, it becomes undefined in the .ejs file. Here is the code snippet: ...

Troubleshooting problems with tooltips when utilizing a custom arrow in jQuery UI

Utilizing the Tooltip custom style plugin presents a challenge for me... My goal is to have my tooltip message appear like those seen on websites and in the image provided (for instance, incorporating an arrow into the tooltip): Sample link Sample link ...

Dealing with the state of an array of checkboxes: What you need to know

Is there a way to individually control the checked state of an array of checkboxes? Here is the array in question: const CheckboxItems = t => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', ...

Exploring the world of AJAX: My initial roadblock

Referring to http://jsfiddle.net/DLy6j/ var echoHTML = '<img src="URL-TO-MY-IMAGE.JPG"/>'; $.ajax({ type: 'post', url: '/echo/html/', data: { html: echoHTML, delay: 2 }, beforeSend: ...

Is the div height set to 100% until the content surpasses the height of the browser window

Is there a method to make a div fill 100% of the available page height, until it contains enough content to require a scrollbar? // For example, if the browser height is 600px: <div> // Initially empty, so it will be 600px tall. </div> . ...

Conceal shortcodes in Wordpress's TinyMCE editor

Would it be possible to customize the appearance of shortcodes in the WordPress TinyMCE editor? One of my clients lacks HTML knowledge, making it difficult to explain what should not be edited on subpages. All I am looking for is a way to hide the shortco ...

Creating additional columns in a database table with PHP and SQL

        I'm currently working on a feature that enables me to add a new column to a database table using SQL and PHP. My setup includes a front-end form where users can choose the table they want to modify and input boxes for specifying the new c ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged ...

employing a particular texture on a personalized shape leads to a WebGL issue stating "trying to reach vertices that are out of bounds."

When implementing the following code: let shape = new THREE.Geometry() shape.vertices.length = 0 shape.faces.length = 0 shape.vertices.push(new THREE.Vector3(0, 0, 0)) shape.vertices.push(new THREE.Vector3(0, 0, 32)) shape.vertices.push(new THREE.Vector3( ...

Utilizing jQuery to make AJAX requests to multiple URLs

I am experiencing some difficulty running an Ajax call due to complications in locating the script.php file within my folder. This issue is a result of the RewriteRule in my htaccess file, which changes the formatting of URLs from "domain.com/index.php?bla ...

Instead of utilizing just one <select> element, Django mistakenly generates two while attempting to implement Bootstrap for form uploads

Struggling to develop a website using django and facing an issue where two select lists are appearing instead of one. Here is the HTML code: <form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-g ...