What is the usage of onblur event in JavaScript?

The onblur event in JavaScript triggers when an HTML element loses focus. This commonly occurs when users click away from an input field, tab to another element, or programmatically change focus.

Syntax

<element onblur="functionName()">
// OR
element.onblur = function() { /* code */ };
// OR
element.addEventListener('blur', function() { /* code */ });

Example: Input Field Validation

<!DOCTYPE html>
<html>
<body>
    <p>Enter your email and click outside the field:</p>
    <input type="text" id="emailInput" placeholder="Enter email" onblur="validateEmail(this)">
    <p id="message"></p>
    
    <script>
        function validateEmail(input) {
            const message = document.getElementById('message');
            if (input.value.includes('@')) {
                input.style.backgroundColor = 'lightgreen';
                message.textContent = 'Valid email format';
                message.style.color = 'green';
            } else {
                input.style.backgroundColor = 'lightcoral';
                message.textContent = 'Please enter a valid email';
                message.style.color = 'red';
            }
        }
    </script>
</body>
</html>

Example: Using addEventListener

<!DOCTYPE html>
<html>
<body>
    <input type="text" id="myInput" placeholder="Type something...">
    <p id="status"></p>
    
    <script>
        const input = document.getElementById('myInput');
        const status = document.getElementById('status');
        
        input.addEventListener('blur', function() {
            if (this.value.length > 0) {
                status.textContent = 'Input saved: ' + this.value;
                status.style.color = 'blue';
            } else {
                status.textContent = 'Field is empty';
                status.style.color = 'orange';
            }
        });
    </script>
</body>
</html>

Common Use Cases

The onblur event is commonly used for:

  • Form validation: Check input values when users move to the next field
  • Auto-save: Save draft content when user leaves a textarea
  • Formatting: Format phone numbers, dates, or currency fields
  • Visual feedback: Change styling to indicate completion status

onblur vs onfocus

Event When it triggers Common use
onblur Element loses focus Validation, save data
onfocus Element gains focus Clear placeholders, show help

Conclusion

The onblur event is essential for form validation and user experience improvements. Use it to validate inputs, provide feedback, or save data when users move away from form elements.

Updated on: 2026-03-15T23:18:59+05:30

941 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements