YogeshChauhan . com

How to create a Bootstrap style accordion using CSS and JavaScript?

in CSS & JavaScript on March 18, 2021

HTML

Let’s add the HTML first with main container and accordion buttons and contents to open upon click on those buttons.

CSS

Let’s add style for the headers and the main accordion container. Bootstrap has borders on headers and the content both so I have added it.

Now, lets style the content sections. For the content we’ll just have borders on sides. The top and bottom borders will be just headers borders.

For the last content box we have to add border bottom since there won’t be more header after that and it can’t get the border from header. We can use :last-child to do so.

I have also used transition, height and opacity properties to create the sliding down animation.

JavaScript

The concept is just show the content box when clicked on header. For that we need to add onclick event on headers. For that, we need to get all header elements. We can use querySelectorAll to do so.


var allAccordions = document.querySelectorAll(".acc");

Once we have that, we can use forEach on the elements array to go through the each one of them and add onclick event.

The advantage of using forEach is we can pass the index and save code in creating the temporary variable for index storage and iteration.

Also, we are gonna use nextElementSibling get the content box for the headers. After that, all we need to do is toggle the properties using simple if-else condition.

Here’s the complete code and demo.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What is Conditional Rendering in React?Reactperspective property in CSSCSSHow to zoom an element on hover using CSS?CSSWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryCreate a simple bar chart and column chart using pure CSS gridCSSIntroduction to components and templates Part 3: Data bindingAngular