forked from itchief/ui-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtabs.js
47 lines (47 loc) · 1.63 KB
/
tabs.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
class ItcTabs {
constructor(target, config) {
const defaultConfig = {};
this._config = Object.assign(defaultConfig, config);
this._elTabs = typeof target === 'string' ? document.querySelector(target) : target;
this._elButtons = this._elTabs.querySelectorAll('.tabs__btn');
this._elPanes = this._elTabs.querySelectorAll('.tabs__pane');
this._eventShow = new Event('tab.itc.change');
this._init();
this._events();
}
_init() {
this._elTabs.setAttribute('role', 'tablist');
this._elButtons.forEach((el, index) => {
el.dataset.index = index;
el.setAttribute('role', 'tab');
this._elPanes[index].setAttribute('role', 'tabpanel');
});
}
show(elLinkTarget) {
const elPaneTarget = this._elPanes[elLinkTarget.dataset.index];
const elLinkActive = this._elTabs.querySelector('.tabs__btn_active');
const elPaneShow = this._elTabs.querySelector('.tabs__pane_show');
if (elLinkTarget === elLinkActive) {
return;
}
elLinkActive ? elLinkActive.classList.remove('tabs__btn_active') : null;
elPaneShow ? elPaneShow.classList.remove('tabs__pane_show') : null;
elLinkTarget.classList.add('tabs__btn_active');
elPaneTarget.classList.add('tabs__pane_show');
this._elTabs.dispatchEvent(this._eventShow);
elLinkTarget.focus();
}
showByIndex(index) {
const elLinkTarget = this._elButtons[index];
elLinkTarget ? this.show(elLinkTarget) : null;
};
_events() {
this._elTabs.addEventListener('click', (e) => {
const target = e.target.closest('.tabs__btn');
if (target) {
e.preventDefault();
this.show(target);
}
});
}
}