1

I'm building a widget akin to a datepicker, but I can't figure out how to make it disappear when when either (a) the user tabs out of the input box, or (b) clicks outside both the widget and input.

It's easy to bind a blur event to the input box, but the problem is that it will get triggered when you click on the widget, and there doesn't appear to be a reliable way to determine which element the focus was changed to from inside the blur event.

Closing the widget when the user clicks outside of the input is a bit sketchy too, but it's doable:

$('body').on('click', function(e) {
    if(e.target != self.element[0] && e.target != self.clock[0] && !$.contains(self.clock[0], e.target)) {
        self.clock.hide();
    }
});

But I wouldn't need that if I could figure out how to handle the blur event properly (which may also be triggered by tabbing outside of the element).

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • Chrome has a `e.relatedTarget` property which gives the element the focus has switched to, but only if its another input element. It will be null if they click on one if the `` that comprise my widget – mpen Oct 01 '13 at 21:11
  • 1
    I believe mousedown fires before blur. You might want to try listening for that instead of click. – rojoca Oct 01 '13 at 21:40
  • @rojoca: That actually seems to work extremely well... – mpen Oct 01 '13 at 22:13

1 Answers1

1

Turns out the solution is actually quite simple. Thanks to rojoca's suggestion, I came up with this:

this.timepicker.on('mousedown', function(e) {
    return false;
});
this.element.on('blur', function(e) {
    self._parseInput();
    self._refreshInput();
    self._close();
});

The mousedown event fires first, and by returning false it prevents the blur event from triggering when clicking on the widget. Everything else (clicking outside the widget and input box, or tabbing away) causes a blur, which closes the widget as desired.

Further, it had the unintended by pleasant side-effect of keeping your cursor inside the textbox while interacting with the widget.

mpen
  • 272,448
  • 266
  • 850
  • 1,236