The focus() method can move keyboard focus to a focusable HTML element such as an input or button. window.focus() can also request focus for a browser window, although the browser and user settings decide whether that request is honored.
const input = document.getElementById('my_input');
input.focus();
input.blur();
Calling element.focus() makes that element the active focus target when it is focusable. This is useful after validation errors, after opening a dialog, or when a workflow genuinely benefits from moving keyboard focus.
const email = document.querySelector('#email');
email.focus();
window.focus() asks the browser to bring a window to the front:
window.focus();
This is only a request. Browsers can refuse it, so code should not depend on a popup or tab becoming frontmost. The original plus2net popup demo is retained below for learning about browser-window methods.
Demo of window focus, blur and hasFocus()
Unexpected focus changes can confuse keyboard and assistive-technology users. Move focus only when it supports the user’s next action, and ensure the focused control is visible and clearly styled.
Use document.hasFocus() when you need to know whether the document currently has focus. For visibility of a whole tab, page-visibility APIs are usually more precise than focus alone.
You can also review the related blur() tutorial, window.closed, the Window object, bookmark example and page redirect.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.