jQuery Accordion Plugin
Last updated: 10.10.2025
Views: 322
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:
-
jQuery Tabs Plugin
Tabs are a fairly common element. There are various implementations of this element on the Internet. But often the tabs are overloaded with code filled with effects that ...
-
Swipe Events on Touch Devices in JavaScript
Every day sensory devices are being introduced into our lives. These devices have specific events, unlike the desktop. One of these events is the swipe. Especially often ...
-
How to Detect Scroll Direction on a Page Using JavaScript
Sometimes it is necessary to detect the direction of vertical scrolling on a website in order to dynamically change the behavior of interface elements. For example, this ...
Leave a Reply