.focus()

The method that sets focus on the DOM element on which it is called.

Time to read: 5 min

Briefly

Calling the focus() method on a DOM element sets focus on that element. When an element is focused, it intercepts and processes keyboard events.

Focus cannot be placed on an element if it is disabled. For example, if a button or input field has the disabled attribute.

How it's written

The focus() method is usually called without arguments, but you can also pass an object with the preventScroll property:

        
          
          element.focus()element.focus({ preventScroll: true })
          element.focus()
element.focus({ preventScroll: true })

        
        
          
        
      

By default, the browser scrolls the page to the element that the focus is moved to. This also happens if preventScroll is set to false. If preventScroll is set to true, there will be no scrolling of the page to the element.

Example

Imagine we are working with a web page with a form:

        
          
          <form action="/apply" method="POST">  <label>    Your name:    <input type="text" name="name">  </label>  <label>    Email:    <input type="email" name="email" id="email">  </label>  <button type="submit">Submit application</button></form>
          <form action="/apply" method="POST">
  <label>
    Your name:
    <input type="text" name="name">
  </label>

  <label>
    Email:
    <input type="email" name="email" id="email">
  </label>

  <button type="submit">Submit application</button>
</form>

        
        
          
        
      

To programmatically set focus on the Email field, you need to get the desired element and call the focus() method on it:

        
          
          const emailInput = document.getElementById('email')emailInput.focus()
          const emailInput = document.getElementById('email')
emailInput.focus()

        
        
          
        
      

After executing the code, the field will become available for input.

In the example, focus moves depending on the selected element in the dropdown list:

Open demo in the new window

How to understand

What is focus?

Focus in the web is an indication of the active element on the page. Browsers most often denote such an element with a blue semi-transparent border. You can interact with the active element, and it receives keyboard events. For example, when we type a value in an input field, that input field is focused.

Focus is critically important for people who cannot or do not want to use a mouse. These users move the focus between interactive elements within the page using the Tab button. This behavior is provided by the browser by default.

You can influence focus using the HTML attributes autofocus and tabindex, as well as from JavaScript by calling the focus() and blur() methods on DOM elements.

When the browser displays the page, the focus is not set by default. When pressing Tab, the focus will be set on the first interactive element at the top of the page and will move down in order through the markup.

When is focus() needed?

There are cases when you need to programmatically set focus on an element:

  • a user clicks a button that opens a modal window. You need to move focus to this window so that the user does not get lost;
  • when selecting a value from a list, you need to automatically move focus to a dependent list;
  • when implementing custom hotkeys. For example, we want to move between form elements with arrow keys.

These cases share the need to move focus non-sequentially, not as the browser does by default. The focus() method allows you to move the focus arbitrarily.

For example, in the case of opening a modal window, you need to move focus to it. We will subscribe to the click event on the button that opens the window and call focus() in the handler:

        
          
          const openModalButton = document.getElementById('open-modal-button')const modalWindow = document.getElementById('modal-window')openModalButton.addEventListener('click', function(event) {  modalWindow.focus()})
          const openModalButton = document.getElementById('open-modal-button')
const modalWindow = document.getElementById('modal-window')
openModalButton.addEventListener('click', function(event) {
  modalWindow.focus()
})

        
        
          
        
      

A complete example of implementing a modal window is described in WAI-ARIA Authoring Practices.

Not every element can have focus

Focus is an indication of the active element on the page, but not all elements can have focus. Typically, focus can be set on interactive elements that can be interacted with via the keyboard.

The HTML specification describes all the criteria that make an element focusable. We will cover the most important ones.

If you do not set the attributes that affect the element's accessibility for focus, each browser independently determines which element can have focus. In all modern browsers, the following elements can have focus:

  • links <a> with an href attribute set;
  • buttons <button>;
  • input fields <input>, except for hidden ones (type="hidden");
  • dropdown lists <select>;
  • multi-line input fields textarea;
  • elements <summary>;
  • any arbitrary element if it has the tabindex attribute set.

If any of these elements has the disabled attribute set, it ceases to be accessible for focus.

In practice

Advice 1

🛠 If you need to set focus on an element immediately after the page loads, it's better to add the autofocus attribute directly in the markup. The browser will set focus on the element automatically:

        
          
          <form action="/apply" method="POST">  <label>    Your name    <input type="text" name="name" autofocus>  </label>  <label>    Email:    <input type="email" name="email">  </label>  <button type="submit">Submit application</button></form>
          <form action="/apply" method="POST">
  <label>
    Your name
    <input type="text" name="name" autofocus>
  </label>

  <label>
    Email:
    <input type="email" name="email">
  </label>

  <button type="submit">Submit application</button>
</form>

        
        
          
        
      

🛠 To programmatically remove focus from an element, you need to either call the blur() method or move the focus to another element. Non-programmatically, focus is removed with the mouse as soon as the user clicks on any mouse button.

🛠 The CSS property outline is responsible for the outline of the focused element. Do not hide it if there is no alternative way to highlight focused elements on the website.