Reputation: 299
I'm new to jQuery and am experimenting on hiding and showing li
lists.
I have it working to where the when you click on the parent li (li.2015
) the sub li (ul.2015
) list is shown and hidden.
However, I only want this behavior to work on the parent li (li.2015
) and not when clicking on the sub li list (ul.2015
).
Right now it hides when I click on the sub li list (ul.2015
) which I don't want to happen, I only want the show/hide to function on the parent li (li.2015
).
What changes do I need to make to my jQuery for this?
html
<div class="content">
<ul class="date">
<li class="2015">2015
<ul class="2015">
<li><a href="http://google.com">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</li>
</ul>
</div>
jquery
(function () {
var ulSub = $('ul.2015');
$('li.2015').on('click', function (e) {
e.stopPropagation();
ulSub.toggle();
});
ulSub.hide();
$(this).on('click', function () {
ulSub.hide();
});
})();
Upvotes: 0
Views: 1020
Reputation: 655
Actually Parent li contains the child li elements that is the reason it is happening in that way. try below code using extra span element will solve the problem.
<div class="content">
<ul class="date">
<li class="2015"><span id="spanId">2015</span>
<ul class="2015">
<li><a href="http://google.com">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</li>
</ul>
</div>
(function() {
var ulSub = $('ul.2015');
$('li.2015 span#spanId').on('click', function(e) {
e.preventDefault();
ulSub.toggle();
});
$('a[href="#"').on('click', function(e) {
e.preventDefault();
});
})();
Upvotes: 0
Reputation: 25352
Sub item hides because you wrap ul
with li.2015
.
Your html
<div class="content">
<ul class="date">
<li class="2015">2015
<ul class="2015">
<li><a href="http://google.com">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</li>
</ul>
</div>
When you click on subitem then first will go through parent li
which you wrapped your child with.
Try like this
HTML
<div class="content">
<ul class="date">
<li class="2015">2015</li>
<ul class="2015">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
</ul>
</div>
Javascript
var ulSub = $('ul.2015');
ulSub.hide();
$('li.2015').on('click', function(e) {
e.stopPropagation();
ulSub.toggle();
});
Upvotes: 1
Reputation: 18600
You need only following code and remove other code from jquery code.
var ulSub = $('ul.2015');
$('li.2015').on('click', function(e) {
e.stopPropagation();
ulSub.toggle();
});
Upvotes: 1