views:

27

answers:

1

I've written a simple jQuery (1.4.2) UI (1.8) widget that embeds a jQuery UI datepicker. I'd like to detect when a user clicks outside my widget, in which case it should automatically hide itself. My code looks roughly like this:

var self = this;
$(document).bind("click.mywidget": function(event) {
    var target = event.target;
    if (!self.container.has(target).length && target != self.container.get(0)) {
        self.hide();
    }
});

The problem comes when clicking on a date or month prev/next button in the datepicker. For some reason, even though Firebug shows those elements as being descendants of my container, the has() check fails for them.

What is happening, and how might I fix this?

A: 

After digging through the datepicker source a bit, I realized what was going on. Apparently whenever you click on a date, or cycle through months, it empties the entire div and re-creates it.

Since the picker is further down in the DOM, it handles the click event first. By the time the document handler gets called, the target element is no longer in the DOM, and is therefore no longer a descendant of the container.

My hasty hack was to check the target's more direct parents, to see whether any of them is a datepicker table or header. Since this widget is thus far my only use of datepicker, I can assume that a click on such an element should not count as a click outside the container.

I'll update this answer once I come up with a real solution.

DNS