How To Set Focus With JavaScript

Sharing buttons:

in this lesson we're going to look at

how to focus on an input element using

JavaScript so to focus on an input

element basically means to set the next

user input to go into particular input

field so for example I've got two input

elements set up here input element one

and two and simply clicking on one means

that I'm setting the focus on input

element one so we can do that

programmatically with JavaScript and

there is a focus function but calling it

directly in the console

doesn't actually do anything and this is

one of those weird quirks of using

javascript while consoles open so what

we'll actually do is trigger that focus

function based on when the focus one

unfocused two buttons are clicked

so now when I click on either the focus

1 or focus 2 buttons you can see that

that focus function is called on the

relevant HTML element and I'm able to

start typing some text into that input

field and whoops and for the second

focus button I've actually set up the

function call on input element 1 again

so let's fix that so you can see when I

click on the focus 2 button now I'm able

to type some text into that second box

and clicking focus 1 again takes me back

to the first input element so that's all

you really need to know about setting

the focus on an input element but there

are some times when you might want to

lose that focus in other words to use

JavaScript to actually remove focus from

that particular element and we can do

that with a similar command called blur

so now let's say input elements who has

focus if I take the blur to button you

can see that focus is removed from

element 2 and it's not actually

reapplied to any other elements ie

element 1 we can do the same thing for

element 1 as well so that might be

useful when you want to control which

element has focus by adding and removing

it using the focus and blur functions