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.
$(document).ready(function() { var previousActiveTabIndex = 0; $(".tab-switcher").on('click', function (event) { if (event.type === "click") { var tabClicked = $(this).data("tab-index"); $(".tab-switcher").removeClass("active") $(this).addClass("active") if(tabClicked != previousActiveTabIndex) { $(".tab-container").hide(); $("#allTabsContainer .tab-container").each(function () { if($(this).data("tab-index") == tabClicked) { $(this).show(); previousActiveTabIndex = $(this).data("tab-index"); return; } }); } } }); });
#header ul { margin: 0.15em; padding-bottom: 0.3em; padding-left: 0.4em; } .tab-switcher { display: inline-block; cursor: pointer; margin-right: 1.7em; } .tab-switcher:hover { color: #0f0; border-bottom: 0.15em solid var(--mainCol); } .tab-switcher.active { color: var(--mainCol); border-bottom: 0.15em solid var(--mainCol); font-weight: bold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="header"> <ul> <li class="tab-switcher active" data-tab-index="0" tabindex="0">Locations</li> <li class="tab-switcher" data-tab-index="1" tabindex="0">Inventory</li> <li class="tab-switcher" data-tab-index="2" tabindex="0">Profile</li> </ul> </div> <div id="allTabsContainer" data-tab-show="0"> <div class="tab-container" id="locations" data-tab-index="0"> content 1 </div> <div class="tab-container" data-tab-index="1" style="display:none"> content 2 </div> <div class="tab-container" data-tab-index="2" style="display:none"> content 3 </div> </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.
function Tabmenu() { var previousActiveTabIndex = 0; let Tab = document.querySelectorAll('tab-switcher'); let Content = document.querySelectorAll("tab-container"); Tab.forEach(t => t.addEventListener("click", function() { alert("coucou"); })) } window.onload = Tabmenu;
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.
document.querySelectorAll('.tab-switcher');
and
document.querySelectorAll(".tab-container");
Hope this helps!