Guide to implementing a sliding effect for accordion menu using Javascript

Currently, I am working on an accordion menu that slides up and down when clicked. While I have been successful in achieving the functionality, I am facing a challenge with implementing a smooth animation effect that smoothly slides from top to bottom and vice versa when displaying and hiding the menu content.

Although I have experimented with jQuery functions like slideUp() and slideDown(), my goal is to accomplish this through pure JavaScript. Here is a snippet of my code:

let k = 0;
let rightArrow = $(".fa-arrow-down");
$(".accordian-hover").click(() => {

  if (k == 0) {
    $(".accordian-content").style.display = "block";
    k = 1;
    rightArrow.classList.toggle("fa-arrow-down fa-arrow-up");
  } else {
    $(".accordian-content").style.display = "none";
    k = 0;
    rightArrow.classList.toggle("fa-arrow-up fa-arrow-down");

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordian-wrapper">
  <div class="accordian-hover d-flex flex-row justify-content-center align-items-center container">
    <div id="accordian-question-div">
      <h5>How to use this product ?</h5>
    </div>
    <div>
      <i class="fa fa-solid fa-arrow-down"></i>
    </div>
  </div>
  <div class="accordian-content">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Deserunt iste est sunt? Excepturi quas, sunt recusandae laboriosam eligendi cum autem. Tempora nulla, at sequi minima praesentium, explicabo ullam eius odio corporis optio autem pariatur consequuntur,
      rem voluptate soluta exercitationem natus quod repudiandae. Reprehenderit vitae, iste facere aspernatur minima modi repellat!</p>
  </div>

</div>

Answer №1

To achieve the desired effect, make use of the functions "slideDown" and "slideUp"

let x = 0;
let arrowRight = $(".fa-arrow-down");
$(".accordian-hover").click(() => {

  if (x == 0) {
    $(".accordian-content").slideDown();
    x = 1;
    arrowRight.toggleClass("fa-arrow-down fa-arrow-up");
  } else {
    $(".accordian-content").slideUp();
    x = 0;
    arrowRight.toggleClass("fa-arrow-up fa-arrow-down");

  }
});
.accordian-content p{
  margin-top:0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordian-wrapper">
  <div class="accordian-hover d-flex flex-row justify-content-center align-items-center container">
    <div id="accordian-question-div">
      <h5>How to properly utilize this item ?</h5>
    </div>
    <div>
      <i class="fa fa-solid fa-arrow-down"></i>
    </div>
  </div>
  <div class="accordian-content">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Deserunt iste est sunt? Excepturi quas, sunt recusandae laboriosam eligendi cum autem. Tempora nulla, at sequi minima praesentium, explicabo ullam eius odio corporis optio autem pariatur consequuntur,
      rem voluptate soluta exercitationem natus quod repudiandae. Reprehenderit vitae, iste facere aspernatur minima modi repellat!</p>
  </div>

</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

Using AJAX, create an item in Rails that can be linked to various categories directly from the categories edit page

` section: Considering items as keys that accept only a name for input. The main reason behind including keys on the categories edit display through ajax is to enable users to modify the category items template. The template contains keys that can be uti ...

Encountering issues with Yarn Install during production build. Issue states: "Error - [email protected] : The engine "node" does not align with this module"

Currently facing an issue while deploying a ReactJS Project on the PROD environment. The previous command "Yarn install" was working fine, but now it's failing with an error message. The error that I'm encountering is: info [email protected ...

Automatically close the modal upon receiving a valid input

When it comes to my modal, I've figured out how to show validation errors. My challenge now is preventing the modal from closing when there's an error in my ajax function. On the flip side, I'm also unsure of how to automatically close the m ...

Creating a Node server exclusively for handling POST requests is a straightforward process

I'm looking to set up a Node server that specifically handles POST requests. The goal is to take the data from the request body and use it to make a system call. However, my current setup only includes: var express = require('express'); var ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

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 ...

Following the application of the filter function, a singular array was generated as the output

function sortByAge(arr) { let ageSorted = arr.sort(function(a, b) { return Object.fromEntries(a).age - Object.fromEntries(b).age }); // Arrange by young age. it's working well. let result = []; let names = ageSor ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

leveraging React Router in conjunction with Next JS routing

As a newcomer to Next.JS, I have a simple question about managing routes in my web application. Currently, our project utilizes Next JS to handle routes in the BackEnd. However, I am facing a dilemma where I would like to use React-Router-Dom in a specifi ...

Exploring the implementation of if statements within the array map function in the context of Next.js

Is there a way to wrap certain code based on the remainder of the index number being 0? I attempted the following approaches but encountered syntax errors. {index % 3 === 0 ? ... : ...} {index % 3 === 0 && ...} export default function UserPosts() { / ...

The jQuery .animate function seems to be malfunctioning

I recently came across this jsfiddle link: http://jsfiddle.net/2mRMr/3/ However, the code provided is not functioning as expected: setInterval(function () { box.animate({ left: function (i, v) { return newv(v, 37, 39); }, ...

Rows in a table will not decrease when added anew

On a page that allows adding and deleting rows from a table of input fields, the following code functions properly for existing fields. However, when attempting to add new rows and delete them in a sequential manner that requires replacing the ID and name ...

Is there a way to exclude the element from being displayed when using ngIf in AngularJS?

Is there a way in Angular to conditionally add an element to the DOM without having it always added, even when its evaluation is false? I am looking for an alternative method to ngIf. ...

Exploring the World of PHP, MySQL, and AJAX

Recently, I came across an issue where I needed to extract values from a MySQL database using JavaScript. What I intended to achieve was to dynamically add a div element when a PHP page is loaded for editing information. The plan was to populate this div w ...

When attempting to retry in Next.js, the props obtained from getServerSideProps may

Currently, I am facing an issue with sending axios requests in getServerSideProps and passing the value through props via SSR to the client. The challenge lies in including a token in the header using an instance. In case the token expires, I utilize refre ...

Accessing new information seamlessly without the need for page refresh

For optimal mobile viewing of my website, I am considering implementing a select element. Here are the available options: HTML: <select name="select-choice-8" id="select-choice-nc"> <optgroup label="News"> & ...

"Table layout set to fixed is failing to function as intended

Can someone help me figure out why the CSS table in the code below is not hiding the content that exceeds the table height of 200px? Instead, the table is expanding vertically. <div style='display:table; border:1px solid blue; width:200px; table ...

export default select an option

Forgive me if my question comes off as naive, but I'm still learning the ropes. :-) I stumbled upon something perplexing in this GitHub file. I am aware that we can export or import default functions, but in this instance, the author has used: expo ...

Adjust the dimensions of the dropdown menus

I've set up 2 dropdown menus, but I'm having trouble adjusting their size. I need them to fill the screen width. Here's my code: <select id="repeatSelect" ng-model="selectedArea"> <option ng-repeat="(key,prop) in result" value=" ...

By employing jQuery ajax and leaving out a value for the form action attribute

Recently, I designed an ajax sign-up form using jQuery that connects to a PHP backend. One question I have is whether it's wise to keep the form attribute action="" empty and let the ajax interface handle everything. Are there any potential downsides ...