JavaScript Form blur Event: The Complete Guide

JavaScript has many events that help us create interactive and dynamic web pages. One of these useful events is the blur event. This guide will explain everything you need to know about the blur event. We’ll cover what it is, why it’s useful, where to use it, how to implement it, and when it comes into play. Let’s dive in!

What is the blur Event?

The blur event in JavaScript is fired when an element loses focus. This typically happens when a user clicks away from an input field, a textarea, or navigates to another element using the tab key. The blur event is useful for validating input fields, saving data, or triggering other actions when an element loses focus.

Why Use the blur Event?

Using the blur event is beneficial because it allows you to handle actions when an element loses focus. You can use it to validate input fields, save user input, provide feedback, or perform any other action that should occur when an element is no longer active. This improves user experience by ensuring that necessary actions are taken at the right time.

Where Can You Use the blur Event?

You can use the blur event on any HTML element that can receive focus, such as <input>, <textarea>, <button>, and <select>. This event is particularly useful in forms and interactive elements that require user input.

How to Use the blur Event

Let’s dive into some examples to see how the blur event works in different scenarios.

Basic Example

Here’s a simple example to show how the blur event works with an input element.

HTML
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<p id="status">Status: Click on the input field to focus, then click away to blur ✍️</p>

<script>
  const input = document.getElementById("name");
  const status = document.getElementById("status");

  input.addEventListener("blur", () => {
    status.textContent = "Status: Input field lost focus πŸ’€";
  });
</script>

In this example, the status message updates when the input field loses focus.

Example with Form Validation

Let’s see how the blur event works with form validation.

HTML
<form id="validationForm">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" />
  <p id="validationStatus">Status: Waiting for input ⏳</p>
</form>

<script>
  const input = document.getElementById("email");
  const status = document.getElementById("validationStatus");

  input.addEventListener("blur", () => {
    if (!input.value.includes("@")) {
      status.textContent = "Status: Invalid email address ❌";
    } else {
      status.textContent = `Status: Valid email address: ${input.value} βœ”οΈ`;
    }
  });
</script>

In this example, the status message updates to indicate whether the email address is valid when the input field loses focus.

Example with Saving Data

Let’s see how the blur event works with saving user input.

HTML
<form id="saveForm">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" />
  <p id="saveStatus">Status: Waiting for input ⏳</p>
</form>

<script>
  const input = document.getElementById("username");
  const status = document.getElementById("saveStatus");

  input.addEventListener("blur", () => {
    localStorage.setItem("username", input.value);
    status.textContent = `Status: Username saved: ${input.value} πŸ’Ύ`;
  });
</script>

In this example, the username is saved to local storage when the input field loses focus.

When to Use the blur Event

The blur event is particularly useful in scenarios where:

  • You need to validate input fields when they lose focus.
  • You want to save user input when they leave a field.
  • You need to trigger specific actions when an element is no longer active.

Comparing blur with Other Form Events

To understand the blur event better, let’s compare it with other common form events.

EventDescriptionExample Usage
blurFired when an element loses focusValidate input fields when they lose focus
focusFired when an element gains focusHighlight focused elements
inputFired whenever the value of an input changesProvide live feedback on form fields
changeFired when the value of an input changes and loses focusValidate field values after changes

Code Examples of Different Events

Here’s how you can use some of these events in your code:

HTML
<form id="exampleForm">
  <label for="exampleInput">Input:</label>
  <input type="text" id="exampleInput" name="exampleInput" required />
  <button type="submit">Submit</button>
  <button type="reset">Reset</button>
</form>

<p id="exampleStatus">Status: Waiting for interaction ⏳</p>

<script>
  const form = document.getElementById("exampleForm");
  const status = document.getElementById("exampleStatus");
  const input = document.getElementById("exampleInput");

  input.addEventListener("blur", () => {
    status.textContent = "Status: Input field lost focus πŸ’€";
  });

  input.addEventListener("focus", () => {
    status.textContent = "Status: Input field focused πŸ”";
  });

  form.addEventListener("input", () => {
    status.textContent = `Status: Input changed to: ${input.value} ✍️`;
  });

  form.addEventListener("change", () => {
    status.textContent = `Status: Input finalized as: ${input.value} βœ”οΈ`;
  });

  form.addEventListener("submit", (event) => {
    event.preventDefault();
    status.textContent = `Status: Form submitted with input: ${input.value} πŸŽ‰`;
  });

  form.addEventListener("reset", () => {
    status.textContent = "Status: Form reset πŸ”„";
  });
</script>

Conclusion

The blur event in JavaScript is a powerful tool for handling actions when elements lose focus. By understanding and using this event, you can create more interactive and user-friendly web applications. Whether you are validating input fields, saving user data, or triggering specific actions, the blur event helps you ensure that your forms work smoothly and effectively.

Summary

  • What: The blur event fires when an element loses focus.
  • Why: It helps in validating input fields, saving data, and performing actions when an element is no longer active.
  • Where: Use it on any HTML element that can receive focus.
  • How: By adding an event listener for blur and handling the necessary actions.
  • When: Use it whenever you need to manage actions when an element loses focus and improve user experience.

Feel free to use the examples provided and modify them to suit your needs. Happy coding! πŸŽ‰

What are JavaScript Browser Events?

JavaScript browser events are key to creating interactive web applications. These events are actions or occurrences detected by the browser, such as user interactions, document changes, or window modifications. By responding to events like clicks, key presses, and form submissions, developers can enhance user experience and functionality.

This comprehensive list of JavaScript browser events is a valuable reference for developers. It covers a wide range of events, from mouse and keyboard actions to document and window changes. Understanding and handling these events is essential for building responsive and engaging web applications, ensuring a seamless and intuitive user experience.

See List of all JavaScript Browser Events – Cheat Sheet

  • Document events:
    • ended
    • error
    • loadeddata
    • loadedmetadata
    • loadstart
    • pause
    • play
    • playing
    • progress
    • ratechange
    • seeked
    • seeking
    • stalled
    • suspend
    • timeupdate
    • volumechange
    • waiting
    • emptied
    • durationchange
    • cuechange
    • change
    • canplaythrough
    • canplay
    • abort
    • DOMContentLoaded
  • Window events:
    • afterprint
    • beforeprint
    • beforeunload
    • error
    • hashchange
    • load
    • message
    • offline
    • online
    • pagehide
    • pageshow
    • popstate
    • resize
    • scroll
    • storage
    • unload
  • Form events:
    • submit
    • select
    • reset
    • invalid
    • input
    • focus
    • change
    • blur
  • Keyboard events:
    • keyup
    • keypress
    • keydown
  • Mouse events:
    • wheel
    • mouseup
    • mouseover
    • mouseout
    • mousemove
    • mouseleave
    • mouseenter
    • mousedown
    • dblclick
    • contextmenu
    • click

Leave a Reply