TECH

Vol.45

author

Engineer

N.T.

Easy to Use! Implementing an Accordion Menu

#WEB#programming#coding#開発
An accordion menu is useful when you want to display a large number of items within a limited UI space, such as on smartphones, by toggling open/close (show/hide) states. In this article, we will implement a commonly seen accordion menu on web pages using :contentReference[oaicite:0]{index=0}.
stuffstuff

Introduction

Since this tutorial uses :contentReference[oaicite:0]{index=0}, please download the source code from the official jQuery website or include it via a CDN service provided by Google or other providers.

jQuery Official Website
CDN Service

Simple Implementation

We will implement a simple accordion menu.

view demo

Accordion 1

Accordion 2

Accordion 3

HTML

<div class="a_container">
  <div class="a_item">demo</div>
  <div class="a_contents">
    <p>Accordion 1</p>
    <p>Accordion 2</p>
    <p>Accordion 3</p>
  </div>
</div>

CSS

.a_container{
  width:500px;
  margin:50px auto;
}
.a_item{
  background:#70f9a1;
  color:#fff; 
  text-align:center;
  padding:10px;
  cursor:pointer;
}
.a_contents{
  display:none;
  padding:10px;
  height:110px;
  border:solid 1px #d6dddf;
}
.a_contents p{
  margin:10px 0;
  border-bottom:dashed 1px #d6dddf;
}

jQuery

$(document).ready(function(){
  $(".a_item").click(function(){
    $(this).next().slideToggle(300);
  });
});

The class “.a_contents” is initially set to “display:none;” to hide the accordion content section.
A click event is assigned to the class “.a_item” using “click(function(){});”.
Inside this event, “slideToggle()” is used so that when the item is clicked, the content section opens and closes with a sliding animation.

One Point

.click(function(){});

This event registers a function that runs when the element is clicked.
You can assign this event to a specific class name or ID.
In this case, the event is triggered when the class “.a_item” is clicked.

$(this).next().slideToggle(300);

“this” refers to the element that triggered the event, meaning the action applies only to the clicked element itself.
If you use a class selector, the event may apply to all elements with that class, but using “this” ensures that only the clicked button is affected.

“next()” selects the next sibling element in the DOM.
Here, it refers to the content section (”.a_contents”) that comes immediately after the clicked button.

“slideToggle()” toggles the element’s visibility with an animation.
If the element is hidden, it performs slideDown; if it is visible, it performs slideUp.
You can specify the animation duration inside the parentheses.
For example, “slideToggle(300)” animates the transition over 0.3 seconds.

Rich Implementation

We will enhance the simple accordion menu by adding more features to create a richer implementation.
The added features are summarized below.

  • Change colors on mouse hover
  • Highlight the selected item when clicked
  • Close an already open accordion when another one is opened
  • Fade in the selected content with a delay after clicking
  • Add animation to the arrow indicator to show open/close state

 

HTML

<div class="a_container">
  <div class="a_item_r">demo</div>
  <div class="a_contents_r">
    <p>Accordion 1</p>
    <p>Accordion 2</p>
    <p>Accordion 3</p>
  </div>
  <div class="a_item_r">demo</div>
  <div class="a_contents_r">
    <p>Accordion 1</p>
    <p>Accordion 2</p>
    <p>Accordion 3</p>
  </div>
</div>

css

.a_item_r{
  background:#70f9a1;
  color:#fff; text-align:center;
  padding:10px; cursor:pointer;
  position: relative
}
.a_contents_r{
  display:none;
  padding:10px;
  height:110px;
  border:solid 1px #d6dddf;
}
.a_item_r:hover{
  background-color:#6aec99;
}
.selected{
  background-color:#ffc44d;
}
.a_contents_r p{
  display:none;
  margin:10px 0;
  border-bottom:dashed 1px #d6dddf;
}
.a_item_r:after{
  background:url(arrow_dw.png) no-repeat left top;
  content: "";
  display: block;
  width: 20px;
  height: 12px;
  position: absolute;
  right: 20px;
  background-size: 100% auto;
  top:15px;
  bottom:0;
  transition: 0.3s linear;
}
.open_close_r:after{
  transform: rotateZ(180deg);
}

Point 1: Pseudo-class “:hover”
By using this selector, you can apply CSS changes when the mouse hovers over an element.
Here, “.a_item_r:hover” changes the background color to visually indicate hover state.

Point 2: Pseudo-element “:after”
This allows you to insert and style an element after the target element.
In this case, an arrow icon is added using “:after”. A key requirement is specifying content:"".

Point 3: transition
This property defines animation timing in a single declaration.
Here, “transition: 0.3s linear;” creates a smooth 0.3-second linear animation for changes such as transform.

Point 4: transform
Used to apply transformations such as rotation.
In this example, “transform: rotateZ(180deg);” rotates the arrow when the accordion is opened.

Note: “transition” and “transform” are CSS3 features, and older browsers may require vendor prefixes.
-webkit- for Safari / Google Chrome
-moz- for Mozilla Firefox
-ms- for Internet Explorer

jQuery

$(document).ready(function(){
  $(".a_item_r").click(function(){
    $(".a_item_r").removeClass("open_close_r");
    $(".a_contents_r p").css("display","none");
    $(this).next().slideUp(300);
    $(this).removeClass("selected");
    if($(this).next().css("display")=="none"){
      $(this).addClass("open_close_r");
      $(".a_contents_r").slideUp(300);
      $(this).next().slideDown(300);
      $("+.a_contents_r p",this).fadeIn(1500);
      $(".selected").removeClass("selected");
      $(this).addClass("selected");
    }
  });
});

