Why isn't this textarea focusing with .focus()?

A mouse-click on a focusable element raises events in the following order:

  1. mousedown
  2. focus
  3. mouseup
  4. click

So, here's what's happening:

  1. mousedown is raised by <a>
  2. your event handler attempts to focus the <textarea>
  3. the default event behavior of mousedown tries to focus <a> (which takes focus from the <textarea>)

Here's a demo illustrating this behavior:

$("a,textarea").on("mousedown mouseup click focus blur", function(e) {
  console.log("%s: %s", this.tagName, e.type);
})
$("a").mousedown(function(e) {
  $("textarea").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)">reply</a>
<textarea></textarea>

So, how do we get around this?

Use event.preventDefault() to suppress mousedown's default behavior:

$(document).on("mousedown", "#reply_msg", function(e) {
    e.preventDefault();
    $(this).hide();
    $("#reply_message").show().focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)" id="reply_msg">reply</a>
<textarea id="reply_message"></textarea>


Focusing on something from an event handler that, itself, grants focus, is always problematic. The general solution is to set focus after a timeout:

setTimeout(function() {
  $('#reply_message').focus();
}, 0);

That lets the browser do its thing, and then you come back and yank focus over to where you want it.


Could it be the same issue as this? jQuery Textarea focus

Try calling .focus() after .show() has completed.

$('#reply_msg').live('mousedown', function() {
    $(this).hide();
    $('#reply_holder').show("fast", function(){
        $('#reply_message').focus();
    }); 
});