Diogo Bento Diogo Bento - 1 month ago 6
Javascript Question

Toggle on click except one element

Given the following html structure, how to make

#top-bar-toggle
toggle on click except when clicking
.top-bar-menu-search
or its children?

<div id="top-bar-toggle">
<div id="top-bar-menu">
<ul class="vertical menu">
<li>
<a href="home_link"><h2>Home Item</h2></a>
</li>
<li>
<a href="other_link"><h2>Other Item</h2></a>
<ul class="nested vertical menu">
<li><a href="nested_link"><h2>Nested Item</h2></a></li>
<li><a href="nested_link"><h2>Nested Item</h2></a></li>
<li><a href="nested_link"><h2>Nested Item</h2></a></li>
</ul>
</li>
<li>
<a href="other_link"><h2>Other Item</h2></a>
<ul class="nested vertical menu">
<li><a href="nested_link"><h2>Nested Item</h2></a></li>
<li><a href="nested_link"><h2>Nested Item</h2></a></li>
<li><a href="nested_link"><h2>Nested Item</h2></a></li>
</ul>
</li>
<li class="top-bar-menu-search">
<form id="searchform" method="get" role="search">
<div class="input-group">
<span class="input-group-label"></span>
<input type="text" placeholder="Search" id="s" name="s" value="" class="input-group-field">
</div>
</form>
</li>
</ul>
</div>
</div>


I thought the following jquery code would work, but the
#top-bar-toggle
element gets toggled anyway…

$('#top-bar-toggle').not('.top-bar-menu-search').click(function() {
$(this).fadeToggle();
});


Thanks in advance!

Answer

I think you need to use stopPropagation method of jquery.

$('#top-bar-toggle').click(function() {
    console.log("topbar clicked");
  });
  $('.top-bar-menu-search').click(function(e) {
     e.stopPropagation();
    console.log("searchbar clicked");
  });