Page Content

Tutorials

How to Use :Focus Selector in jQuery With Example

:Focus Selector in jQuery

jQuery’s :focus selector helps find and interact with a page’s keyboard-focused element. The element that receives keyboard input or human interaction is indicated by a blinking cursor or highlighted border. It falls under the category of filtering selectors and is regarded as a special jQuery addition to the conventional CSS selectors.

Syntax:

The basic :focus selector syntax follows the jQuery selector pattern:

$(selector:focus)

Selector is any CSS selector (class, ID, tag name) that minimises the number of elements to target, and :focus filters only include the focused element.

How It Works

Tab or click concentrate an HTML element. Most attention goes to keyboard-driven components such form fields, links, and tabIndex.

Putting attention on something triggers a focus event. JQuery handles browser-dependent oddities and inconsistencies that JavaScript developers would have to deal with, simplifying event identification and management. JQuery enables you use concise code across multiple browsers without browser-specific scripting.

One of the shorthand event methods in jQuery is focus(). A function, called a handler, is triggered anytime an element obtains keyboard focus when it is bound to the focus() method of a chosen element. Comparably, jQuery offers the focusin() and focusout() functions, which bind handlers to be triggered in response to the acquisition or loss of keyboard focus by an element or one of its descendants.

Keyup, keydown, and keypress are examples of following keyboard events that are deemed to “target” the element that now has keyboard focus. As a result, when combined with these events, the :focus selector is very helpful for creating interactive web applications since it enables developers to accurately respond to user input in designated fields.

Code Example

Examine an example employing text input fields to illustrate the use and capabilities of the :focus selector and the related focus() method. Here’s an example of how to trigger the appearance of an alert box when a particular text box has attention.

<!DOCTYPE html>
<html>
<head>
  <title>My Test Page</title>
  <!-- Correct jQuery CDN and quotes -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#submitBtn").click(function(){
        var firstName = $("#textbox1").val();
        var lastName = $("#textbox2").val();
        $("#output").html("Hello, " + firstName + " " + lastName + "!");
      });
    });
  </script>
</head>
<body>
  First Name: <input type="text" id="textbox1" /><br />
  Last Name: <input type="text" id="textbox2" /><br /><br />
  <button id="submitBtn">Submit</button>
  <p id="output"></p>
</body>
</html>

Output:

First Name: 
John
Last Name: 
Doe
Submit
Hello, John Doe!

A small web page with two text input boxes (textbox1 and textbox2) with unique id attributes is created by this HTML. In contrast to $(document), the <script> tag includes the jQuery library.major code is in ready(). This restricts code execution to when the web page’s DOM is fully loaded and ready for change.

Explanation of the Code

$(document).ready(function(){…});: This standard jQuery construct ensures that its function code only executes once the DOM is loaded and constructed. This is crucial since you cannot interact with page components earlier. Due to inconsistent browser implementations, it is considered more reliable than the onload event handler.

$(‘#textbox2’): The jQuery selector $(‘#textbox2’) targets HTML elements by ID. ‘textbox2’ is the second input field’s unique ID in our HTML, and # indicates an ID selector. The $ function is the basic procedure for picking portions of a document in jQuery and is a shorthand notation for referring an element of the web page.

.focus(function() { … });: This jQuery event method attaches the focus event to a function (the event handler). This anonymous function() runs when $(‘#textbox2’) focusses on the HTML element it selects. Many jQuery functions are nameless and not meant to be reused.

alert(‘textbox2 has focus’);: This JavaScript line in the event handler displays “textbox2 has focus” in a browser pop-up alert box.

The Example’s Operation When the HTML page loads in a browser, nothing happens at first. You can then use the Tab key to travel to the “Last Name” text box (textbox2) or click right into it to initiate the focus event. Consequently, the bound function will run and an alert box will appear.

This illustrates how jQuery enables you to precisely identify when an element is the focus of the keyboard and programmatically react to that event. This method is essential for developing user interfaces and interactive forms because it enables developers to apply validation criteria or offer dynamic feedback while users interact with the page.

Conclusion

In conclusion, jQuery’s :focus selector and focus() method allow developers to detect and respond to keyboard focus on web components easily. Developers can improve user experiences by enabling precise interaction with targeted elements usually form inputs or links through dynamic feedback, validation, and interactive behaviours.

The selector targets the element in focus in real time, while focus() connects custom behaviour to focus events. They simplify event processing and minimise cross-browser discrepancies with short, legible code. Building accessible and responsive forms and interfaces with this functionality makes web page navigation and interaction more straightforward.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index