JQuery.focus () callback not working

I just don’t understand why this callback method. Focus not working?

$('a.focus').click(function(){
    $('form input:first').focus(function(){
        console.log('done focus');         
    });
});  

Live demo: http://jsfiddle.net/SHxbj/

Is everything I am doing wrong here?

+3
source share
4 answers

Why not just do this:

$('a.focus').click(function() {
    $('form input:first').focus();
});
$('form input:first').focus(function() {
    console.log('focused');
});​

The first fragment binds a click on the link to focus the cursor in the input field, and the second fragment binds a focus event in the input field and sends a message to the console.

JsFiddle example .

+8
source
$('form input:first').focus(function(){
    console.log('done focus');         
});

, . , , , , , . , .

, :

$('form input:first').focus();
console.log('done focus');
+6

Your code associates a callback with an event focus, but does not actually focus the element. You can save it as a callback and manually focus the element, or just start it after focus:

Edited by; thanks @ GNi33 for pointing out the re-binding!

var $input = $('form input:first');
$input.focus(function(){
    console.log('done focus');         
});

$('a.focus').click(function(){
    $input.focus();
});  
0
source
$('a.focus').click(function(){
    $('form input:first').focus(function(){
        console.log('done focus');         
    }).focus();
});  

Fiddle

0
source

All Articles