1

I have a notification dropdown similar to what stackoverflow has. So when the user request the notifications window I open and close my dropdown div using .show and .hide.

Meanwhile I also want to close it when the user clicks anywhere outside my dropdown div.

My approach was to do the following on my layout.cshtml :

$(document).on("click", onDocumentClick);

function onDocumentClick(event) {
    var target = $(event.target);
    if (!target.hasClass('nbr-notifications')) {
        if ($('#notifications-dropdown').css('display') === 'block') {
            $('#notifications-dropdown').hide();
        }
    }
}

My question and concern is : Is this the best way to do it? From the performance perspective? Since I am handling all clicks on my document everytime.

user2779312
  • 661
  • 2
  • 9
  • 23
  • Solution can be found here : http://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it – user2779312 Feb 28 '14 at 22:08

2 Answers2

0

Couldn't you use this if you are not sure where the element would be?

    $('body').on("click",".nbr-notifications", onClick)
  .on('blur','.nbr-notifications',closeNotifications);

function onClick(event) {        

        if ($('#notifications-dropdown').css('display') === 'block') {
            $('#notifications-dropdown').hide();

    }
}

function closeNotifications()
{
//close it
}

Here only responding to clicks on elements with the class 'nbr-notifications' rather than hooking event handler for all clicks and check if the target is the required one.

Ananthan Unni
  • 1,304
  • 9
  • 23
  • I tried but the event does not fire for my div. I tried with an input text box and it works. So somehow that code is not applicable to a div. Thanks – user2779312 Feb 27 '14 at 21:47
0

If you want the notification to disappear after it loses focus why not just bind a focusout event specifically to that element instead of click to the entire document.

http://api.jquery.com/focusout/

$('.nbr-notifications').on('focusout',function(){ 
    //close functionality here.  something like: $(this).hide();
});
FGhilardi
  • 337
  • 1
  • 7
  • I applied it to the #notifications-dropdown and I'm not being able to put it to work. It does not fire. when I click outside my ``#notifications-dropdown`` div nothing happens. Thanks – user2779312 Feb 27 '14 at 21:18