RS7
RS7

Reputation: 2361

Jquery - hide on click anywhere on document

I have a div that hides whenever you click outside of it but I'm having some trouble getting certain links inside the div to work (and not hide the div).

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

That is what I have for the whole clicking outside and closing event. Heres the thing: I have two types of links in my div, one regular link and another which is a javascript one. The regular one redirects OK but the javascript one doesn't do anything.

Could somebody help me out? Thanks.

EDIT:

Here are the bits of my code that might help out

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 page load):

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

Upvotes: 4

Views: 2758

Answers (2)

Felix Kling
Felix Kling

Reputation: 816780

This could be a problem with the live() click event handler. When you use live the event handler is actually attached to the document. So the event needs to bubble up to the document, but your click event handler on fav prevents bubbling up.

It works with delegate though:

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

Here, the event handler is added to fav.

DEMO

Upvotes: 2

Kenny Shen
Kenny Shen

Reputation: 4883

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

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

instead.

Upvotes: 0

Related Questions