A mouse-click on a focusable element raises events in the following order:
- mousedown
- focus
- mouseup
- click
So, here’s what’s happening:
mousedown
is raised by<a>
- your event handler attempts to focus the
<textarea>
- 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="https://stackoverflow.com/questions/8380759/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="https://stackoverflow.com/questions/8380759/javascript:void(0)" id="reply_msg">reply</a>
<textarea id="reply_message"></textarea>