Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus on input field when div slides down

I have is a hidden div. When the button is clicked, the div slides down with an input field. How do I make this input field autofocus as soon as the div slides down? Thanks.

<input type="text" name="comment_field" id="comment_field" placeholder="Comment..." />

is what I have and is in a div

$("#status_comments_"+a).slideDown();
    $("#comment_field").focus();

I tried to use the above, but that didn't work.

like image 282
Elmer Almeida Avatar asked Sep 15 '12 19:09

Elmer Almeida


People also ask

Is autofocus attribute always set focus on first input field?

The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.

What is the html5 syntax to enable autofocus feature for an input field?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.


1 Answers

You can use slideDown's callback function which is executed when animation is complete.

$("#status_comments_"+a).slideDown(function(){
    $("#comment_field").focus();
});

Note that IDs must be unique, otherwise your ID selector only selects the first element with that specific ID. If input element is within the div tag you can also code:

$("#status_comments_"+a).slideDown(function(){
    $('input', this).focus();
});
like image 106
undefined Avatar answered Oct 07 '22 19:10

undefined