I am listening for a blur event on a form input. Right now, the event immediately gets triggered when the mouse is pressed down outside of the control. I need to be able to detect when the mouse is completely clicked outside of the input (mouse down and then mouse up).
Is there already an event type that I can listen to that will handle this? If not, what is the best way to handle this type of event?
I'd say no, there aren't any event of that type. And I don't think there is a perfect way to handle that
I'll try to handle it this way
adding a mousedown
handler to the document when the form get the focus. It will set a global variable to 1.
event.target
). If it's the case, let 1, else set it to 0.The mousedown
handler will have event.preventDefault;
and return false;
. This may cause some trouble to your others eventHandlers. To avoid such trouble, I'll try to capture the events that could be damaged on the capturing phase, not the bubbling one.
mouseup
handler to the document when the form get the focus. In it, test if the variable has a value of 0. if yes, then do the blur job and remove the two special handlers.But this might have some weakness (especially if the user leaves the window while the mouse is pressed).
I hope this is clear, I'll try to post a fiddle asap.
EDIT: Here is the fiddle. However note that I force the focus on the form and it works only one.I did so because it looks like the form never get focused otherwise (probably linked to the way jsfiddle handle events). But in theory that should work without the $("form").focus();
line.
As a side note, i used jQuery for some shortands I'll try to remove the calls if needed.