Javascript focus lost event

Focusing: focus/blur

An element receives the focus when the user either clicks on it or uses the 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 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.

  • 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):
 .invalid < border-color: red; >#error Your email please: >; input.onfocus = function() < if (this.classList.contains('invalid')) < // remove the "error" indication, because the user wants to re-enter something this.classList.remove('invalid'); error.innerHTML = ""; >>; 

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.

Читайте также:  On line html course

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:

 .error Your email please:   

It works in all browsers except Firefox (bug).

If we enter something into the input and then try to use 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.

A focus loss can occur for many reasons.

One of them is when the visitor clicks somewhere else. But also JavaScript itself may cause it, for instance:

  • An alert moves focus to itself, so it causes the focus loss at the element ( blur event), and when the alert is dismissed, the focus comes back ( focus event).
  • If an element is removed from DOM, then it also causes the focus loss. If it is reinserted later, then the focus doesn’t return.

These features sometimes cause focus/blur handlers to misbehave – to trigger when they are not needed.

The best recipe is to be careful when using these events. If we want to track user-initiated focus-loss, then we should avoid causing it ourselves.

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: , , , and so on.

This can be changed using HTML-attribute tabindex .

Any element becomes focusable if it has tabindex . The value of the attribute is the order number of the element when Tab (or something like that) is used to switch between them.

That is: if we have two elements, the first has tabindex=»1″ , and the second has tabindex=»2″ , then pressing Tab while in the first element – moves the focus into the second one.

The switch order is: elements with tabindex from 1 and above go first (in the tabindex order), and then elements without tabindex (e.g. a regular ).

Elements without matching tabindex are switched in the document source order (the default order).

There are two special values:

  • tabindex=»0″ puts an element among those without tabindex . That is, when we switch elements, elements with tabindex=0 go after elements with tabindex ≥ 1 . Usually it’s used to make an element focusable, but keep the default switching order. To make an element a part of the form on par with .
  • tabindex=»-1″ allows only programmatic focusing on an element. The Tab key ignores such elements, but method elem.focus() works.

For instance, here’s a list. Click the first item and press Tab :

Источник

Element: focusout event

The focusout event fires when an element has lost focus, after the blur event. The two events differ in that focusout bubbles, while blur does not.

The opposite of focusout is the focusin event, which fires when the element has received focus.

The focusout event is not cancelable.

Syntax

Use the event name in methods like addEventListener() .

addEventListener("focusout", (event) => >); 

Event type

Event properties

This interface also inherits properties from its parent UIEvent , and indirectly from Event . FocusEvent.relatedTarget The element receiving focus, if any.

Examples

Live example

HTML

form id="form"> label> Some text: input type="text" placeholder="text input" /> label> label> Password: input type="password" placeholder="password" /> label> form> 

JavaScript

const form = document.getElementById("form"); form.addEventListener("focusin", (event) =>  event.target.style.background = "pink"; >); form.addEventListener("focusout", (event) =>  event.target.style.background = ""; >); 

Result

Specifications

Note: The UI Events specification describes an order of focus events that’s different from what current browsers implement.

Browser compatibility

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Фокусировка: focus/blur

Элемент получает фокус, когда пользователь кликает по нему или использует клавишу Tab . Также существует HTML-атрибут autofocus , который устанавливает фокус на элемент, когда страница загружается. Есть и другие способы получения фокуса, о них – далее.

Фокусировка обычно означает: «приготовься к вводу данных на этом элементе», это хороший момент, чтобы инициализовать или загрузить что-нибудь.

Момент потери фокуса («blur») может быть важнее. Это момент, когда пользователь кликает куда-то ещё или нажимает Tab , чтобы переключиться на следующее поле формы. Есть другие причины потери фокуса, о них – далее.

Потеря фокуса обычно означает «данные введены», и мы можем выполнить проверку введённых данных или даже отправить эти данные на сервер и так далее.

В работе с событиями фокусировки есть важные особенности. Мы постараемся разобрать их далее.

События focus/blur

Событие focus вызывается в момент фокусировки, а blur – когда элемент теряет фокус.

Используем их для валидации(проверки) введённых данных.

  • Обработчик blur проверяет, введён ли email, и если нет – показывает ошибку.
  • Обработчик focus скрывает это сообщение об ошибке (в момент потери фокуса проверка повторится):
 .invalid < border-color: red; >#error Ваш email: >; input.onfocus = function() < if (this.classList.contains('invalid')) < // удаляем индикатор ошибки, т.к. пользователь хочет ввести данные заново this.classList.remove('invalid'); error.innerHTML = ""; >>; 

Современный HTML позволяет делать валидацию с помощью атрибутов required , pattern и т.д. Иногда – это всё, что нам нужно. JavaScript можно использовать, когда мы хотим больше гибкости. А ещё мы могли бы отправлять изменённое значение на сервер, если оно правильное.

