Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to set focus and cursor to input text using javascript in Chrome Console

This is in reference to this SO answer. I am trying the same on web.whatsapp.com (chrome) for its input search field. Here is my code to do it:

document.getElementsByClassName("input input-search")[0].focus()
document.getElementsByClassName("input input-search")[0].select()

Above does not work from chrome console.

Also the jQuery code:

$(".input-search").focus() 

does not work. What could be the reason that I don't see the cursor even after executing above methods?

like image 873
rahulserver Avatar asked Mar 27 '15 12:03

rahulserver


People also ask

Why focus () is not working?

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 do I make my cursor focus on input?

Use the setSelectionRange() method to move the cursor to the beginning of the input field. Call the focus() method on the input element. The focus method will move the cursor to the beginning of the element's value.

When focus () method is used in JavaScript?

JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.


1 Answers

I think this is not related to issue with class, id, javascript or jQuery. It's the way browser console works. The console gets focus after each command is run. So the focus will not work for other inputs from the console.

To test it, run this code in console.

setTimeout(function(){$(".input.input-search").focus()},5000);

After executing it immediately click anywhere on the page to take focus out of console. Now after 5 seconds, the focus will set on input.

like image 130
K K Avatar answered Oct 05 '22 05:10

K K