How to remove focus from activeElement when changing tabs (onfocus / onblur)?

I am trying to remove focus from text input (jQuery Mobile) when a user switches tabs to the desktop. Although I can correctly identify the active element in the console below, I cannot edit any of its properties or remove its focus.

This is what I do:

// 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 am in the form and focus the text input, then switch to another tab and return to the tab with the form, event listen triggers and my still active input is correctly registered. However, this ... I cannot blur or change any properties of the elements.

Question :
How to remove focus from the active element on either window.onblur 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.

+6
source share
1 answer

Ok It works:

  window.onblur = function () { document.activeElement.blur(); }; 

So, it seemed that the blur was working fine, because if I had the activeElemnt console before and after my blur() call, it switched from INPUT to the BODY tag. That's right, in my body this class is set to FOOBAR . The problem for me was that the text element still retained focus, but I guess this is due to some handler inside jQuery Mobile.

The above solution works the other way around. I activeElement focus of the activeElement when the user switches the tab. Works.

+6
source

All Articles