How could this be achieved via jQuery?
When the user clicks on any input in the form, it is focussed. When a user clicks out of the form from any input it is blurred, but, the blur does not get triggered between tabbing between inputs in the form itself.
For something like this, we're looking at this basic structure:
<form>
<input ... />
<input ... />
<input ... />
</form>
So again, lets say I click on any input in the form, we know the form is focused. Next, when the user clicks off of ANY input the blur is triggered ONLY if we clicked outside the form.
I've asked this question previously and kindly received input on how to achieve the blurring effect when the last input field in the form was blurred, but not from any element in the input list.
Thanks, Mark Anderson
The sequence of events when you're tabbing between inputs:
Click on input1: input1 focus
Clickb on input2: input1 blur
input2 focus
Click outside: input2 blur
When an input loses focus you need to check if some other element within the form gains focus. Or you can simply check if the active element is still within the form:
$('form').on('focusout', function(event) {
setTimeout(function() {
if (!event.delegateTarget.contains(document.activeElement)) {
console.log('Form blur');
}
}, 0);
});
JSFiddle
Note that form doesn't blur on submit, so you may need to add a submit handler if you want to do the same thing on blur and submit.
Also note the use of setTimeout
, it's required because blur
and focusout
events are emitted when an element is about to lose focus, but haven't lost it yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With