How to Set the Focus on an Element in JavaScript

08/03/2021

Contents

In this article, you will learn how to set the focus on an element in JavaScript.

Setting focus on an element

In JavaScript, you can set the focus on an element using the focus() method. This method is available on most DOM elements, including form controls, links, and buttons.

const myElement = document.getElementById('my-element');
myElement.focus();

In this example, the getElementById() method is used to get the element with the ID of my-element. The focus() method is then called on the element to set focus.

Setting focus on an element when the page loads

You can also set focus on an element when the page loads using the window.onload event. This event fires when the page has finished loading, so you can use it to set focus on an element as soon as the page is ready.

window.onload = function() {
  const myElement = document.getElementById('my-element');
  myElement.focus();
};

In this example, the window.onload event is used to set focus on the element with the ID of my-element as soon as the page is loaded.

Setting focus on a dynamically created element

You can also set focus on an element when it is dynamically created or added to the DOM. To do this, you need to wait until the element is added to the DOM before setting focus. You can do this using the setTimeout() method with a delay of 0 milliseconds. This delay allows the element to be added to the DOM before setting focus.

const myElement = document.createElement('input');
document.body.appendChild(myElement);

setTimeout(function() {
  myElement.focus();
}, 0);

In this example, the createElement() method is used to create a new input element. The appendChild() method is then called on the document.body element to add the new element to the DOM. The setTimeout() method is used to set focus on the new element after a delay of 0 milliseconds.