Reputation: 4607
I am on the site www.RedBubble.com with the intent of using javascript to place the active cursor inside the search box at the top. I can get it to focus via code, a popout shows up. But I can't seem to get the cursor to show up inside the box after I get the focus working.
I run the following commands:
let searchbar = document.querySelector('input[name="query"]');
const focusEvent = new Event('focus');
const selectEvent = new Event('select');
searchbar.dispatchEvent(focusEvent);
searchbar.dispatchEvent(select);
This results in the search input box getting the focus but stubbornly the cursor does not blink inside the input field. If I manually click tab while on the page or I manually click in the box I get both the focus AND the cursor in the box. But I can't seem to re-create this programmatically.
I have also attempted to do this outside of the Developer Console just in case that was what was stealing the focus but I am getting the same result with or without the Developer Console active.
Upvotes: 0
Views: 1529
Reputation: 36426
The accepted answer here explains that dispatching an event does not generate the default action associated with a dispatched event.
You need to call the focus explicity.
let searchbar = document.querySelector('input[name="query"]');
searchbar.focus();
<input name="query"/>
Upvotes: 2
Reputation: 69
For a cursor focus try below code, it may help:
let searchbar = document.querySelector('input[name="query"]');
searchbar.focus();
Upvotes: 1