Setting focus on HTML elements is a crucial aspect of creating user-friendly web applications. Whether you’re building forms, modal dialogs, or interactive interfaces, knowing how to programmatically control focus using jQuery can significantly enhance user experience and accessibility.
This comprehensive guide will walk you through everything you need to know about setting focus on elements using jQuery.
What is Element Focus in Web Development?
Element focus refers to the state where a particular HTML element is selected and ready to receive user input. When an element has focus, it becomes the active element on the page and can respond to keyboard events like typing or pressing Enter. Common focusable elements include input fields, textareas, buttons, and select dropdowns.
The jQuery .focus() Method
The .focus() method is jQuery’s primary tool for setting focus on elements. This method triggers the focus event or attaches a function to run when a focus event occurs.
Basic Syntax
$(selector).focus()Set Focus on Different HTML Elements
Let me show you how to set focus on different HTML elements.
1. Set Focus on Input Fields
The most common use case is setting focus on input fields, especially in forms:
<input type="text" id="username" placeholder="Enter username">
<input type="text" id="email" placeholder="Enter email">
<button id="focusUsername">Focus Username</button>$(document).ready(function() {
// Set focus on username field when page loads
$("#username").focus();
// Set focus when button is clicked
$("#focusUsername").click(function() {
$("#username").focus();
});
});You can see the output in the screenshot below.

2. Set Focus on Textarea Elements
Textareas work similarly to input fields:
<textarea id="comments" rows="4" cols="50" placeholder="Enter your comments"></textarea>
<button id="focusComments">Focus Comments</button>$(document).ready(function() {
$("#focusComments").click(function() {
$("#comments").focus();
});
});3. Set Focus on Select Dropdowns
You can also set focus on select elements:
<select id="country">
<option value="">Select Country</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select>$(document).ready(function() {
$("#country").focus();
});You can see the output in the screenshot below.

Common Scenarios and Solutions
Here are the common scenarios and solutions to set focus on elements.
Set Focus on Dynamically Created Elements
One challenge developers often face is setting focus on elements that appear dynamically. You need to ensure the element is fully rendered before setting focus:
// Wrong way - element might not be ready
$("#dynamicElement").show().focus();
// Correct way - using setTimeout or callback
$("#dynamicElement").show(function() {
$(this).focus();
});
// Alternative using setTimeout
$("#dynamicElement").show();
setTimeout(function() {
$("#dynamicElement").focus();
}, 10);Set Focus in Modal Dialogs
When opening modal dialogs, it’s good practice to set focus on the first input field:
function openModal() {
$("#myModal").show();
$("#myModal input:first").focus();
}Form Validation Focus
Set focus on the first invalid field in form validation:
function validateForm() {
var isValid = true;
var firstInvalidField = null;
$("input[required]").each(function() {
if ($(this).val() === "") {
$(this).addClass("error");
if (firstInvalidField === null) {
firstInvalidField = $(this);
}
isValid = false;
}
});
if (!isValid && firstInvalidField) {
firstInvalidField.focus();
}
return isValid;
}You can see the output in the screenshot below.

Get the Currently Focused Element
Sometimes you need to determine which element currently has focus. jQuery provides a selector for this:
// Get the currently focused element
var focusedElement = $(":focus");
// Check if a specific element has focus
if ($("#username").is(":focus")) {
console.log("Username field has focus");
}
// Get focused element on focus change
$(document).on("focusin", function(e) {
console.log("Focused element:", e.target);
});Event Handling with Focus
Let us see how we can handle events with focus.
Focus and Blur Events
These events let you detect when an input gains or loses focus, allowing you to style fields or trigger actions accordingly.
$("#username").focus(function() {
$(this).css("border-color", "blue");
console.log("Username field gained focus");
});
$("#username").blur(function() {
$(this).css("border-color", "");
console.log("Username field lost focus");
});Focus with Validation
This approach removes error styling on focus and re-applies it if the input is left empty after losing focus.
$("input").focus(function() {
$(this).removeClass("error");
}).blur(function() {
if ($(this).val() === "") {
$(this).addClass("error");
}
});Best Practices for Setting Focus on Elements in jQuery
Here are some best practices for setting the focus on elements in jQuery.
1. Accessibility Considerations
Always ensure focus management enhances accessibility:
// Set focus and announce to screen readers
$("#errorMessage").focus().attr("aria-live", "polite");2. Prevent Focus Loops
Avoid creating infinite focus loops:
var preventLoop = false;
$("#field1").blur(function() {
if (!preventLoop) {
preventLoop = true;
$("#field2").focus();
preventLoop = false;
}
});3. Mobile Considerations
Be cautious with automatic focus on mobile devices, as it can trigger the virtual keyboard unexpectedly:
// Check if not mobile before setting focus
if (!(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))) {
$("#searchField").focus();
}Advanced Focus Techniques
Let me explain to you the advanced focused techniques.
Sequential Focus Management
This technique manually controls the tab order of form elements for custom navigation behavior.
function setupTabOrder() {
var focusableElements = $("input, select, textarea, button");
focusableElements.each(function(index) {
$(this).data("tabindex", index);
});
$(document).keydown(function(e) {
if (e.key === "Tab") {
e.preventDefault();
var current = $(":focus").data("tabindex") || 0;
var next = e.shiftKey ? current - 1 : current + 1;
if (next >= 0 && next < focusableElements.length) {
focusableElements.eq(next).focus();
}
}
});
}Troubleshoot Common Issues
Let us learn how to troubleshoot some common issues that occur when setting focus on an element in jQuery.
Focus Not Working on Hidden Elements
Elements with display: none cannot receive focus. Show the element first:
// Wrong
$("#hiddenField").focus(); // Won't work
// Correct
$("#hiddenField").show().focus();Timing Issues
Use proper timing when setting focus after DOM manipulation:
// Use callbacks or promises
$("#element").slideDown(300, function() {
$(this).focus();
});Mastering jQuery’s focus functionality is essential for creating intuitive and accessible web applications. From basic focus setting to advanced focus management, these techniques will help you build better user interfaces. Remember to always consider accessibility, mobile users, and provide smooth user experiences when implementing focus behavior.
The .focus() method, combined with proper event handling and validation techniques, gives you powerful control over user interaction flows in your web applications. Practice these examples and adapt them to your specific use cases for optimal results.
You may also like to read:
- jQuery Set Selected Option by Text
- jQuery Remove Element by ID: with Examples
- How to Set Selected Value of Dropdown in jQuery?
- How to Get URL Parameters Using jQuery?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.