Hatatister
Hatatister

Reputation: 1052

js element.click() on focusable element does not shift focus to that element

I stumbled across this behaviour. I want that an input element receives focus, if you click it, so that it becomes the documents' active element. The click is generated programmatically via javascript with element.click(). A default action for focusable elements is, that they receive focus, if clicked w3.

const e = document.getElementById("dom-root");
const e2 = document.createElement("input");
e.appendChild(e2);

e2.addEventListener("click", () => e2.focus());

console.log("Before click:", document.activeElement);
e2.click();
console.log("After click:", document.activeElement);
<!DOCTYPE html>
<html>
  <body>
    <div id="dom-root"></div>
  </body>
</html>

The focus does not change. I tested this with Chrome and Safari. According to this page Most untrusted events will not trigger default actions, with the exception of the click event. This event always triggers the default action, even if the isTrusted attribute is false So I would expect that the focus is changed.

Why isn't the focus changed?

Upvotes: 1

Views: 32

Answers (1)

Mippy
Mippy

Reputation: 904

From Mozilla's web documentation:

The HTMLElement.click() method simulates a mouse click on an element. When called on an element, the element's click event is fired (unless its disabled attribute is set).

It does not focus the element because it is "simulating" a click, not an actual click. Just use .focus() on an element you need to focus.

Upvotes: 2

Related Questions