The following is the code am using to create on click method. I am getting an error when I click, nothing happens and I don\'t know what is wrong.
"Don't Repeat Yourself."
You don't need 12 separate functions to cover every single element. This duplicates code and makes it harder to troubleshoot (as you saw), and harder to maintain. You'd have to add new functions for every new item category!
Instead, you can add event listeners to each of the menu tags in a loop. Here you can also give your elements unique IDs or a class. In HTML5 you can add custom data- attributes as well.
(function addEventListeners(){
//Give the an ID instead of a class to target only those - elements.
var menuItems = document.getElementById("cbp-vimenu").getElementsByTagName("li");
var len = menuItems.length;
for (var i=0; i < len; i++){
menuItems[i].addEventListener("click", showMenu);
menuItems[i].setAttribute("id", "menuItem" + i);
menuItems[i].setAttribute("data-itemNum", i);
}
})();
Then create a single showMenu() function that compares the clicked to the div you want to show. You could use a switch-case approach, or if the list and the divs are in the same order you can match them numerically (Ex: the 3rd menu item -> the 3rd sub-menu div). Either option really cuts down the code, which makes things less repetitive & easier to troubleshoot.
Option 1, switch-case (JSFiddle):
function showMenu(){
hidemenus();
var selectedItem = this.id;
var divID;
switch (selectedItem){
case "menuItem1":
divID = "mobi";
break;
case "menuItem2":
divID = "elec";
break;
//add more cases here to account for other items
default: return false;
}
document.getElementById(divID).style.display = "block";
};
Option 2, match list item and div position in array of matching elements (JSFiddle):
function showMenu(){
hidemenus();
var itemNum = this.getAttribute("data-itemNum");
var menuDivs = document.getElementsByClassName("answer_list");
menuDivs[itemNum].style.display = "block";
};
Your hidemenus() function can be simplified by targeting the class="answer_list" attribute instead:
function hidemenus() {
var menusToHide = document.getElementsByClassName("answer_list");
var len = menusToHide.length;
for (var i = 0; i < len; i++){
menusToHide[i].style.display = "none";
}
};
BTW, you don't need to use nested tags if all you're doing is changing CSS. You can put a click event listener on any element, and use CSS for the hand cursor to indicate that it's clickable.
li:hover{
cursor: pointer;
cursor: hand; /*outdated cross-browser option, but no harm including it*/
}
Also, try to avoid inline CSS and inline JavaScript like onClick() - it can be much harder to maintain. As you can tell, it's hard to troubleshoot this code, and if you want to change its functionality, you'd need to edit 20+ locations in HTML vs maybe 2 in external JS.
Ok, really last note - your HTML is missing some closing tags,