⊗jsPrStAcc 14 of 62 menu

Accordion in JavaScript

Let's now implement the accordion. It is similar to tabs laid on their side. At the same time, in the accordion, you can collapse the current tab by clicking on the active link.

Here is a sample:

Also study the layout with which we will solve the problem:

<div id="parent"> <div class="tab active"> <div class="link"> <a href="#" >tab 1</a> </div> <div class="text"> tab text 1 </div> </div> <div class="tab"> <div class="link"> <a href="#" >tab 2</a> </div> <div class="text"> tab text 2 </div> </div> <div class="tab"> <div class="link"> <a href="#" >tab 3</a> </div> <div class="text"> tab text 3 </div> </div> </div> #parent { margin: 0 auto; width: 400px; } .tab { margin-bottom: 10px; } .tab .link a { display: block; padding: 10px; color: black; text-decoration: none; text-align: center; background: #f8f8f8; border: 1px solid gray; } .tab .link:hover a { background: #f2f2f2; } .tab:not(.active) .text { display: none; } .tab .text { border: 1px dashed gray; border-top: none; padding: 10px; height: 300px; }

Discussion

Technically, the HTML code for the accordion is more convenient than the code for the tabs: it has links directly above the spoiler that they open and close. In addition, the active class in our layout is given to the common parent of the link and spoiler.

This means that when you click on a link, you just need to deactivate the old tab and activate the new one. To deactivate the old tab, you need to find a tab with the class active and remove this class from it.

To activate a new tab, you need to click on the link to find the parent tab of this link and assign it the active class. Technically, such a search can be done like this: just find the closest parent of a link that has the tab class.

Copy the provided HTML and CSS codes. Implement the accordion according to the described algorithm.

enru