I'm trying to set the cursor into the input field. I'm using the functions focus() and select() but I don't know why it isn't working.
Any ideas?
<input type="text" id="test"> <p onmousedown="press()">Test</p> <script> function press() { let input = document.getElementById('test'); input.focus(); input.select(); } </script>
This was an interesting question that had me investigating a fair bit about the default behaviour of the mousedown
event and the differences between that and click
. Thanks!
The answer can actually be explicitly found in the Notes section of the MDN documentation for mousedown
:
If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement
So to fix, do exactly that. Note that I've slightly rewritten your code in order to do that, using addEventListener
to bind a JS function to the event, which then takes the event object as a parameter. (You could I think have done it your way using the global event
object - but it's a bad idea to use that. Using addEventListener
rather than inline JS that evaluates a string attribute and executes it as JS is also a much better, more modern approach.)
<input type="text" id="test"> <p id="button">Test</p> <script> button.addEventListener("mousedown", press); function press(event) { event.preventDefault(); let input = document.getElementById('test'); input.focus(); input.select(); } </script>
The reason I believe this is necessary is that the mousedown
event must have a default handler that causes the focus to go on that particular element - and this overrides your attempt to programatically place the focus elsewhere. I'm not 100% sure on that, but it's the most likely explanation that I can come up with.
Note that your original code works completely fine if you'd used the click
event rather than mousedown
- and this is more usual. The difference is that click
only fires when the user releases the mouse button after the initial press, whereas mousedown
fires instantly when the press happens. I can't see why this distinction would ever be important, and unless for some reason it's vital to you, I would recommend using click
instead, rather than the fix above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.