Методы focus/blur

Методы elem.focus() и elem.blur() устанавливают/снимают фокус.

Например, запретим посетителю переключаться с поля ввода, если введённое значение не прошло валидацию:

 .error Ваш email:   

Это сработает во всех браузерах, кроме Firefox (bug).

Если мы что-нибудь введём и нажмём Tab или кликнем в другое место, тогда onblur вернёт фокус обратно.

Отметим, что мы не можем «отменить потерю фокуса», вызвав event.preventDefault() в обработчике onblur потому, что onblur срабатывает после потери фокуса элементом.

Однако на практике следует хорошо подумать, прежде чем внедрять что-то подобное, потому что мы обычно должны показывать ошибки пользователю, но они не должны мешать пользователю при заполнении нашей формы. Ведь, вполне возможно, что он захочет сначала заполнить другие поля.

Потеря фокуса может произойти по множеству причин.

Одна из них – когда посетитель кликает куда-то ещё. Но и JavaScript может быть причиной, например:

  • alert переводит фокус на себя – элемент теряет фокус (событие blur ), а когда alert закрывается – элемент получает фокус обратно (событие focus ).
  • Если элемент удалить из DOM, фокус также будет потерян. Если элемент добавить обратно, то фокус не вернётся.

Из-за этих особенностей обработчики focus/blur могут сработать тогда, когда это не требуется.

Используя эти события, нужно быть осторожным. Если мы хотим отследить потерю фокуса, которую инициировал пользователь, тогда нам следует избегать её самим.

Включаем фокусировку на любом элементе: tabindex

Многие элементы по умолчанию не поддерживают фокусировку.

Какие именно – зависит от браузера, но одно всегда верно: поддержка focus/blur гарантирована для элементов, с которыми посетитель может взаимодействовать: , , , и т.д.

Это можно изменить HTML-атрибутом tabindex .

Любой элемент поддерживает фокусировку, если имеет tabindex . Значение этого атрибута – порядковый номер элемента, когда клавиша Tab (или что-то аналогичное) используется для переключения между элементами.

То есть: если у нас два элемента, первый имеет tabindex=»1″ , а второй tabindex=»2″ , то находясь в первом элементе и нажав Tab – мы переместимся во второй.

Порядок перебора таков: сначала идут элементы со значениями tabindex от 1 и выше, в порядке tabindex , а затем элементы без tabindex (например, обычный ).

При совпадающих tabindex элементы перебираются в том порядке, в котором идут в документе.

Есть два специальных значения:

  • tabindex=»0″ ставит элемент в один ряд с элементами без tabindex . То есть, при переключении такие элементы будут после элементов с tabindex ≥ 1 . Обычно используется, чтобы включить фокусировку на элементе, но не менять порядок переключения. Чтобы элемент мог участвовать в форме наравне с обычными .
  • tabindex=»-1″ позволяет фокусироваться на элементе только программно. Клавиша Tab проигнорирует такой элемент, но метод elem.focus() будет действовать.

Например, список ниже. Кликните первый пункт в списке и нажмите Tab :

Источник

onfocusout Event

Call a function when an input field is about to lose focus:

More «Try it Yourself» examples below.

Description

The onfocusout event occurs when an element loses focus.

The onfocusout event is often used on input fields.

The onfocosout event is often used with form validation (when the user leaves a form field).

Focus Based Events

See Also:

Syntax

In JavaScript, using the addEventListener() method:

Technical Details

Bubbles: Yes
Cancelable: No
Event type: FocusEvent
HTML tags: ALL HTML elements, EXCEPT: , ,
, , , , , , , , and
DOM Version: Level 2 Events

Browser Support

onfocusout is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

More Examples

Example

Using onfocus and onblur:

Example

Clear input field on focus:

Example

Event delegation: using focus and blur events:

Set useCapture parameter of addEventListener() to true:

let x = document.getElementById(«myForm»);
x.addEventListener(«focus», myFocusFunction, true);
x.addEventListener(«blur», myBlurFunction, true);

function myFocusFunction() document.getElementById(«myInput»).style.backgroundColor = «yellow»;
>

function myBlurFunction() document.getElementById(«myInput»).style.backgroundColor = «»;
>

Example

Event delegation: using focusin and focusout events:

let x = document.getElementById(«myForm»);
x.addEventListener(«focusin», myFocusFunction);
x.addEventListener(«focusout», myBlurFunction);

function myFocusFunction() document.getElementById(«myInput»).style.backgroundColor = «yellow»;
>

function myBlurFunction() document.getElementById(«myInput»).style.backgroundColor = «»;
>

Источник

Оцените статью