Firefox focus() sets the focus and blurs immediately

I have a <span class="numbers"> and this code for on Click, it creates a new <input class="number_input"> field and sets the focus on it:

            $('body').on('click','.numbers', function () {
                oldNumbersValue = $(this).html();
                var input = $('<input />', {'style':'font-size:30pt','type': 'number','class':'number_input', 'name': 'aname', 'value': oldNumbersValue});
                $(this).parent().append(input);
                input.focus();
            });

When the field loses the focus, it will be removed:

 $('body').on('blur', '.number_input',function () {
// do something
 $(this).remove();
});

This works in Chrome but not in Firefox! In Firefox it creates the field, sets the focus on it and loses it immediately!

Any solutions?

edit:

working in chorme/not working in ff fiddle: https://jsfiddle.net/v8hmpgv2/

Answers


The problem here is that (for a reason I'm not 100% sure of), Firefox is triggering the blur event on .number_input after the element has been appended to the document, but before your focus() actually calls.

You can see this happening in Firefox with this JSFiddle demo - note the order of the messages indicating when focus is set and lost on .number_input.

One way you could modify the code is to not use event delegation, and rather attach the blur handler directly to .number_input:

$('body').on('click', '.numbers', function (e) {
    oldNumbersValue = $(this).text();
    var input = $('<input />', {
        'style': 'font-size:30pt',
        'type': 'number',
        'class': 'number_input',
        'name': 'aname',
        'value': oldNumbersValue
    });
    $(this).parent().append(input);

    input.focus();
    input.blur(function(){
        $(this).remove();
    });
});

Here's a working JSFiddle to demonstrate. (Don't worry about any potential memory leakage due to constantly adding new event handlers - the jQuery docs indicate that .remove() should erase those each time.)

Hope this helps! Let me know if you have any questions.


Need Your Help

How to store object represented as Json string into Couchbase Lite?

java android json serialization couchbase-lite

I use Couchbase Lite in my Android app. In the app, I retrieve a bunch of Json objects from a server which I want to store locally. But I can't seem to find a way to do that without prior having to

Service Stack API and ThinkTecture.IdentityServer

claims-based-identity sts-securitytokenservice

Our team is developing our first web api and using Service Stack to expose our REST services. We know that we need security so these API endpoints are not available to the world. We also know that we