Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid element blur handler when window blur invoked (browser loses focus)

To expound upon the question:

I've got an element which when clicked receives a sub-element. That sub-element is given a blur handler.

What I would like is for that handler not to be invoked when the browser loses focus (on window blur).

Towards that goal I've attempted several tacks, this being my current effort:

function clicked() {
    // generate a child element
    ...
    field = $(this).children(":first");
    $(window).blur(function () {
        field.unbind("blur");
    });
    $(window).focus(function () {
        field.focus();
        field.blur(function () {
            save(this);
        });
    });
    field.blur(function () {
        save(this);
    });
}

This doesn't work. What appears to be occurring is that when the browser loses focus, the field is losing focus first.

like image 466
Michael Plotke Avatar asked Oct 31 '13 07:10

Michael Plotke


People also ask

How can you prevent elements from losing focus?

You need to subscribe to the blur event of the textbox and reinstate focus with a small timeout: $('#txtSearch'). blur(function (event) { setTimeout(function () { $("#txtSearch"). focus(); }, 20); });

Which of the following events get triggered with a control or element loses focus?

The onblur event occurs when an object loses focus.

What is focus blur?

Events focus/blur The focus event is called on focusing, and blur – when the element loses the focus. Let's use them for validation of an input field. In the example below: The blur handler checks if the field has an email entered, and if not – shows an error.

What is blur () method?

Definition and Usage The blur event occurs when an element loses focus. The blur() method triggers the blur event, or attaches a function to run when a blur event occurs. Tip: This method is often used together with the focus() method.


1 Answers

Nice question!

This is possible, and fairly straightforward.

field.blur(function() {
    if(document.activeElement !== this) {
         // this is a blur that isn't a window blur
    }
});

JSFiddle

Or in vanilla JS:

field.addEventListener('blur', function() {
    if(document.activeElement !== this) {
         // this is a blur that isn't a window blur
    }
});

Edit: Though your answer deals with the browser losing focus, know that Firefox has unusal behavior (bug?) when returning to focus. If you have a input focused, and then unfocus the window, the element's blur is triggered (which is what the question was about). If you return to something other than the input, the blur event is fired a second time.

like image 94
Paul Draper Avatar answered Nov 03 '22 10:11

Paul Draper