dngoo dngoo - 1 month ago 5
jQuery Question

What are some reasons for jquery .focus() not working?

Some thoughts are that the ELEMENT_ID.focus() is inside divs that are hidden at certain times.

This should be an easy problem to solve -- but I'm struggling :(

***code works fine -- the text field isn't being focused on upon page loading up.

STEP1 [SOLVED]
JAVASCRIPT:

$("#goal-input").focus();

$('#goal-input').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13') {
etc, etc, etc
}


HTML

<input type="text" id="goal-input" name="goal" />


[STEP2]
JAVASCRIPT:

if (goal) {
step1.fadeOut('fast', function() {
step1.hide();
step2.fadeIn('fast');

etc, etc


HTML:

<div id="step-2">
<div class="notifications">
</div>
<input type="text" id="name" name="name" placeholder="Name" />
<script type="text/javascript">
$(function(){
$("#name").focus();
});
</script>


Why doesn't step 2 work? :(

Answer

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();
          });
      });
}
Comments