JQuery - hide when clicked anywhere in the document

I have a div that hides whenever you click on it, but I am having problems getting certain links inside the div to work (and not hide the div).

$(document).click(function() { fav.hide(); }); theDiv.click(function(e) { e.stopPropagation(); }); 

This is what I have for all clicking outside and closing the event. Here's what: I have two types of links in my div, one regular link and the other which is javascript. Normal redirects OK, but javascript does nothing.

Can anyone help me out? Thanks.

EDIT:

Here are snippets of my code that might help

 var fav = $('#favorites'); // Open & close button $('#favorites_a').click(function(e) { e.stopPropagation(); e.preventDefault(); fav.toggle(); }); $('a.c',fav).live('click', function(e) { alert('hey'); }); $(document).click(function() { fav.hide(); }); fav.click(function(e) { e.stopPropagation(); }); 

HTML (built after loading the page):

 <div id="favorites"> <div class="wrap"> <ul><li><a href="/abc" class="p">A</a><a href="#" class="c">B</a></li></ul> </div> </div> 
+4
source share
2 answers

This may be a problem with the live() event handler. When you use live , the event handler is actually attached to the document. Thus, the event needs to tint the document, but the click event handler on fav prevents the appearance of bubbles.

It works with delegate though:

 fav.delegate('a.c', 'click', function(e) { alert('hey'); }); 

Here the event handler is added to fav .

Demo

+2
source

I think your fav code is preventing the "B" link from working. Instead of .live () try:

 $('a.c').click(function() { ... }); 

instead.

0
source

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


All Articles