Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery add/remove class onClick

Tags:

jquery

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/

like image 474
Gallex Avatar asked Nov 30 '22 10:11

Gallex


2 Answers

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()

like image 129
empiric Avatar answered Dec 19 '22 16:12

empiric


Use toggleClass instead.

$(document).ready(function(){
  $('#toggle li').on('click', function(){
  $(this).toggleClass('open');
});
});
like image 36
Pramod Karandikar Avatar answered Dec 19 '22 16:12

Pramod Karandikar