JQuery Extension Nav Collapsing on Child Click

https://jsfiddle.net/aesya0g6/

Hello!

I built an expandable navigator, and it works exactly the way I want, except that it crashes when the children are clicked. I tried switching to where jQuery points out, in the hope that this would resolve it, but no luck. Where am I going wrong?

    $('.expandingNav').click(function(){
  if($(this).hasClass('expanded')){
    $(this).children('.hidden').slideUp();
    $(this).removeClass('expanded');
  }
  else{
    $(this).children('.hidden').slideDown();
    $(this).addClass('expanded');
  }
});
+4
source share
5 answers

You can check if the closest element has a ulparent element nav.sidebar:

$('.expandingNav').on('click', function (e) {
    if ($(e.target).closest('ul').parent('nav.sidebar').length) {
        // ...
    }
});

Updated example

$('.expandingNav').on('click', function (e) {
    if ($(e.target).closest('ul').parent('nav.sidebar').length) {
        if ($(this).hasClass('expanded')) {
            $(this).children('.hidden').slideUp();
            $(this).removeClass('expanded');
        } else {
            $(this).children('.hidden').slideDown();
            $(this).addClass('expanded');
        }
    }
});

Alternatively, you can also check if the parent is the following sibling ul:

$('.expandingNav').on('click', function (e) {
    if ($(e.target).parent().next('ul').length) {
        // ...
    }
});

Updated example

$('.expandingNav').on('click', function (e) {
    if ($(e.target).parent().next('ul').length) {
        if ($(this).hasClass('expanded')) {
            $(this).children('.hidden').slideUp();
            $(this).removeClass('expanded');
        } else {
            $(this).children('.hidden').slideDown();
            $(this).addClass('expanded');
        }
    }
});
+2

, :

//If the e.target is the same element as this, you've not clicked on a descendant.
if( e.target !== this ) return;

+1

, click "" , , . click stopPropagation, . - :

$('.expandingNav li').click(function(ev) { ev.stopPropagation(); })
0

shuold -. li expandingNav.

   $("li.expandingNav").on('click', function(e) {
  if($(this).hasClass('expanded')){
    $(this).children('.hidden').slideUp();
    $(this).removeClass('expanded');
  }
  else{
    $(this).children('.hidden').slideDown();
    $(this).addClass('expanded');
  }
    });
//On sub LI click , stop propagating. 
$("li.expandingNav li").on('click', function(e) {
 e.stopPropagation();
}); 

0

.

.

:

  $('.expandingNav').children('a').click(function(){
   var element = $(this).parent();
  if($(element).hasClass('expanded')){
    $(element).children('.hidden').slideUp();
    $(element).removeClass('expanded');
  }
  else{
    $(element).children('.hidden').slideDown();
    $(element).addClass('expanded');
  }
});
0

All Articles