JQuery plugin: catch events for clicking/tabbing into and out of an input box
Posted
by poswald
on Stack Overflow
See other posts from Stack Overflow
or by poswald
Published on 2010-06-14T05:21:53Z
Indexed on
2010/06/14
5:22 UTC
Read the original article
Hit count: 263
I'm creating a Javascript JQuery Timepicker control plugin (which I hope to open source soon) and I would like some advice on how to best register the events in the cleanest way.
The control will attach to an <input>
box and provide a graphical way to enter times of day ( 14:25, 2:45 AM, etc...). It does this by adding a <div>
after the input box.
What I want is to bind an openControl()
function that fires when the input is clicked or tabbed to, and a closeControl()
function that fires when the input box is tabbed away from or deselected but not if the control itself is clicked. That is, I don't want to close the control if you're clicking inside of the control's <input>
or the <div>
.
Here's what I have been doing to try to get there:
/* Close the control attached to the passed inputNode */
function closeContainer(inputNode, options) {
$input = $(inputNode);
if ( $input.next().is(':visible')) {
$input.next().hide(options.hideAnim, options.hideOptions, options.hideDuration, options.onHide );
}
}
/* Open the control */
function openContainer(node, options) {
$input = $(node);
$input.next().show(options.showAnim, options.showOptions, options.showDuration, options.onShow );
// bind a click handler for closing the contol
$("body").bind('click', function (e) {
$('.time-control').each( function () {
$input = $(this).prev();
// only close if click is outside of the control or the input box
if (jQuery.contains(this, e.target) || ($input.get(0) === e.target) ) {
closeContainer($input, options);
setTime($input, $input.next(), options);
} else {
closeContainer($input, options);
}
});
});
}
I want to add support for tabbing in/out but I feel like this approach is wrong. Focus/Blur wasn't working well because the blur event fires if you click on the control. Should I be using those events but filtering out if they are inside the control's div?
Anyone have a better way of doing this? Thanks!
© Stack Overflow or respective owner