focus() input element with jQuery, but the cursor doesn't appear
46,158
Solution 1
It doesn't work with the mousedown
method; it does, though, work with the mouseup()
and click()
methods:
$(".placeholder_input").mouseup(function() {
$(this).children(":first").focus();
});
And:
$(".placeholder_input").click(function() {
$(this).children(":first").focus();
});
References:
Solution 2
if you insist on using mousedown
, delay the focus till the next tick
$(".placeholder_input").mousedown(function() {
var $el = $(this).children(":first");
setTimeout(function() {
$el.focus();
}, 0);
});
Related videos on Youtube
Comments
-
Zsolt over 2 years
I want to focus an input element when a div is clicked.
My HTML looks like this:
<div class="placeholder_input"> <input type="text" id="username" maxlength="100" /> <div class="placeholder_container"> <div class="placeholder">username</div> </div> </div>
And my script is:
$("#username").focus(function() { $(this).next().hide(); }); $(".placeholder_input").mousedown(function() { $(this).children(":first").focus(); });
When I click into the textbox, the placeholder text disappears correctly, but the blinking cursor doesn't show in the textbox. (and I can't type any text into the textbox)
Inside of the
mousedown
event handler, the$(this).children(":first")
expression selects the correct input element, so I have no idea why thefocus()
call doesn't work.