I'm trying to remove focus from a (jQuery Mobile) text input when a user switches tabs on desktop. While I can correctly identify the activeElement in the below console, I cannot edit any of its properties or remove its focus.
This is what I'm doing:
// inside some init method
window.onfocus = function () {
// triggers
console.log(document.activeElement);
if (document.activeElement.tagName !== "BODY") {
console.log("clear focus");
document.activeElement.blur();
document.activeElement.className = "FOOBAR";
}
};
When I'm on a form and focus a text input, then switch to another tab and go back to the tab with the form, the event listener triggers and my still active input is correctly logged. However that's it... I can't blur or edit any of the elements properties.
Question:
How do I correctly remove focus from the active element either on window.onfocus
or window.onblur
?
Thanks!
PS: it also does not work with jQuery:
$(window).on("focus", function () {
$(document.activeElement).blur();
});
and I'm looking for a JavaScript only solution.
EDIT:document.activeElement.blur()
works fine from the console, but not from my listener.
The blur() method removes focus from an element.
Use the blur() method to remove the focus from an element, e.g. input. blur() . If you need to remove the focus from the currently active element without selecting it, call the blur method on the activeElement property - document.
If you want to remove the focus around a button, you can use the CSS outline property. You need to set the “none” value of the outline property.
Definition and Usage Tip: The onblur event is the opposite of the onfocus event. Tip: The onblur event is similar to the onfocusout event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you could use the onfocusout event.
Ok. This works:
window.onblur = function () {
document.activeElement.blur();
};
So it seemed the blur worked fine, because if I console activeElemnt
before and after my call to blur()
it switched from an INPUT to the BODY tag. Correctly, my body has it's class set to FOOBAR
. Problem for me was that the text element still retained focus, but I assume this is due to some handler inside jQuery Mobile.
The above solution works the other way around. I remove focus of the activeElement
when the user switches a tab. Works.
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