JQuery: stop dropdown menu when crashing when clicking on its children

I have a top navigation bar, and some of its elements trigger dropdown menus / slides.

My problem is that whenever I click on an item or virtually any area in the drop-down list, the drop-down menu crashes.

I need help figuring out how to avoid dropping a dropdown when a child is clicked (or anywhere in the dropdown list, since I would like to take into account random clicks inside the dropdown, but this doesn’t actually click on the child )

Here is the basic HTML structure:

<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 demo

Any help is greatly appreciated.

Thanks.

+4
source share
4 answers

stop event.stopPropagation () on these children so that the event does not turn into li

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

http://jsfiddle.net/DEfK9/

+7
source

Demo . Attach the .click() event to the <a> tags instead of the <li> tags.

 $('.dropdown .noclick').click(function(e) { // Do stuff. }); 
+1
source

You can simply change slideToggle () to slideDown () using the snippet below:

http://jsfiddle.net/yrzRu/

 if ($(this).not('.selected')) { $('ul:first', this).stop(true, true).slideDown('fast'); $(this).addClass('selected'); } 
0
source

Here you go!

Fiddle

 $('.dropdown').children('li').click(function() { //Show clicked dropdown and add 'selected' class $(this).addClass('selected').find('ul').slideToggle('fast'); //Hide all other dropdowns and remove 'selected' class $('.dropdown').children('li').not(this).removeClass('selected').find('ul').slideUp('fast'); }); 
0
source

Source: https://habr.com/ru/post/1445609/


All Articles