I have a function in jQuery to switch tabs and as it the only one using jQuery, I want to convert it to JS only. After hours of trying (still learning) and feeling miserable to fail at this trivial thing, I humbly ask for help.
JavaScript
x
21
21
1
$(document).ready(function() {
2
var previousActiveTabIndex = 0;
3
4
$(".tab-switcher").on('click', function (event) {
5
if (event.type === "click") {
6
var tabClicked = $(this).data("tab-index");
7
$(".tab-switcher").removeClass("active")
8
$(this).addClass("active")
9
if(tabClicked != previousActiveTabIndex) {
10
$(".tab-container").hide();
11
$("#allTabsContainer .tab-container").each(function () {
12
if($(this).data("tab-index") == tabClicked) {
13
$(this).show();
14
previousActiveTabIndex = $(this).data("tab-index");
15
return;
16
}
17
});
18
}
19
}
20
});
21
});
JavaScript
1
22
22
1
#header ul {
2
margin: 0.15em;
3
padding-bottom: 0.3em;
4
padding-left: 0.4em;
5
}
6
7
.tab-switcher {
8
display: inline-block;
9
cursor: pointer;
10
margin-right: 1.7em;
11
}
12
13
.tab-switcher:hover {
14
color: #0f0;
15
border-bottom: 0.15em solid var(--mainCol);
16
}
17
18
.tab-switcher.active {
19
color: var(--mainCol);
20
border-bottom: 0.15em solid var(--mainCol);
21
font-weight: bold;
22
}
JavaScript
1
21
21
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="header">
3
<ul>
4
<li class="tab-switcher active" data-tab-index="0" tabindex="0">Locations</li>
5
<li class="tab-switcher" data-tab-index="1" tabindex="0">Inventory</li>
6
<li class="tab-switcher" data-tab-index="2" tabindex="0">Profile</li>
7
</ul>
8
</div>
9
10
11
<div id="allTabsContainer" data-tab-show="0">
12
<div class="tab-container" id="locations" data-tab-index="0">
13
content 1
14
</div>
15
<div class="tab-container" data-tab-index="1" style="display:none">
16
content 2
17
</div>
18
<div class="tab-container" data-tab-index="2" style="display:none">
19
content 3
20
</div>
21
</div>
I was about here when I gave up, my forEach/event listener won’t even work and I don’t know even why, any help/explanation appreciated.
JavaScript
1
12
12
1
function Tabmenu() {
2
var previousActiveTabIndex = 0;
3
let Tab = document.querySelectorAll('tab-switcher');
4
let Content = document.querySelectorAll("tab-container");
5
6
Tab.forEach(t => t.addEventListener("click", function() {
7
alert("coucou");
8
}))
9
}
10
11
window.onload = Tabmenu;
12
Advertisement
Answer
I believe the element listener is not being called, try adding a “.” in front of the selector names as follows. I reckon it does not know what the element is.
JavaScript
1
2
1
document.querySelectorAll('.tab-switcher');
2
and
JavaScript
1
2
1
document.querySelectorAll(".tab-container");
2
Hope this helps!