window.onload = function() {
// setting the default landing page to #Overview
window.location.replace("#Overview");
// registering click event listeners for the top navigation bar:
var navBarButtons = ["class1","class2","class3","class4","class5","class6","class7","class8","class9"];
var navBarTargets = ["id1","id2","id3","id4","id5","id6","id7","id8","id9"];
registerNavBar(navBarButtons, navBarTargets);
}
function registerNavBar(navBarButtons, navBarTargets){
for (var i=0; i<navBarButtons.length; i++){
sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
sourceElement.addEventListener("click",clickNavBarButton({targets:navBarTargets,index:i}))
}
}
function clickNavBarButton(event){
clearPages(event.targets);
document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
}
function clearPages(navBarTargets) {
for (i=0; i<navBarTargets.length; i++){
var target = "#".concat(navBarTargets[i]),classList=document.querySelector(target).classList;
if (classList.contains("active")){
classList.remove("active")
}
}
}
Trying to implement onclick events on elements in the navigation bar with this structure:
<div id="left_nav">
<a href="#Overview" title="Overview"><span class="class1"></span></a>
The registerNavBar() function is not successfully adding onclick events to the elements selected by #left_nav .classn
.
The definition of the .active
class is:
.active {
display: block!important
}
while the default state is:
display: none
therefore, toggling visibility. External libraries are not an option.
All functions in the loop are executing without errors and the element with #id9 is displayed, but the buttons do not trigger the onclick events when clicked. What is the correct way to add eventListeners to all elements in the Array?