# Text fields focus in JavaScript

Let's have an input. You can click on this input and after that the text cursor will blink in it and you will be able to enter text into it.

This state is said to be that the input now has input focus. In practice, this means that if you start typing text from the keyboard, then this text will fall into the input that currently has the input focus. If you then click anywhere outside of the input, that input will lose the focus and you won't be able to type into it.

In order to catch the moment an input gains or loses focus, JavaScript provides special events: the `focus` event allows you to catch the focus gain by an input, and the `blur` event catches the loss. Let's try it in practice. Let us have an input:

`<input id="elem" value="text">`

Let's get a reference to it into a variable:

`let elem = document.querySelector('#elem');`

And now let's make it so that when focus is received, the current input text is displayed in the console:

`elem.addEventListener('focus', function() { console.log(elem.value); });`

Given an input. When focus is gained, write the number `1` into it, and when the focus is lost, write the number `2`.

An input is given. Let's put in a number. When focus is lost, display the square of this number.

An input is given, in which there is some text initially. When an input receives focus, clear the contents of that input.

←→
↑
en ru