How to Add Accordion Without Using Plugin to WordPress Blog

In this quick video tutorial, I will show you how to add Accordion to WordPress blog without using a plugin. In web design, an accordion is a type of menu that displays a list of headers stacked on top of one another. When clicked on, these headers will either reveal or hide associated content.

How to Add Custom JavaScript Code?

We will use a plugin called Header Footer Code Manager to add custom JavaScript code to WordPress website.

Custom CSS Code

/* Accordion CSS - Begins */
.wpfaccordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}
.wpfaccordion-active, .wpfaccordion:hover {
  background-color: #cccccc;
}
.wpfaccordion:hover {
  color: #222222;
}
.wpfpanel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
}
.wpfpanel p {
  margin-top: 15px;
}
.wpfaccordion:after {
  content: '\02795'; 
  font-size: 13px;
  color: #777;
  float: right;
  margin-left: 5px;
}
.wpfaccordion-active:after {
  content: "\2796";
}
/* Accordion CSS - Ends */

Accordion HTML Code Template

<button class="wpfaccordion">Header Content Comes Here</button>
<div class="wpfpanel">
  <p>Inner Content Comes Here</p>
</div>

Custom JavaScript Code

<script>
var wpfaccordion = document.getElementsByClassName("wpfaccordion");
var i;

for (i = 0; i < wpfaccordion.length; i++) {
  wpfaccordion[i].addEventListener("click", function() {
    this.classList.toggle("wpfaccordion-active");
    var wpfpanel = this.nextElementSibling;
    if (wpfpanel.style.maxHeight) {
      wpfpanel.style.maxHeight = null;
    } else {
      wpfpanel.style.maxHeight = wpfpanel.scrollHeight + "px";
    }
  });
}
</script>

The above code snippets is extremely small and it wont have any impact on website’s performance.

Leave a Comment