JavaScript > Events > Common Events > focus and blur events
Focus and Blur Events in JavaScript
Learn how to use focus and blur events in JavaScript to enhance user interaction. This tutorial provides practical code snippets and detailed explanations.
Basic Focus and Blur Event Handling
This code snippet demonstrates the basic implementation of focus and blur events. When the input field receives focus (is clicked or tabbed to), its background color changes to yellow. When the input field loses focus (is clicked or tabbed away from), its background color changes back to white. The addEventListener method is used to attach event listeners to the input element. The this keyword refers to the input element within the event handler function.
<input type="text" id="myInput" value="Click here">
<script>
const inputElement = document.getElementById('myInput');
inputElement.addEventListener('focus', function() {
this.style.backgroundColor = 'yellow';
});
inputElement.addEventListener('blur', function() {
this.style.backgroundColor = 'white';
});
</script>
Concepts Behind the Snippet
The focus event fires when an element gains focus, typically through a mouse click or tabbing. The blur event fires when an element loses focus, meaning it's no longer the active element. These events are commonly used to provide visual feedback to users, validate input, or trigger other actions based on the element's focus state.
Real-Life Use Case: Input Validation
This snippet showcases a real-world use case for focus and blur events: input validation. When the username input loses focus, the code checks if the input field is empty. If it is, an error message is displayed. If the user refocuses on the input, the error message disappears. This provides immediate feedback to the user regarding the validity of their input, making the user interface more interactive and helpful.
<input type="text" id="username" placeholder="Enter username">
<span id="usernameError" style="color: red; display: none;">Username is required</span>
<script>
const usernameInput = document.getElementById('username');
const usernameError = document.getElementById('usernameError');
usernameInput.addEventListener('blur', function() {
if (this.value.trim() === '') {
usernameError.style.display = 'inline';
} else {
usernameError.style.display = 'none';
}
});
usernameInput.addEventListener('focus', function() {
usernameError.style.display = 'none';
});
</script>
Best Practices
setTimeout or requestAnimationFrame.blur event triggers frequent updates or calculations. This helps to prevent unnecessary processing and improve performance.
Interview Tip
When asked about focus and blur events in an interview, be prepared to discuss their purpose, common use cases (like input validation and providing visual feedback), and any potential performance considerations. Also, mention accessibility best practices. Being able to explain the difference between focus and focusin as well as blur and focusout will demonstrate a deeper understanding.
When to Use Them
Use focus and blur events when you need to respond to changes in the active state of an element. This is particularly useful for:
Memory Footprint
Adding event listeners, including those for focus and blur events, does consume memory. It's important to remove event listeners when they are no longer needed, especially for dynamically created elements. You can remove event listeners using the removeEventListener method. Failing to do so can lead to memory leaks, especially in long-running applications.
Alternatives
While focus and blur events are commonly used, there are alternatives depending on the specific use case. For example:input event can be used to detect changes in the value of an input field in real-time, providing more immediate feedback than the blur event.change event can be used for input fields but only fires when the value has changed and the element loses focus.
Pros
addEventListener.
Cons
blur event can fire more frequently than expected, especially when dealing with complex UI interactions. Debouncing may be required.
Focusin and Focusout Events
It's important to note that there are also the focusin and focusout events. These are similar to focus and blur, but they bubble up the DOM tree. This means that if you attach a focusin listener to a parent element, it will be triggered when any of its child elements receive focus. This can be useful for event delegation.
document.getElementById('myDiv').addEventListener('focusin', function(event) {
console.log('Focus entered element: ' + event.target.tagName);
});
FAQ
-
What is the difference between
focusandfocusinevents?
Thefocusevent does not bubble, while thefocusinevent does bubble up the DOM tree. Usefocusinwhen you need to handle focus events on parent elements. -
How can I prevent the default behavior of a focus or blur event?
You can useevent.preventDefault()within the event handler to prevent the default behavior. However, preventing the default behavior of focus or blur events is generally not recommended as it can negatively impact usability and accessibility. -
Are focus and blur events supported in all browsers?
Yes,focusandblurevents are supported by all major browsers.