views:

105

answers:

3

hello, i have a little problem with JQuery.

Well, i have a and i want to hide this div when an user click in a zone that is not in the like the "notifications" behavior in facebook.

The solution that i found is to use jQuery.live() method but i think there is a better way to do it.

Thank you.

+4  A: 

Assuming:

<div class="notification">You have 3 new messages</div>

use:

$(document).click(function(evt) {
  if ($(this).closest("div.notification").length == 0) {
    $("div.notification").fadeOut();
  }
});

Basically this listens to all clicks. If one is received that doesn't occur inside a notification div it fades them out.

cletus
What happens if the click is made on `div.notification` itself?
rahul
@rahul had to make a slight correction for that case (`parents()` to `closest()`) but basically it won't fade them out if clicked on.
cletus
+1 for you and deleted my answer.
rahul
A: 

Thank you for your answer but, the :

$(this).closest("div.notification").length == 0) 

always return me 0 (even if i click in the div), so the div is always hidden.

This is my code :

$(document).click(function(evt) {
        if ($(this).closest("div#show_notif").length==0)
            $("div#show_notif").fadeOut();
});

And the html :

<div id="click_show_notif" onclick="$('div#show_notif').show();"><img src="http://'+STATIC_SERVER+'/images/notif.png" /><div id="show_notif"></div>

There is something that i forgot ?

hann
A: 

Try this :

$("#click_show_notif").live('click',function(e) {
    $("#show_notif").show();
    return false;
});

$('body').live('click',function(e) {
    if ($(this).closest("div#show_notif").length==0) {
        $("div#show_notif").hide();
    }
});
MikeBrant