YogeshChauhan.com

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

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.

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

WordPress: How to loop through a repeater field in ACF?WordPressAngular: Templates, directives, data binding, Services and dependency injectionAngularHow to create a vertically rotating texts using CSS?CSSWordPress: How to find all posts from a custom post type with multiple custom fields values?WordPressHow to remove N/A from Radio Button list in Drupal?DrupalSelect statement in Postgres with examplesPostgres