Hung up the processor of a click on the button displaying, hiding the additional block with the list. Everything is working.

$('.button').on('click', function (event) { event.preventDefault(); var ul = $(this).next('.ul'); ul.toggle(); }); 

I decided to do it in such a way that the additional block would be hidden when clicking outside of it.

 $(document).on('click', function (event) { var ul = $('.ul'); if (!ul.is(event.target) && ul.has(event.target).length === 0 && ul.is(':visible')) { ul.hide(); } }); 

After that the toggle stopped working. Already tried different combinations of code from various sites, but nothing helps. Tell me, please, where is the error.

1 answer 1

Your click handler on the document is executed when the button is clicked To prevent this, use event.stopPropagation .

 $('.button').on('click', function (event) { event.preventDefault(); event.stopPropagation(); // !!! var ul = $(this).next('.ul'); ul.toggle(); }); 

Explanation

First, a click handler is executed. It makes .ul visible. Then (if there is no event.stopPropagation ), a click handler on the document is executed. At this moment, the .ul is visible, and the event.target (button) is outside .ul . And .ul is hiding again.

  • Thanks, helped! Only it is not clear, since the handler going up to the document should not fall into the if condition and close the block. - Eugene
  • @ Eugene In the handler for the document, you do not check the event.target for .button . - Igor
  • Igor, I probably misunderstand something. I thought that the hide in document would work only if the if condition was fully met. And the condition seems to be: a click should not be on the block And should not be on its descendants And the block should be expanded. Or can hide work without a condition? - Eugene
  • @ Yevgeny, it seems to me, when I click on the button and .ul all conditions are satisfied. Now I will look fidl. - Igor
  • @ Eugene Yes. First, a click handler is executed. It makes .ul visible. Then (if there is no event.stopPropagation ), a click handler on the document is executed. At this moment, the .ul is visible, and the event.target (button) is outside .ul . - Igor