Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus() input element with jQuery, but the cursor doesn't appear

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.

like image 676
Zsolt Avatar asked Sep 16 '12 08:09

Zsolt


People also ask

Why focus is not working jQuery?

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);

How can input focus in jQuery?

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.

How do you set the input element to focus?

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.

How do you know if input is focused or not?

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.


1 Answers

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().
like image 179
David Thomas Avatar answered Sep 19 '22 17:09

David Thomas