Open submenu on click, close on next click - that's what i would like to achive. example is this page (submenu under 'follow' link).
it opens submenu (adds class 'open'), but not closing. stucked... :(
my html:
<ul id="toggle"><li>
<a href="#">Menu</a>
<ul id="dropdown" class="dropdown-menu" role="menu">
<li><a href="#">2017</a></li>
<li><a href="#">2012</a></li>
<li><a href="#">2003</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
javascript:
$(document).ready(function(){
$('#toggle li').on('click', function(){
$(this).removeClass('open').addClass('open');
});
});
http://jsfiddle.net/Gallex/32pv6xz8/7/
You can use the function toggleClass()
for this:
$('#toggle li').on('click', function () {
$(this).toggleClass('open')
});
Demo
Here is a slightly different approach:
jQuery
$('#toggle li').on('click', function () {
$(this).find('ul').slideToggle();
});
CSS
#toggle li ul {
list-style-type: none;
left:0;
position:absolute;
display: none;
}
Demo 2
For preventing the redirect you have to use .preventDefault()
:
$('#toggle li:has(#dropdown)').on('click', function (event) {
if ($(event.target).parents('#dropdown').length > 0) {
event.stopPropagation();
} else {
event.preventDefault();
}
$(this).find('ul').slideToggle();
});
I`m not sure if this is the cleanest or best approach, but it is working.
If you want to save the url for further use (e.g. redirectuing via window.location
) you can assign the href-attribute to a variable:
var href = $(this).find('a').attr('href');
Demo 3
Reference
.toggleClass()
.slideToggle()
Use toggleClass
instead.
$(document).ready(function(){
$('#toggle li').on('click', function(){
$(this).toggleClass('open');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With