Search code examples
javascriptjquerymozilla

Mozilla focus after focus out


I am trying to make my code work targeting the 14 year unfixed bug in Mozzila which fails to focus back on the input. I have found in multiple places (most of the top 20 results in google mozilla focus not working) that setting a timeout for the focus will do the trick. However this is not working in any browser for me even tho it is the "official" (everyone says it worked for them) way to deal with this problem.

I have a simple focusout event targetting input with id test.

$(document).on('focusout', '#test', function()
{
    setTimeout(function()
    {
        $(this).focus();
    }, 500);
});

JsFiddle

Can someone tell me what I am doing wrong?


Solution

  • A function changes the scope, so this isn't what you think it is, inside the timeout this is actually the window, as that's the natural scope of window.setTimeout

    $(document).on('focusout', '#test', function() {
        var self = this;
        setTimeout(function() {
            $(self).focus();
        }, 500);
    });
    

    As a sidenote, why wouldn't you let the user focus anything else than the input, it seems like horrible UX.