Keith John Hutchison
Keith John Hutchison

Reputation: 5277

Setting the focus on a element that was hidden

I'm looking for a way to trigger a focus event that occurs after an element is recognised as focusable within the DOM.

I'm showing form elements based on previous input. That works. Then I want to set the focus for user input.

The following function fails to work unless I set a break point on the line with setTimeout. I've tried using a function callback which also failed.

function triggerFocus(id,timeout){
    console.log('triggerFocus') ;
    console.log(id) ;
    /* the following works if a breakpoint is set*/
    setTimeout( function() { $( id ).focus() }, timeout ) ;
}

/* code used to show the elements from another function */
if ( $('#first').val() == '') {
    $('#firstRow').show() ;
    $('#middleRow').show() ;
    $('#lastRow').show() ;
    $('#emailRow').show() ;    
    triggerFocus($('#first'),100) ;    
} else {
    $('#docket').blur(docketBlur) ;
    $('#firstRow').show() ;
    $('#docketRow').show() ;
    triggerFocus($('#docket'),100) ;    
}

An example showing how to achieve this using a tab keyCode is at http://jsfiddle.net/pvrSU/ I discovered that the other element must be focusable before the blur event is fired.

Upvotes: 0

Views: 884

Answers (1)

CD..
CD..

Reputation: 74096

The show() function has a complete callback, you can use it in this case:

$('#emailRow').show(400, function(){
 .
 .
 .
})

Example: http://jsfiddle.net/ar5wS/

Upvotes: 1

Related Questions