Problems with jQuery.blur () and .focus () events
I have a form with multiple input fields. When the user clicks on an input field, a hidden div appears with some highlight for that field, they can then select an option and that value is set as the value of the field.
Currently, the way the div is hidden is when the user selects an option. This works great, but what if the user doesn't want to select an option, the div won't be removed. So my solution was to use a blur event for the input fields which would hide their div element. This way the user could fill out the form, see the hidden div, and hide it when they leave the field. This also works correctly.
The problem comes when they now want to click something from the div to be filled into the input. Since I even added blur, it even fires when the user tries to click an option in the div, effectively hiding the div a little second before the user clicks, rather than adding anything to the input field.
What would be the best way to solve this problem? I would like to have a blur event to hide the div, but there must be some kind of exception when the user wants to click inside the div that the blur event will not hide the div they are trying to click on.
Thanks for the help.
source to share
You can set a timeout on the blur event and immediately hide the "help div" only if the other is the focus input field.
Something like that:
$("#input1").focus(function() {
hideAllHelpers(); $("#helper1").show();
});
$("#input1").blur(function() {
window.setTimeout(function() { $("#helper1").hide(); },2000); });
});
$("#input2").focus(function() {
hideAllHelpers(); $("#helper2").show();
});
// etc...
Surely you could make this more versatile and it could use some fine tuning, but you get the idea ...
source to share
Onblur, set a timeout that waits seconds before hiding the corresponding one div
. Then, onclick, clear the timeout. Here's a basic example ...
// Namespace for timer
var myPage = {
timer: null
}
// Blur event for textbox
.blur(function() {
myPage.timer = setTimeout(function() {
// Hide the div
}, 1000);
});
// Click event for DIV
.click(function() {
clearTimeout(myPage.timer);
// Fill in the textbox
$(this).hide();
});
source to share