Focus/Blur Events in jQuery Tutorial 🎯

beginner
9 min

Focus/Blur Events in jQuery Tutorial 🎯

Welcome to our comprehensive guide on Focus/Blur Events in jQuery! This tutorial is designed to help both beginners and intermediates understand and master this essential concept.

Understanding Focus and Blur Events 📝

In web development, Focus and Blur events are essential to react to user interaction with form elements. When a user interacts with a form field (like clicking inside a textbox), the field gains focus. Conversely, when a user clicks somewhere else, the field loses focus.

Focus Event

The focus event triggers whenever an element receives focus. This could be due to several reasons, such as:

  • Clicking on the element
  • Navigating to the element using the Tab key
  • Programmatically setting the focus
javascript
$( "input" ).focus(function() { // code to execute when the input field receives focus });

Blur Event

The blur event triggers whenever an element loses focus. This could be due to several reasons, such as:

  • Clicking outside the element
  • Navigating to another form field using the Tab key
  • Programmatically setting the focus to another element
javascript
$( "input" ).blur(function() { // code to execute when the input field loses focus });

Practical Use Cases 💡

Focus and Blur events are crucial in various real-world scenarios, such as:

  • Validating form fields when they lose focus
  • Disabling submit button until all form fields are filled
  • Highlighting the focused form field

Advanced Example: Enforcing Field Validation 🎯

Let's create a simple example where we validate a username field when it loses focus.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Focus/Blur Events</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <form id="myForm"> <label for="username">Username:</label> <input type="text" id="username" name="username"> <button type="submit">Submit</button> </form> <script> $(document).ready(function(){ $("#username").blur(function(){ // Validate the username field var username = $(this).val(); if(username.length < 5){ alert("Username must be at least 5 characters long."); $(this).focus(); // Re-focus the field } }); }); </script> </body> </html>

Quiz

Quick Quiz
Question 1 of 1

What event triggers when a user clicks outside a form field?