What are some reasons for jquery .focus() not working?
You need to either put the code below the HTML or load if using the document load event:
<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
$("#goal-input").focus();
});
</script>
Update:
Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:
if (goal) {
step1.fadeOut('fast', function() {
step1.hide();
step2.fadeIn('fast', function() {
$("#name").focus();
});
});
}
I had problems triggering focus on an element (a form input) that was transitioning into the page. I found it was fixable by invoking the focus event from inside a setTimeout with no delay on it. As I understand it (from, eg. this answer), this delays the function until the current execution queue finishes, so in this case it delays the focus event until the transition has completed.
setTimeout(function(){
$('#goal-input').focus();
});