1

I took the following code from a question here on StackOverflow:

$('body').click(function(event) {
    if (!$(event.target).closest('#myDiv').length) {
        $('#myDiv').hide();
    };
});

The only problem is that on Firefox (on Safari works) doesn't work. Why is that? How should I change it to make it compatible with Firefox?

Community
  • 1
  • 1
Shoe
  • 74,840
  • 36
  • 166
  • 272

2 Answers2

1

This is an old trick copied from Which HTML element is the target of the event?

$(function() {
    $('body').click(function(event) {

        var targ;
        if (event.target) targ = event.target;
        else if (event.srcElement) targ = event.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
           targ = targ.parentNode;

        if (!$(targ).closest('#myDiv').length) {
            $('#myDiv').hide();
        };
    });

});

DEMO Clicking outside the div will hied the div !$(targ).closest('#myDiv').length

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • It works on the demo but on my website it doesn't work. I'm using jQuery 1.7.2 with the jQuery UI 1.8.16. The only thing different from that code is that before I set `$("#myDiv").draggable();`. Why doesn't it work? – Shoe May 10 '12 at 23:38
0

Try this and let me know if it did not worked

$('body').click(function(event) {
    target = (window.event) ? window.event.srcElement /* for IE */ : event.target;
    if (!($(target).closest('#myDiv').length>0)) {
        $('#myDiv').hide();
    };
});
Imdad
  • 5,942
  • 4
  • 33
  • 53