3

I'm using a color-picker which should be hidden when a click is made anywhere outside it. The problem is, it disappears even when the click is made inside the picker.

$('body :not(#picker)').click(function() {
    $('#picker').fadeOut();
});

I tried this, but it would show the picker and hide it immediately. Does anybody have a suggestion?

Majid
  • 13,853
  • 15
  • 77
  • 113
cili
  • 1,037
  • 2
  • 19
  • 34

2 Answers2

22

Try using event.target to obtain the element that was clicked:

$("body").click(function(event) {
    if (event.target.id != "picker") {
        $("#picker").fadeOut();
    }
});
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
3
$("body").click(function(e) {
    if ($(e.target).attr('id') == 'picker') {
        return;
    } else {
        $('#picker').fadeOut();
    }
});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164