I am at a loss here, never had a problem with this before.
I cannot get focus() to work at all in any browser. I’m using jquery and can’t even get it to work with standard javascript. I tried adding the timeout as well but still nothing. All I get in the alert is “undefined”.
Here is the input
<input type="text" name="SearchBox" id="SearchBox" class="SearchBox" />
and here is the jquery
$(document).ready(function(){
setTimeout(function(){
$("#SearchBox").focus();
}, 0);
alert($("*:focus").attr("id"));
});
I’ve stripped the page down to just the above in case something was interfering with it but still no success. It has to be something simple I’m missing!!!!
The searchbox will not get the focus until the document ready handler completes.
When you call
setTimeout, even if the timeout is set to zero, JavaScript will not handle that timeout until the current function is complete. This is because JS is single threaded.Calling
setTimeoutwith a timeout of zero is like saying “Here’s something I’d like you to do, once this function has completed.”Hence, the searchbox won’t get focus until after the
alertis called.An example