- HTMLElement: focus() method
- Syntax
- Parameters
- Return value
- Examples
- Focus on a text field
- HTML
- JavaScript
- Result
- Focus on a button
- HTML
- JavaScript
- Result
- Focus with and without scrolling
- HTML
- JavaScript
- Result
- Specifications
- Notes
- Browser compatibility
- See also
- Found a content problem with this page?
- HTML autofocus Attribute
- Definition and Usage
- Browser Support
- Syntax
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Автофокус
- Автофокус
- Популярные материалы
HTMLElement: focus() method
The HTMLElement.focus() method sets focus on the specified element, if it can be focused. The focused element is the element that will receive keyboard and similar events by default.
By default the browser will scroll the element into view after focusing it, and it may also provide visible indication of the focused element (typically by displaying a «focus ring» around the element). Parameter options are provided to disable the default scrolling and force visible indication on elements.
Syntax
Parameters
An optional object for controlling aspects of the focusing process. This object may contain the following properties:
A boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true , no scrolling will occur.
focusVisible Optional Experimental
A boolean value that should be set to true to force visible indication that the element is focused. By default, or if the property is not true , a browser may still provide visible indication if it determines that this would improve accessibility for users.
Return value
Examples
Focus on a text field
This example uses a button to set the focus on a text field.
HTML
input id="myTextField" value="Text field." /> button id="focusButton">Click to set focus on the text fieldbutton>
JavaScript
The code below adds an event handler to set the focus on the text field when the button is pressed. Note that most browsers will automatically add visible indication (a «focus ring») for a focused text field, so the code does not set focusVisible to true .
.getElementById("focusButton").addEventListener("click", () => document.getElementById("myTextField").focus(); >);
Result
Select the button to set focus on the text field.
Focus on a button
This example demonstrates how you can set the focus on a button element.
HTML
First we define three buttons. Both the middle and right button will set focus on the left-most button. The right right-most button will also specify focusVisible .
button id="myButton">Buttonbutton> button id="focusButton">Click to set focus on "Button"button> button id="focusButtonVisibleIndication"> Click to set focus and focusVisible on "Button" button>
JavaScript
The code below sets up handlers for click events on the middle and right buttons.
.getElementById("focusButton").addEventListener("click", () => document.getElementById("myButton").focus(); >); document .getElementById("focusButtonVisibleIndication") .addEventListener("click", () => document.getElementById("myButton").focus( focusVisible: true >); >);
Result
Select either the middle button or right-most button to set focus on the left-most button.
Browsers do not usually show visible focus indication on button elements when focus is set programmatically, so the effect of selecting the middle button may not be obvious. However provided the focusVisible option is supported on your browser, you should see focus changing on the left-most button when the right-most button is selected.
Focus with and without scrolling
This example shows the effect of setting focus with the option preventScroll set true and false (the default).
HTML
The HTML defines two buttons that will be used to set the focus of a third button that is off-screen
button id="focus_scroll">Click to set focus on off-screen buttonbutton> button id="focus_no_scroll"> Click to set focus on offscreen button without scrolling button> div id="container"> button id="myButton" style="margin-top: 500px;">Buttonbutton> div>
JavaScript
This code sets a click event handler on the first and second buttons to set the focus on the last button. Note that the first handler doesn’t specify the preventScroll option so scrolling to the focused element will be enabled.
.getElementById("focus_scroll").addEventListener("click", () => document.getElementById("myButton").focus(); // default: >); document.getElementById("focus_no_scroll").addEventListener("click", () => document.getElementById("myButton").focus( preventScroll: true >); >);
Result
Select the first button to set focus and scroll to the off-screen button. Selecting the second button set’s the focus, but scrolling is disabled.
Specifications
Notes
- If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement
- Behavior of the focus in relation to different HTML features like tabindex or shadow dom, which previously remained under-specified, were updated in October 2019. See the WHATWG blog for more information.
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.
HTML autofocus Attribute
Let the «First name» input field automatically get focus when the page loads:
Definition and Usage
The autofocus attribute is a boolean attribute.
When present, it specifies that an element should automatically get focus when the page loads.
Browser Support
The numbers in the table specify the first browser version that fully supports the attribute.
Attribute | |||||
---|---|---|---|---|---|
autofocus | 5.0 | 11.0 | 4.0 | 5.0 | 9.6 |
Syntax
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Автофокус
Фокус это активность элемента формы, позволяющая производить с ним какие-то действия. Для текстового поля можно вводить текст, для списка выбирать пункт с помощью клавиатуры и др. Автофокус — это автоматически установленный фокус поля формы. К примеру, при открытии google.ru вы можете сразу набирать текст в строке поиска без лишних манипуляций с мышью и клавиатурой.
Автофокус создаётся с помощью атрибута autofocus , который можно добавлять к следующим элементам: , , , , . Для текстового поля синтаксис такой.
На странице должен быть только один элемент с автофокусом.
В примере 1 показано создание формы авторизации с автофокусом.
Пример 1. Использование автофокуса
Результат примера показан на рис. 1. Браузер обычно выделяет поле с фокусом рамкой.
Рис. 1. Автофокус в текстовом поле
Поле с фокусом можно изменить через стили воспользовавшись псевдоклассом :focus , добавляя его к селектору input . Код HTML останется неизменным, появится только блок со стилями (пример 2).
Пример 2. Изменение вида поля с фокусом
Результат данного примера показан на рис. 2. Как только поле получает фокус или, другими словами, в него можно вводить текст, то цвет фона у поля меняется и вокруг появляется голубое свечение. Оно сделано с помощью тени соответствующего цвета через свойство box-shadow .
Рис. 2. Вид поля при получении фокуса
- Текст
- Фон
- Ссылки
- Списки
- Изображения
- Таблицы
- Формы
- Отправка данных формы
- Текстовое поле
- Поле для ввода пароля
- Многострочное текстовое поле
- Кнопки
- Элемент label
- Переключатели
- Флажки
- Поле со списком
- Скрытое поле
- Поле с изображением
- Загрузка файлов
- Адрес электронной почты
- Веб-адрес
- Выбор цвета
- Ввод чисел
- Ползунок
- Календарь
- Поле для поиска
- Номер телефона
- Группирование элементов форм
- Блокирование элементов форм
- Автофокус
- Подсказывающий текст
- Защита от дурака
Автофокус
Фокус это активность элемента формы, позволяющая производить с ним какие-то действия. Для текстового поля можно вводить текст, для списка выбирать пункт с помощью клавиатуры и др. Автофокус — это автоматически установленный фокус поля формы. К примеру, при открытии google.ru вы можете сразу набирать текст в строке поиска без лишних манипуляций с мышью и клавиатурой.
Автофокус создаётся с помощью атрибута autofocus , который можно добавлять к следующим тегам: , , , , . Для текстового поля синтаксис следующий.
На странице должен быть только один элемент с автофокусом.
В примере 1 показано создание формы авторизации с автофокусом.
Пример 1. Использование автофокуса
Результат примера показан на рис. 1. Браузер Chrome фокус полей формы выделяет с помощью оранжевой рамки.
Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.
Популярные материалы
- Самоучитель HTML4
- Самоучитель CSS
- Как добавить картинку на веб-страницу?
- Спецсимволы
- Структура HTML-кода
- Введение в HTML
- Способы добавления стилей на страницу
- Выравнивание текста
- Якоря
- Как добавить иконку сайта в адресную строку браузера?
- Позиционирование элементов
- Ссылки