mildog8
mildog8

Reputation: 2154

Tell if <input> or <textarea> has focus using native Javascript

How do you tell if an input or textarea has focus in native javascript?

This is not a duplicate as it asks for a native Javascript solution!

Upvotes: 2

Views: 485

Answers (2)

mildog8
mildog8

Reputation: 2154

To determine if any input/textarea on the page has focus:

if([...document.querySelectorAll("input, textarea")].some(el => el === document.activeElement)) {
  // An input or textarea currently has focus
}

To determine if a particular input/textarea on the page has focus:

if(document.activeElement === textareaEl) {
  // textareaEl currently has focus
}

Upvotes: 3

Rituraj ratan
Rituraj ratan

Reputation: 10378

use :focus

$("input, textarea").is(":focus")

see here it will helpful

Upvotes: 0

Related Questions