jQuery Accordion Plugin
Last updated: 10.10.2025
Views: 208
An accordion is often used on websites. This element is popular and convenient at the same time. An accordion helps to structure content and save space. In my work, I often used jQuery (and sometimes use it now). And with the help of this library, I wrote an accordion plugin for use in different projects. The plugin is based on the slideToggle() method. Maybe this plugin will also be useful to someone. That’s why I posted the code in this note. In addition, in one of the previous articles, we looked at the jQuery tabs plugin.
HTML
<div class="accordion">
<div class="acc-title">
Caption 1
</div>
<div class="acc-cont">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti eius quisquam excepturi eaque a soluta laborum delectus in culpa! Necessitatibus ea obcaecati.
</div>
<div class="acc-title">
Caption 2
</div>
<div class="acc-cont">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deleniti eius quisquam excepturi eaque a soluta laborum delectus in culpa! Necessitatibus ea obcaecati.
</div>
<div class="acc-title">
Caption 3
</div>
<div class="acc-cont">
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages.
</div>
</div>
CSS
/* required styles */
.acc-cont {
display: none; /*hide content*/
}
Initialization
$(() => {
$('.accordion').simpleAccordion();
});
Initialization with options
$(() => {
$('.accordion').simpleAccordion({
'title' : '.othertitle',
'content': '.othercontent',
'cb': callbackFunction,
'speed': 500
});
});
Plugin code
$.fn.simpleAccordion = function(options) {
const settings = $.extend({
'title': '.acc-title',
'content': '.acc-cont',
'cb': '',
'speed': 400
}, options);
const accTitle = $(this).find(settings.title);
accTitle.on('click', function() {
if (!$(this).next().is(':visible')) {
$(settings.content).slideUp(settings.speed);
$(settings.title).removeClass('active');
}
$(this).next().stop().slideToggle(settings.speed);
$(this).toggleClass('active');
if (settings.cb) {
settings.cb();
}
});
};
You can see an example of using jQuery plugin on Codepen: https://codepen.io/igorrybalko/pen/EaYNyWx
Similar posts:
-
Drop down menu (jQuery)
Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay i...
-
Vue Accordion Component
A simple and lightweight Vue 3 accordion component plugin. Supports both global plugin registration and local component usage. Written in TypeScript. The accordion compon...
-
Simple JavaScript Clock
There are many examples of implementing a clock using JavaScript, and while the approaches may vary slightly, most of them follow a similar idea. Typically, such function...
Leave a Reply