JQuery Window Binding Window

I have it:

$(window).bind("focus", function() {
    $('input[name=myName]').focus();
});

But that caused "too much recursion." So I changed this to the following:

$(window).one("focus", function() {
    $('input[name=myName]').focus();
});

But this, of course, only works on the first click of a window.

Q: How can I write so that every time the user switches to another screen and returns to this, then myName has focus?

+3
source share
2 answers

Prevent the event bubble by assigning a handler to the inputs calling e.stopPropagation():

$(window).bind("focus", function() {
    $('input[name="myName"]').focus();
});
$('input[name="myName"]').focus(function(e) {
    e.stopPropagation();
});

or just try the windowcheck function e.targetto find out where the event came from:

$(window).bind("focus", function(e) {
    if( e.target === window ) {
        $('input[name="myName"]').focus();
    }
});

EDIT: Added quotation marks around the value part of the attribute selector. It is necessary.

+4
source

Can something like this work?

function winFocus(){
    $(window).one("focus", function() {
        $('input[name="myName"]').focus();
    });
}

winFocus(); //first time

$(window).bind("blur",winFocus);
+1
source

All Articles