Reputation: 1699
I have a list in my navigation bar which has a list inside it used as a drop down menu. The overall list is named categories (I know it should have a reference to another page but I am just trying to get the dynamic content working first).
I have an event listener attached to this element which takes the user to a page that displays all categories.
As you hover over this element it displays a list of categories. What i would like to do is to be able to click on one of these and it take the user straight to the category.
This works with my code but only in certain places. In others it takes me to the page which displays all categories.
Here is the code i am using to add the events:
var categoryHeading = document.getElementById('categoriesNav');
dropList = document.createElement("ul");
dropList.setAttribute("id", "categoriesDrop");
categoryHeading.appendChild(dropList);
categoryHeading.addEventListener('click', displayCategoriesPage); //displayCategoriesPage displays a page with all categories listed
categoryHeading.addEventListener("mouseover", function(){
if(dropList){
dropList.style.display = "block";
}
});
categoryHeading.addEventListener("mouseout", function(){
if(dropList){
dropList.style.display = "none";
}
});
var categoryListItems = document.getElementsByClassName("categoryListItem");
for(var i=0; i<categoryListItems.length; i++){
categoryListItems[i].addEventListener("click", function(e){
displaySingleCategory(e); //Displays the page with all items from one category
});
}
Here is the HTML:
<nav>
<ul>
<li id="homeNav"></li>
<li id="categoriesNav">
<a>Categories</a>
<ul id="categoriesDrop">
<li class="categoryListItem">Outdoor</li>
<li class="categoryListItem">Technology</li>
</ul>
</li>
<li id="basket"></li>
<li id="search"></li>
</ul>
</nav>
I am assuming the problem is to do with how my <nav>
is laid out. Or where i have added the events.
Upvotes: 0
Views: 183
Reputation: 782
In Javascript whenever an event is triggered, it's default behaviour is bubbling up through DOM.
In your case, you need to stop the event propagation because you have a click listener in the child li and it's parent that will be executed showing you the categories page instead of specific category page.
Try to put e.stopPropagation();
in your child event listeners.
Upvotes: 2