-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaccordion.js
94 lines (83 loc) · 2.77 KB
/
accordion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Accordion Settings
const accSettings = {
speed: 300,
oneOpen: true,
offsetAnchor: false,
offsetFromTop: 180,
scrollTopDelay: 400,
classes: {
accordion: "accordion_wrapper",
header: "accordion_header",
item: "js-accordion-item",
body: "js-accordion-body",
icon: "accordion_icon",
active: "active",
},
};
const prefix = accSettings.classes;
const accordion = (function () {
const accordionElem = $(`.${prefix.accordion}`);
const accordionHeader = accordionElem.find(`.${prefix.header}`);
const accordionItem = accordionElem.find(`.${prefix.item}`);
const accordionBody = accordionElem.find(`.${prefix.body}`);
const accordionIcon = accordionElem.find(`.${prefix.icon}`);
const activeClass = prefix.active;
return {
// pass configurable object literal
init: function (settings) {
accordionHeader.on("click", function () {
accordion.toggle($(this));
if (accSettings.offsetAnchor) {
setTimeout(() => {
$("html").animate(
{ scrollTop: $(this).offset().top - accSettings.offsetFromTop },
accSettings.speed,
);
}, accSettings.scrollTopDelay);
}
});
$.extend(accSettings, settings);
// ensure only one accordion is active if oneOpen is true
if (settings.oneOpen && $(`.${prefix.item}.${activeClass}`).length > 1) {
$(`.${prefix.item}.${activeClass}:not(:first)`)
.removeClass(activeClass)
.find(`.${prefix.header} > .${prefix.icon}`)
.removeClass(activeClass)
.css({
transform: "rotate(0deg)",
});
}
// reveal the active accordion bodies
$(`.${prefix.item}.${activeClass}`).find(`> .${prefix.body}`).show();
},
toggle: function ($this) {
if (accSettings.oneOpen) {
const $activeItem = accordionItem.filter(`.${activeClass}`);
const $activeIcon = $activeItem.find(`> .${prefix.header} > .${prefix.icon}`);
if (!$this.closest(accordionItem).hasClass(activeClass)) {
$activeItem.removeClass(activeClass).find(accordionBody).slideUp(accSettings.speed);
$activeIcon.css({
transform: "rotate(0deg)",
});
}
}
const $item = $this.closest(accordionItem);
const $icon = $item.find(`> .${prefix.header} > .${prefix.icon}`);
$item.toggleClass(activeClass);
if ($item.hasClass(activeClass)) {
$icon.css({
transform: "rotate(45deg)",
});
$this.next().stop().slideDown(accSettings.speed);
} else {
$icon.css({
transform: "rotate(0deg)",
});
$this.next().stop().slideUp(accSettings.speed);
}
},
};
})();
$(document).ready(function () {
accordion.init(accSettings);
});