jQuery Accordion Plugin
Last updated: 10.10.2025
Views: 351
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:
-
How to Submit a Form Using jQuery Ajax ($.ajax)
Submitting a form using jQuery's $.ajax method is a powerful way to send data to the server without reloading the page. This approach improves user experience and allows ...
-
Ways to Create Objects in JavaScript
There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain ot...
-
How to Сlone (Copy) Object and Array in JavaScript
Cloning objects and arrays is not as simple a topic as it may seem at first glance. Cloning objects and arrays in JavaScript can be done using various methods depending...
Leave a Reply