Yogesh Chauhan's Blog

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.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to select multiple values in React dropdown?ReactMySQL queries to get data rows from previous month as well as from last 30 daysSQL/MySQLHow to modify AutoSave Interval using code in WordPress?WordPressHow destructuring works in React?ReactHow to add before after image effect using pure CSS?CSSObservation of Human Behavior [Shopping Observation Example]Miscellaneous