The class “.a_item_r” is assigned a click event using “click(function(){});”.
Inside this function, several reset operations are performed to ensure correct behavior on repeated clicks:

“.a_item_r” has the class “open_close_r” removed using “removeClass”.
“.a_contents_r p” is hidden using “display:none”.
The next sibling element of the clicked item is closed using “slideUp(300)”.

Next is the if statement, which is a conditional branch.
The condition “if($(this).next().css('display')=='none')” means: if the next sibling element of the clicked item is currently hidden, execute the following process inside the braces.

$(this).addClass("open_close_r"); → adds the open/close state class
$(".a_contents_r").slideUp(300); → closes all accordion contents
$(this).next().slideDown(300); → opens the next sibling element
$("+.a_contents_r p",this).fadeIn(1500); → fades in paragraph elements with delay
$(".selected").removeClass("selected"); → removes selected state from other items
$(this).addClass("selected"); → adds selected state to the clicked item

Change the color when the mouse hovers over the element

.a_item_r:hover{background-color:#6aec99;}

By specifying “background-color”, you can change the color of “.a_item_r” when the mouse hovers over it.

Add color to the selected item when it is clicked

$(this).removeClass("selected");
$(this).addClass("selected");

“removeClass” removes the specified class, and “addClass” adds the specified class.
In this case, these are used to control the selected state when an item is clicked.

When one accordion is already open, clicking another closed accordion will close the currently open one

$(".a_contents_r").slideUp(300);
$(this).next().slideDown(300);

First, the currently open accordion is closed, and then the accordion that was clicked is opened.

Fade in the content of the selected item with a delay after clicking

$("+.a_contents_r p",this).fadeIn(1500);

The “fadeIn()” method is used to gradually display hidden elements.
In this case, it is used to make the text fade in when the accordion menu is opened.
With “fadeIn(1500)”, the animation runs over 1.5 seconds.

Add animation to the right-side arrow to indicate open/close state

$(".a_item_r").removeClass("open_close_r");
$(this).addClass("open_close_r");

The class “.open_close_r” is responsible for the arrow animation.
Therefore, “removeClass” and “addClass” are used to remove and add the class as needed.
The actual animation behavior is defined in CSS.

One point

if( /* condition */ ){
  /* some process */
}else{
  /* another process */
}

The if statement executes a process when the condition inside it evaluates to true.
If the condition is false, the process inside else {} will be executed instead.

view demo

Accordion 1

Accordion 2

Accordion 3

view demo

Accordion 1

Accordion 2

Accordion 3

CSS3 Implementation

Until now, we have implemented the accordion using HTML, CSS, and :contentReference[oaicite:0]{index=0}.
However, it is also possible to create the same behavior using only CSS.

To achieve a CSS-only implementation, we use the ON/OFF state of a form element called a checkbox.

  • Accordion 1
  • Accordion 2
  • Accordion 3

HTML

<div class="a_container">
  <label for="Panel1">demo</label>
  <input type="checkbox" id="Panel1" class="open_close_c"/>
  <ul>
    <li>Accordion 1</li>
    <li>Accordion 2</li>
    <li>Accordion 3</li>
  </ul>
</div>

CSS

label {
  display: block;
  background-color: #70f9a1;
  color: #fff;
  padding: 10px;
  text-align: center;
}
label:hover{
  background-color:#6aec99;
}
input[type="checkbox"].open_close_c{
  display: none;
}
ul{
  border:solid 1px #d6dddf;
  transition: all 0.3s;
  margin: 0;
  padding: 0;
  list-style: none;
}
li{
  margin:10px 0;
  color:#666666;
  border-bottom:dashed 1px #d6dddf;
}
input[type="checkbox"].open_close_c + ul{
  height: 0;
  overflow: hidden;
}
input[type="checkbox"].open_close_c:checked + ul{
  height: 110px;
  padding:10px;
}

The class “.open_close_c” is hidden using display:none; so that the checkbox itself is not visible.

Animation speed is controlled using the transition property on the ul element.
Instead of using display to hide the element, the height property is used because display cannot be animated.

The hidden state is defined with height:0; and overflow:hidden;.
When the checkbox is checked, the height changes (e.g., to 110px), and this transition creates a smooth animation effect.

A label element is used to simulate clicking the checkbox.
By setting the for attribute to match the checkbox id, clicking the label toggles the checkbox ON/OFF.

This allows CSS to differentiate between the two states:
input[type="checkbox"].open_close_c + ul (unchecked state)
input[type="checkbox"].open_close_c:checked + ul (checked state)

One point

input[type="checkbox"].open_close_c:checked + ul

The selector input[type="checkbox"] is an example of an attribute selector in CSS.
It allows you to apply styles based on attribute names or attribute values.

The full selector input[type="checkbox"].open_close_c:checked + ul targets the ul element that is the next sibling of a checked checkbox with the class “.open_close_c”.

Summary

How was it?
An accordion menu can be implemented in various ways by using the “click” event to add classes to target elements. However, since :contentReference[oaicite:0]{index=0} processes code from top to bottom, even correctly written code may fail if the order is wrong, which can be challenging.

With the introduction of CSS3, it has become possible to implement similar functionality without using jQuery. New implementation methods may continue to emerge in the future. Since the web industry evolves very quickly, we must keep learning every day to stay up to date.

PREV
Vol.44Creating AMP HTML for Faster Mob…
NEXT
Vol.46Summer Traditional Colours and P…

MORE FOR YOU