leszek.hanusz
leszek.hanusz

Reputation: 5317

JQuery detect lost focus to another element on the page but not lost focus of the browser

Using jquery I am detecting the lost focus on a textbox using the blur event.

I am then hiding the textbox and replacing it with a label containing the text entered.

My problem is that this event is fired even when the browser lose the focus (which under linux/firefox happen even when pressing the "Alt Gr" key to insert a special character like the arobase @ in the textbox)

Is it possible to detect a focus lost only to another element on the page ?

Edit: add example jsfiddle http://jsfiddle.net/XMp5n/

Relevant code:

$('#emailField').blur(function() {
    $('#emailField').hide();
    $('#emailFieldLabel').show();
});

Upvotes: 1

Views: 1379

Answers (1)

Nunners
Nunners

Reputation: 3047

The functionality of your JSFiddle appears to work exactly as it should. You mentioned that in linux/firefox using the Alt key causes the item to lose focus, to correct this you may need to add a global variable and change this in the 'document.onkeydown' function :

        var isAlt = false;

        document.onkeydown = function(event) {
            if (event.keyCode == 18) {
                isAlt = true;
            } else {
                isAlt = false;
            }
        }

        $('#emailField').blur(function() {
            if (isAlt) {
                $('#emailField').hide();
                $('#emailFieldLabel').show();
            }
        });

Check here for other Javascript keycodes.

Upvotes: 1

Related Questions