- Управление фокусировкой
- HTMLElement: blur() method
- Syntax
- Parameters
- Return value
- Examples
- Remove focus from a text input
- HTML
- JavaScript
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Focusing: focus/blur
- Events focus/blur
- Methods focus/blur
- Allow focusing on any element: tabindex
Управление фокусировкой
обладают свойством фокусировки, то есть, когда мы кликаем по ним, они получают фокус и мы можем изменять состояние этих элементов. Например, в такой странице:
DOCTYPE html> html> head> title>Уроки по JavaScripttitle> head> body> form name="reg"> p>input name="user" value="" /> p>input name="sex" type="radio" checked />М input name="sex" type="radio" />Ж p>Город: select name="city"> option>Москваoption> option>Санкт-Петербургoption> option>Тверьoption> select> p>Согласие input name="agree" type="checkbox" /> p>textarea name="about" rows="10" cols="30">О себеtextarea> p>input type="submit" name="submit"> form> script> script> body> html>
let frm = document.forms[0]; frm.user.onfocus = function(event) { console.log("получение фокуса"); }; frm.user.onblur = function(event) { console.log("потеря фокуса"); };
Теперь, щелкая по элементу, появится сообщение «получение фокуса», то есть, сработало событие focus. А при переходе к другому элементу появляется событие «потеря фокуса», то есть, сработало событие blur. Когда могут понадобиться такие события? Например, для проверки корректности ввода данных в поле ввода. Для простоты положим, что имя пользователя не должно содержать символа #. Такую проверку можно сделать так:
frm.user.onblur = function(event) { if(frm.user.value.includes('#')) frm.user.classList.add('error'); else frm.user.classList.remove('error'); };
То есть, когда в поле ввода содержится символ #, то оно принимает красный фон. Соответственно стиль можно прописать так:
style> .error { background: #CC0000; } style>
frm.user.classList.remove('error');
Однако, обратите внимание, стандарты HTML 5 и выше позволяют в полях ввода прописывать атрибуты required, pattern для автоматической проверки корректности введенных данных. Так что скрипт следует использовать, только если недостаточно встроенных способов валидации данных. Также следует иметь в виду, что события focus и blur не всплывают, то есть, мы не можем перехватить их обработчиком элемента более высокого уровня в иерархии DOM-дерева. Например, если поставить обработчик onfocus на форму:
frm.onfocus = function() { console.log("form: focus"); }
то он никогда не будет срабатывать. Однако, тут есть один нюанс: события focus и blur хоть и не всплывают, но зато имеют фазу погружения и мы можем их перехватить на форме в этот момент:
frm.addEventListener("focus", function() { console.log("form: focus"); }, true);
Теперь, кликая по элементам формы, мы будем видеть сообщения в консоли. Но, все же, если нам нужно перехватывать события фокусировки, то лучше использовать для этого специальные события: focusin и focusout которые работают также как и focus и blur, но всплывают. Обработчики этих событий можно добавлять только через метод addEventListener, следующим образом:
frm.addEventListener("focusin", function() { console.log("form: focusin"); });
и при обновлении документа мы увидим фокусировку на теге textarea. Аналогично работает второй метод. Но здесь есть несколько тонких моментов. Во-первых, эти методы могут не работать в браузерах Firefox. Во-вторых, бывают случаи, когда фокусировка с элемента будет сниматься автоматически. Например, при появлении модальных окон, вызванных методами: alert(), prompt(), confirm() Так что полагаться целиком на методы focus и blur не стоит и в практике программирования ими стараются не пользоваться. Вместо этого лучше полагаться на события focus и blur и реализовывать логику через их обработчики. Или же, используя псевдокласс :focus, определять стили сфокусированного элемента. Работая с событиями focus и blur, следует иметь в виду, что далеко не все элементы HTML-документа по умолчанию поддерживают фокусировку. Например, элементы: div, p, table, span, img и т.п. Добавим div на нашу страницу:
div id="block" style="height:50px; background: #777">div>
block.onfocus = function(event) { console.log("focus"); }; block.onblur = function(event) { console.log("blur"); };
Кликая по блоку div мы не увидим никаких сообщений в консоли. Это, как раз, и говорит о том, что данный элемент не имеет фокусировки. Но ее можно включить, если прописать вот такой атрибут: tabindex=»1″ Теперь, при щелчке мыши по блоку div, будут срабатывать эти два события. Что это за атрибут tabindex? Он указывает в какой последовательности следует переключать фокусы между элементами, при нажатии на клавишу Tab. Так что, если мы какой-то элемент включаем в эту последовательность, то он должен обладать фокусировкой. И браузеры ее включают, даже если, ранее элемент не обладал таким свойством. Причем, это свойство можно установить и непосредственно в скрипте, используя свойство tabIndex:
- tabindex=»0″ располагает элемент на уровне с другими элементами без атрибута tabindex, но обладающих фокусировкой;
- tabindex=»-1″ позволяет фокусироваться на элементе только программно.
let active = document.activeElement; console.log(active);
HTMLElement: blur() method
The HTMLElement.blur() method removes keyboard focus from the current element.
Syntax
Parameters
Return value
Examples
Remove focus from a text input
HTML
input type="text" id="sampleText" value="Sample Text" /> br />br /> button type="button" onclick="focusInput()">Click me to gain focusbutton>
JavaScript
function focusInput() const textField = document.getElementById("sampleText"); textField.focus(); // The input will lose focus after 3 seconds setTimeout(() => textField.blur(); >, 3000); >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
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.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
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.
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 :