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 the focus()
call doesn't work.
The reason that's not working is simply because it's not stealing focus from the dev console. If you run the following code in your console and then quickly click in your browser window after, you will see it focus the search box: setTimeout(function() { $('input[name="q"]'). focus() }, 3000);
Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.
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();
});
JS Fiddle demo.
And:
$(".placeholder_input").click(function() {
$(this).children(":first").focus();
});
JS Fiddle demo.
References:
click()
.mouseup()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With