Focusing: focus/blur
An element receives the focus when the user either clicks on it or uses the key:Tab key on the keyboard. There’s also an autofocus HTML attribute that puts the focus onto an element by default when a page loads and other means of getting the focus. Focusing on an element generally means: “prepare to accept the data here”, so that’s the moment when we can run the code to initialize the required functionality. The moment of losing the focus (“blur”) can be even more important. That’s when a user clicks somewhere else or presses key:Tab to go to the next form field, or there are other means as well. Losing the focus generally means: “the data has been entered”, so we can run the code to check it or even to save it to the server and so on. There are important peculiarities when working with focus events. We’ll do the best to cover them further on.
Events focus/blur
The focus event is called on focusing, and blur – when the element loses the focus. Let’s use them for validation of an input field. In the example below: - The blur handler checks if the field has an email entered, and if not – shows an error. - The focus handler hides the error message (on blur it will be checked again): Modern HTML allows us to do many validations using input attributes: required, pattern and so on. And sometimes they are just what we need. JavaScript can be used when we want more flexibility. Also we could automatically send the changed value to the server if it’s correct.
Methods focus/blur
Methods elem.focus() and elem.blur() set/unset the focus on the element. For instance, let’s make the visitor unable to leave the input if the value is invalid: It works in all browsers except Firefox (bug). If we enter something into the input and then try to use key:Tab or click away from the , then onblur returns the focus back. Please note that we can’t “prevent losing focus” by calling event.preventDefault() in onblur, because onblur works after the element lost the focus. In practice though, one should think well, before implementing something like this, because we generally should show errors to the user, but should not prevent their progress in filling our form. They may want to fill other fields first.
Allow focusing on any element: tabindex
By default, many elements do not support focusing. The list varies a bit between browsers, but one thing is always correct: focus/blur support is guaranteed for elements that a visitor can interact with: