Getting focus in javascript

Привлечение внимания к окну

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Проверить, находится ли окно в фокусе, а также перевести внимание посетителя на него – сложно.

В первую очередь, это потому, что JavaScript не интегрирован с оконным менеджером ОС. Кроме того, браузер охраняет права посетителя: если он хочет скрыть окно, то JavaScript не может его остановить.

Но кое-что сделать, конечно, можно. Об этом и поговорим.

Метод window.focus

Метод window.focus позволяет сфокусироваться на окне. Он работает по-разному в разных ОС и браузерах.

setInterval(function() < window.focus() >, 1000);

Что будет, если запустить этот код, и затем переключиться в другое окно или вкладку?

Можно подумать, что окно будет оказываться в фокусе раз в секунду. Но это не так.

  1. Вообще никакого эффекта. Самый распространённый случай, если в окне много вкладок.
  2. Окно развернётся (при необходимости) и выйдет на передний план. Обычно это происходит, когда метод window.focus() вызывается для попапа, а активно сейчас – главное окно. То есть, в этом случае вызов сработает.
  3. Заголовок окна начнёт мигать. Чтобы увидеть это в действии – откройте данную страницу в IE, запустите код и переключитесь на другое окно. Браузер попытается привлечь Ваше внимание миганием/мерцанием заголовка окна.
Читайте также:  Цвета html в samp

Мерцание заголовка

В дополнение к window.focus() используют мерцание заголовка окна, как показано в примере ниже:

  

Запустите код и сверните всплывающее окно. А затем – нажмите кнопку с надписью «getAttention(win)». Браузер будет привлекать ваше внимание, как умеет 😉

Обратите внимание: в коде есть проверка на win.closed . Попытка манипулирования закрытым окном вызовет исключение.

Как только посетитель сфокусировался на окне индикация прекращается. Для определения момента фокусировки в примере выше используется событие document.onmousemove .

Можно было использовать событие window.onfocus , но, оказывается, оно ненадёжно.

Событие window.onfocus

Вот переписанный вариант функции getAttention(win) , с использованием события onfocus :

  

Далее мы посмотрим случаи, когда он не срабатывает, и почему нам всё же нужно document.onmousemove .

Когда событие onfocus не работает?

Возможно такое, что посетитель переключается на окно, а window.onfocus не происходит.

Это потому, что переключение между окнами и фокусировка – это разные вещи. Например, если курсор находится в поле для ввода URL браузера, то считается, что окно не в фокусе, хотя посетитель переключился на это окно.

Попробуйте проделать следующее:

  1. Запустите пример с getAttention в Chrome или IE (кстати, в них нельзя отключить адресную панель).
  2. Поместите курсор в панель адреса всплывающего окна.
  3. Перейдите обратно к главному окну и нажмите кнопку getAttention(win)

Вы увидите, что несмотря на то, что вы переключились на окно, и оно сейчас на переднем плане, событие onfocus не срабатывает.

Есть и другие случаи, когда переключение между окнами не вызывает window.onfocus . Скажем, если окно сфокусировать щелчком в поле ввода формы, то в IE события window.onfocus (а также window.onfocusin ) – не сработают!

Можно попробовать поймать момент фокусировки и по-другому, повесив дополнительные обработчики событий на document . В главе Фокусировка: focus/blur описана техника делегирования для focus/blur .

Но этот способ получает фокус только если посетитель сфокусируется где-то в документе: щёлкнет или сделает ещё какое-то действие в документе, а не просто посмотрит на него и проведёт над ним мышкой.

Впрочем, никто не мешает использовать сочетание всех описанных методов.

Итого

Фокусировка и привлечение внимания к окну:

  • Метод focus для window не надёжен. Окнами и вкладками браузера можно уверенно управлять только на уровне ОС. Поэтому для привлечения внимания посетителя к окну стоит также использовать мерцающий заголовок окна.

Обнаружение переключения на окно:

  • У window есть событие onfocus , но оно также ненадёжно. Поэтому для определения переключения на окно – используйте его вместе с делегируемым focus на документе, а также document.onmousemove .

Источник

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.

Источник

Element: focus event

The focus event fires when an element has received focus. The event does not bubble, but the related focusin event that follows does bubble.

The opposite of focus is the blur event, which fires when the element has lost focus.

The focus event is not cancelable.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("focus", (event) => >); onfocus = (event) => >; 

Event type

Event properties

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

Examples

Simple 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 password = document.querySelector('input[type="password"]'); password.addEventListener("focus", (event) =>  event.target.style.background = "pink"; >); password.addEventListener("blur", (event) =>  event.target.style.background = ""; >); 

Result

Event delegation

There are two ways of implementing event delegation for this event: by using the focusin event, or by setting the useCapture parameter of addEventListener() to true .

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( "focus", (event) =>  event.target.style.background = "pink"; >, true, ); form.addEventListener( "blur", (event) =>  event.target.style.background = ""; >, true, ); 

Result

Specifications

Browser compatibility

See also

  • The HTMLElement.focus() method
  • Related events: blur , focusin , focusout
  • This event on Window targets: focus event
  • Focusing: focus/blur

Found a content problem with this page?

This page was last modified on Jul 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.

Источник

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