jQuery Accordion Plugin
Last updated: 10.10.2025
Views: 152
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 Detect the Operating System (OS) Using JavaScript
Sometimes it is necessary to determine the user's operating system. To use different CSS styles for different OS, or for some analytics, or for other purposes. There are ...
-
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 ...
-
Countdown Timer in JavaScript
Often on sites that sell something, you can find a countdown timer to a certain date. Such a script is usually needed for landing pages or online stores. In one of the pr...
Leave a Reply