Ty Yt Ty Yt - 5 months ago 130
jQuery Question

Show/Hide ul li onclick jquery

I'd like to show/hide my submenus when a

<a href="#"></a>
is clicked.
Here is a code example :

<ul>
<li><a href="www.example.com">Test</a></li>
<li><a href="www.example.com">Test</a></li>
<li class="submenu">
<a href="#">Test 2</a>
<ul class="ul_submenu">
<li><a href="www.example.com">Test</a></li>
<li><a href="www.example.com">Test</a></li>
<li class="submenu_2">
<a href="#">Test 3</a>
<ul class="ul_submenu_2">
<li><a href="www.example.com">Test</a></li>
</ul>
</li>
</ul>
</li>
</ul>


$( 'li.submenu a[href="#"]').click(function(e) {
e.preventDefault();
$("ul.ul_submenu").css("display","block");
}, function() {
$("ul.ul_submenu").css("display","none");
});


You can find a JSFiddle.

I need to allow click on a tag when there are children elements, and modify the display of li. But I need to cancel the page reload when user clicks on a tag like this :
<a href="#"></a>

Answer

You can do,

$('li a').click(function(e) {
  e.preventDefault();
  $(this).closest("li").find("[class^='ul_submenu']").slideToggle();
});

Fiddle

Comments