How to check if an element is focused in JavaScript

One of the typical task that occurs when working with JavaScript is checking if an element on a web page has the focus.

The focus refers to the element that is currently selected or active, such as an input field or a button.

In this article, we will show you the different methods to check if an element is focused in JavaScript, and provide a step-by-step instructions with code examples.

What is the Importance of Checking Element Focus?

Before moving into the different methods of checking element focus, let’s understand first why this task holds importance in web development.

The ability to identify whether an element has the focus allows us to increase user experience and create collective features.

Now, let’s move into the methods for checking element focus in JavaScript.

Methods to check if an element is focused in JavaScript

Here are the following methods to check if an element is focused in JavaScript:

Method 1: Using the document.activeElement Property

The document.activeElement property returns the currently focused element on the page.

We can use this property to check if a specific element is focused.

Here’s an example code that uses the document.activeElement:

const element = document.getElementById('btnInput');

if (element === document.activeElement) {
    console.log('The element is focused in JavaScript.');
} else {
    console.log('The element is not focused in JavaScript.');
}

In this example code, we access a reference to the proper element using its “ID” and then compare it with the active element.

If they match, we log a message that demonstrating the element is focused; otherwise, we log a message declaring that the element is not focused.

Method 2: Using the document.hasFocus()

Another method to identify if an element is focused involves by applying the document.hasFocus() method.

This method returns a Boolean value showing the document has focus.

Here’s an example code that use document.hasFocus():

const isFocused = document.hasFocus();

if (isFocused) {
    console.log('The document has focus element.');
} else {
    console.log('The document does not have focus element.');
}

By using document.hasFocus(), we can figure out that if the document has focus, the element we are interested in is also focused.

Method 3: Using Event Listeners

We can apply the event listeners to detect when an element proceeds or loses focus.

By connecting the proper event handlers, we can execute the different actions based on the element’s focus state.

Here’s an example code that uses Event Listeners:

const element = document.getElementById('btnEvent');

element.addEventListener('focus', () => {
    console.log('The element gained focus the element.');
});

element.addEventListener('blur', () => {
    console.log('The element lost focus in the element.');
});

In this example code, we listen for the focus event, which is triggered when the element gains focus.

Similarly, we listen for the blur event, which is removed when the element loses focus.

Inside the event handlers, we can perform any applicable operations.

Method 4: Using the :focus CSS Pseudo-Class

The :focus CSS pseudo-class enables us to style elements based on their focus state.

We can apply this pseudo-class in combination with JavaScript to identify if an element is focused.

Here’s an example code that uses the :focus CSS Pseudo-Class:

const elementSample = document.getElementById('btnClass');

const isFocused = getComputedStyle(elementSample, ':focus') !== null;

if (isFocused) {
    console.log('The element is focused.');
} else {
    console.log('The element is not focused.');
}

By using the getComputedStyle function, we can check if the element has the :focus pseudo-class applied to it.

Method 5: Using the tabindex Attribute

The tabindex attribute allows us to control the order in which elements receive focus when navigating with the Tab key.

We can utilize this attribute to check if an element is focused programmatically.

Here’s an example code:

const elementSample = document.getElementById('btnEvent');

const isFocused = elementSample === document.activeElement;

if (isFocused) {
    console.log('The element is focused.');
} else {
    console.log('The element is not focused.');
}

In this code example, we compare the proper element with the active element to determine if it is focused.

FAQs

How can I check if an input element is focused?

To check if an input element is focused in JavaScript, you can use any of the methods mentioned in this article.

Can I determine if an element inside an iframe is focused?

Yes, it is possible to determine if an element inside an iframe is focused. You can access the iframe’s content using the contentDocument property and then use any of the methods discussed earlier to check if the desired element has focus.

Is it possible to check if a button element is focused?

Absolutely! The same methods we have covered in this article can be applied to check if a button element is focused.

Whether it is using the document.activeElement property, event listeners, or CSS pseudo-classes, you can easily determine if a button element has the focus.

Are there any browser compatibility issues when checking element focus?

Most of the modern browsers fully support the methods discussed in this article.

However, it is always a good practice to test your code across different browsers and versions to ensure compatibility.

Be aware that older browsers may have limited support for several methods or may require alternative methods.

Conclusion

In this article, we have discussed the different methods to check if an element is focused in JavaScript.

Also, we have learned about using properties like document.activeElement and document.hasFocus(), as well as event listeners, CSS pseudo-classes, and the tabindex attribute.

Additional Resources

Quick step-by-step summary (click to expand)
  1. What is the Importance of Checking Element Focus. Read the ‘What is the Importance of Checking Element Focus?’ section for the details and code.
  2. Methods to check if an element is focused in JavaScript. Read the ‘Methods to check if an element is focused in JavaScript’ section for the details and code.
  3. Conclusion. Read the ‘Conclusion’ section for the details and code.
  4. Additional Resources. Read the ‘Additional Resources’ section for the details and code.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Adones Evangelista


Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++
 · View all posts by Adones Evangelista →

Leave a Comment