0

Possible Duplicate:
How to detect a click outside an element?

Let's say I create an HTML/javascript widget. Let's say that when rendered, the widget sits atop, beside or near any number of other html elements.

I want to be able to make my widget to modify itself when the user clicks anywhere but inside the widget itself.

Can this be done?

Community
  • 1
  • 1
Craig Wilcox
  • 1,577
  • 1
  • 12
  • 23

1 Answers1

2

Bind an event to the document, then test the click event for an id.

http://jsfiddle.net/AgNmt/

$(document).on('click', function (event) {
    var $element = $(event.target);

    if ($element.attr('id') === 'mywidget') {
        // do nothing
    } else {
        alert('you have clicked outside the widget!');
    }
});​
Nate
  • 4,718
  • 2
  • 25
  • 26