Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide with plus minus

So I've got it to work that it shows/hides the UL's/LI's, but I'm not sure what I'm doing incorrectly where it's not swapping out the +/- signs?

Here's my JS:

$(".top ul li:not(:has(li.current))").find("ul").hide().end() // Hide all other ULs
.click(function (e) {
if (this == e.target) {
    $(this).children('ul').slideToggle();
}
$(this).children("li.menu-item-has-children").text(this.toggle ? "-" : "+");
return false;
});

I have a class setup to append the li with a li:before that add the + sign before the li that has the nested ul's. But I'm not sure if I am going about it the right way to swap out the signs.

Here's the fiddle that I made:

http://jsfiddle.net/bc4mg13a/

like image 819
ultraloveninja Avatar asked Oct 31 '22 18:10

ultraloveninja


2 Answers

There you go: http://jsfiddle.net/bc4mg13a/13/

$(".menu-item-has-children").on("click", function(e){
  e.stopPropagation();
  var clickedLi = $(this);
  $("> ul", clickedLi).slideToggle();
  clickedLi.toggleClass("current"); 
});

To start with, your first js line is a has so much redundant stuff.

$(".top ul li:not(:has(li.current))").find("ul").hide().end() // Hide all other ULs .click

could be:

$(".top ul li:not(.current)").find("ul").hide().end() // Hide all other ULs .click

On the other hand, i changed your code slightly, simplified your selectors. On each li click, i select direct ul children, and the i slidetoggle + toggle class the 'current' class.

i also switch the plus sign via the current class on css.

like image 107
Pablo Rincon Avatar answered Nov 12 '22 17:11

Pablo Rincon


Your code feels incredibly verbose. Well, at least your js. Here's a fiddle of your code that I modified a little bit.

Instead of hiding all your menus with js immediately on pageload, I applied a CSS display: none; to the sub-menu class:

.sub-menu {
  display: none; 
}

The js is cleaned up a bit, and since the click handler is bound to .menu-item-has-children, You're really only clicking on that to reveal the contained UL.

Give it a look. Hope it helps :)

like image 28
Morklympious Avatar answered Nov 12 '22 19:11

Morklympious