-
Notifications
You must be signed in to change notification settings - Fork 36
/
tabs.js
43 lines (36 loc) · 1.3 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
const removeActiveClasses = function (ulElement) {
const lis = ulElement.querySelectorAll('li');
Array.prototype.forEach.call(lis, function(li) {
li.classList.remove('active');
});
}
const getChildPosition = function (element) {
var parent = element.parentNode;
var i = 0;
for (var i = 0; i < parent.children.length; i++) {
if (parent.children[i] === element) {
return i;
}
}
throw new Error('No parent found');
}
window.addEventListener('load', function () {
const tabLinks = document.querySelectorAll('ul.tab li a');
Array.prototype.forEach.call(tabLinks, function(link) {
link.addEventListener('click', function (event) {
event.preventDefault();
liTab = link.parentNode;
ulTab = liTab.parentNode;
position = getChildPosition(liTab);
if (liTab.className.includes('active')) {
return;
}
removeActiveClasses(ulTab);
tabContentId = ulTab.getAttribute('data-tab');
tabContentElement = document.getElementById(tabContentId);
removeActiveClasses(tabContentElement);
tabContentElement.querySelectorAll('li')[position].classList.add('active');
liTab.classList.add('active');
}, false);
});
});