Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How not to lose focus on a login page

I have a simple login form with 2 input fields: "username" and "password". "username" field is focused by default. The problem is that when user clicks outside "username" or "password" fields, the focus is gone (it is neither on "username" nor on "password" fields"). How can I force the focus to be on these 2 fields only ?

In my case, this is a really annoying behavior, so I really want to do this :)

Can I do something like:

$("*").focus(function() {
    if (!$(this).hasClass("my_inputs_class")) {
        // How to stop the focusing process here ?
    }
});

?

like image 504
Misha Moroshko Avatar asked Jun 10 '10 14:06

Misha Moroshko


2 Answers

It sounds like you always want one of your inputs to be focused, fair enough. The way I would do this is to bind each of your inputs blur() events so that if it occurs, it goes to the next element.

Here's the markup:

<body>
<form method="POST" action=".">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <input type="submit" name="submit" />
</form>
</body>

And here's the jQuery:

$(document).ready(function() {
    // what are the named fields the user may focus on?
    var allowed = ['username', 'password', 'submit'];
    $.each(allowed, function(i, val) {
        var next = (i + 1) % allowed.length;
        $('input[name='+val+']').bind('blur', function(){
            $('input[name='+allowed[next]+']').focus();
        });
    });
    $('input[name='+allowed[0]+']').focus();
});
like image 152
artlung Avatar answered Sep 27 '22 16:09

artlung


You could use javascript to set the focus on focusout, but you really shoudn't. Forcing focus on those fields would break the normal interaction of the page. It would mean a user couldn't do something as simple as clicking on a link on the page, because focus would always be on those inputs.

Please don't do it :)

like image 39
Bala Clark Avatar answered Sep 27 '22 15:09

Bala Clark