sangoko
sangoko

Reputation: 351

focus() method doesn't work while manually focusing with the mouse or tab key does

I try to focus an element of an email field in this webpage, with the following code:

document.querySelector("#user_email").focus();

While manual focusing with either clicking on the field with the mouse or using tab works, the focus() method fails to create the focus, as it seems both from the fact the CSS doesn't change, and the console returns "undefined".

As a newcomer, I ask why?

Upvotes: 0

Views: 169

Answers (3)

Win
Win

Reputation: 5584

Digital Ocean's input boxes are focusing fine for me. The undefined basically means that nothing is returned from your expression. For example if you type var a = 123 it'll still say undefined. Also there is no special CSS styling on these input boxes. You might be getting confused with the ones in their control panel.

UPDATE: OP was getting confused with Chromes default input styling.

Upvotes: 0

marzelin
marzelin

Reputation: 11600

When you're calling focus() from console, focusing won't happen immediately - you have to go back to the site (close console). When you go back from console to a website by clicking on a website, focusing won't happen. Close console using shortcuts or use setTimeout to delay focusing to give you time to go back to the website.

Upvotes: 1

Pierre Granger
Pierre Granger

Reputation: 2012

You should try with document.getElementById('user_email').

document.getElementById('user_email').focus() ;
<input id="user_email">

Upvotes: 0

Related Questions