Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Stop dropdown menu from collapsing when clicking on its children

Tags:

jquery

I have a top nav bar and some of its items trigger dropdowns/slide-downs.

My problem is that whenever I click an item, or actually any area within the dropdown, the dropdown collapses.

What I need help with is figuring out how to avoid collapsing the dropdown when a child element is clicked (or well, anywhere within the dropdown area since I'd like to account for accidental clicks inside the dropdown but that are not actually clicks on a child element).

Here's the basic HTML structure I have:

<ul class="dropdown">
 <li><a href="#" class="noclick nojs">Select your Topic</a>
  <ul class="nojs" >
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
  </ul>
 </li>
</ul>

My JavaScript:

$('.dropdown li').click(function() {
  //Hide all other drop downs that are visible, and remove the class 'selected'
  $(this).siblings('.selected').removeClass('selected').find('ul:visible').slideUp('fast');

  //Show/Hide dropdowns
  $(this).toggleClass('selected');
  $('ul:first', this).stop(true, true).slideToggle('fast');
});

Here's a DEMO

Any help is greatly appreciated.

Thanks.

like image 925
Ricardo Zea Avatar asked Feb 19 '23 12:02

Ricardo Zea


1 Answers

stop event.stopPropagation() on those children elements so the event doesn't bubble up to the li

$('ul.nojs *').click(function(e){
   e.stopPropagation(); 
});​

http://jsfiddle.net/DEfK9/

like image 192
wirey00 Avatar answered Feb 21 '23 02:02

wirey00