• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Detect If an Element has focus

Detect If an Element has focus

Detect If an Element has focus

To detect if an element has the focus, you use the read-only property activeElement of the document object:

const el = document.activeElement

o detect if an element has focus, you compare it with the document.activeElement.

The following checks if the input text with the .username class has the focus:

const el = document.querySelector('.username');
console.log(el === document.activeElement);

Miscellaneous

Related Snippets:

  • What JavaScript Closures Are and How They Work
  • How To Format Numbers as Currency Strings in JavaScript
  • How To Copy To The Clipboard Using JavaScript
  • How To Insert An Item Into An Array Using JavaScript

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers