How to open a list when you hover an individual element li and only collapse on ul output

I created a foldable menu with a line like:

  • Parent
  • Parent 2
  • Parent 3
    • Subcategory

I have the following javascript

var config = { over: function() { $(this).children('ul').slideDown('slow'); }, timeout: 5, out: function() { } } $("ul.root-tags li").hoverIntent(config); $('ul.root-tags').mouseout(function() { $(this).children('li ul').each(function () { $(this).slideUp('slow'); }); }); 

Basically, I want to open subcategories when hovering the parent element, but only collapse the open subcategories in the output of the entire list, and not just the parent element. My current code does not do this. What changes do I need to make?

jsfiddle here http://jsfiddle.net/zkhVC/4/

+4
source share
3 answers

This should concern what you ask for:

 $('#head').mouseleave(function() { $(this).find('li ul').each(function () { $(this).stop().slideUp('slow'); }); }); $("ul li").mouseenter(function() { $(this).children('ul').stop().slideDown('slow'); });​ 

Fiddle

Here

Explanation

  • Do not use the hover event, because it will be fired over and over the element again and again. Instead, you want to use mouseenter .
  • Use mouseleave instead of mouseout :

The mouseleave event differs from mouseout in the way it handles the bubbling event. If mouseout used in this example, then when the mouse pointer is moved from an internal element, the handler will fire. This is usually an undesirable behavior. The mouseleave event mouseleave on the other hand, only calls its handler when the mouse leaves the element to which it is bound, and not the child. Thus, in this example, the handler starts when the mouse leaves the Outer element, but not the Internal element.

  • See how selectors work: you don't need the children function.
  • You want to use the stop function before invoking an animation to prevent animation buffering.
+3
source

It looks a little strange, but maybe we could explain it this way:

The mouseout () event seems to be dispatched to children from ul.root tags. Therefore, you should try the event.stopPropagation () method to avoid bubbles down .

 $('ul.root-tags').mouseout(function(e) { e.stopPropagation(); $(this).children('li ul').each(function () { $(this).slideUp('slow'); }); }); 

If this does not work right now, using e.target, you can find exactly those who call whom.

+1
source

Use jQuery mouseleave instead of mouseout :

 $('ul.root-tags').mouseleave(function() { $(this).find('ul').slideUp('slow'); }); $("ul.root-tags li").hover(function() { $(this).find('ul').slideDown('slow'); })​ 

See FIDDLE .

+1
source

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


All Articles