reyjoel reyjoel - 4 months ago 20
Javascript Question

NO error display but cant slideUp();

I have this slide up and slide down. I can slide down the child on click but cant slide up when click again.

this is my script

jQuery("#all li").on("click",function(e){
e.preventDefault();
var parent = jQuery(this);
var father = parent.data("clicked",true);
var child = parent.find("ul");
var x = child.on(":visible");

if(parent.is(":visible")){
child.slideDown("fast");
}else{
child.slideUp("fast");
}
});


and this is my Html

<nav>
<ul id="all">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
<ul>
<li><a href="#">Sub-Link 1</a></li>
<li><a href="#">Sub-Link 2</a></li>
<li><a href="#">Sub-Link 3</a></li>
</ul>
</li>
<li><a href="#">Link 3</a>
<ul>
<li><a href="#">Sub-Link 1</a></li>
<li><a href="#">Sub-Link 2</a></li>
<li><a href="#">Sub-Link 3</a></li>
<li><a href="#">Sub-Link 4</a></li>
</ul>
</li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
<li><a href="#">Link 6</a></li>
</ul>
</nav>

Answer

It seems to me, based on your posted script and markup, that the parent is always visible. This means the if statement has essentially no effect. Altering it to check if the child is visible may help:

$('#all li').on('click', function() {
    var parent = $(this);
  var child = parent.find('ul');

   if(child.is(':visible')){
   $(child).slideUp('fast');
   } else {
   $(child).slideDown('fast');
   }

});

Fiddle Demo