Phillip Senn
Phillip Senn

Reputation: 47663

jQuery window bind focus

I have this:

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

But it was causing "too much recursion". So I changed it to this:

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

But that of course only works the first time the window gets the focus.

Q: How do I write it so that every time the user toggles to another screen and back to this one, then myName has the focus?

Upvotes: 3

Views: 3379

Answers (2)

stecb
stecb

Reputation: 14766

Could something like this work?

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

winFocus(); //first time

$(window).bind("blur",winFocus);

Upvotes: 1

user113716
user113716

Reputation: 322612

Prevent the event from bubbling by assigning a handler to the inputs that calls e.stopPropagation():

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

or just have your window function check the e.target to see 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. This is mandatory.

Upvotes: 4

Related Questions