• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Basics / The onblur Event in JavaScript

The onblur Event in JavaScript

The onblur Event in JavaScript

The JavaScript onblur event is triggered when an element loses focus, such as when a user clicks outside of an input field or tabs away from a text area. This event can be useful for validating form input, hiding or showing additional content, or triggering other actions.

Here is an example of using the onblur event to check if a form input is empty:

<form>
  <label for="name">Name:</label>
  <input type="text" id="name" onblur="validateName()">
  <span id="nameError"></span>
</form>
function validateName() {
  var name = document.getElementById("name").value;
  if (name == "") {
    document.getElementById("nameError").innerHTML = "Name is required.";
  } else {
    document.getElementById("nameError").innerHTML = "";
  }
}

In this example, the validateName() function is called when the user tabs away or clicks outside of the “Name” input field. If the input is empty, an error message is displayed next to the input field.

Another example of using onblur event is when you want to show a message to the user when they click outside of a specific element

<div onblur="showMessage()">
   <p>Click anywhere outside of this div to show a message</p>
</div>
function showMessage() {
  alert("You clicked outside of the div");
}

In this example, when the user clicks outside of the div, the showMessage() function is called, and an alert is displayed with the message “You clicked outside of the div.”

It’s important to note that onblur event is supported by all major browsers including Internet Explorer, Google Chrome, and Mozilla Firefox.

Basics

Related Snippets:

  • JavaScript Variables Explained
  • Commonly Used JavaScript Statements
  • How To Automatically Redirect To Another URL (JavaScript and jQuery)
  • The JavaScript function Math.floor()

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us