I’m making a dropdown menu of WordPress category. In my case I look for the list item that has a children class then I add a parent class to that li. When you click on it a dropdown menu of its children category displayed. Here’s the code:
$('.list-category ul li').find('ul').each(function(){
if( $(this).hasClass('children') ){
$(this).parent().find('a:first').append('<span class="parent">»</span>');
$('span.parent').click(function(e) {
e.preventDefault();
e.stopPropagation();
$('.list-category ul li ul.children').css({ 'display' : 'block' });
});
}
});
The code works perfectly if you have only have one sub category of children class. Thing is getting ugly when you get more than one. Every subclass menu display no matter any parent class of the li you click on.
When you view it in a dev tool get something like this:
.list-category ul li item-3
.list-category ul li item-7
How do I click on an li of item-3 and I get children li of item-3 display and not list of other children div.
$('.list-category ul li').find('ul').each(function() {
var self = $(this);
if (self.hasClass('children')) {
self.parent().find('a:first').append('<span class="parent">»</span>').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
self.show();
}
}
});
The problem was that you created a very generic .click for span.parent, which indeed doesn’t work. I’m creating a .click for each parent specifically, which solves the problem
There are other ways, but this one is relatively simple
As an aside, I find it easy to create a function nothing in my projects as follows
function nothing(e) {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}
Then whenever you want to stop default browser behavior, just end with return nothing(e); instead of having to type e.preventDefault() et al over and over and over and over and over and over and over …
This won’t work. I want to click on the <span> tag and show the drop down menu, not the whole parent li. I want the page redirected when clicking on the parent li.
Thanks goodness you understand my gibberish explanation. I typed it down just before I fell asleep after long hours of try and error.
You’ve mentioned some of other ways to do this. What are them? But if this is the simplest way I would go with it.
The nothing function is nice idea though. I would use it.
Thanks. The dropdown works perfectly, but the parent list does not redirect on clicking. I want the dropdown show only when clicking on the <span class=“parent”>»</span>, not include the parent.