focus method
The focus
method sets focus
on an element (most often an input).
This means that the cursor will
start blinking in this input and
the text entered from the keyboard
will fall into this input.
Syntax
element.focus();
Example
Let's click on one button to set focus on the input, and on click on another - remove it:
<input value="text" id="input">
<input type="button" value="focus" id="focus">
<input type="button" value="blur" id="blur">
let input = document.querySelector('#input');
let focus = document.querySelector('#focus');
let blur = document.querySelector('#blur');
// By clicking on the focus button, we set the focus to the input:
focus.addEventListener('click', function() {
input.focus();
});
// By clicking on the blur button, we will remove focus from the input:
blur.addEventListener('click', function() {
input.blur();
});
:
See also
-
the
blur
method
that removes focus from an element