Home >Web Front-end >JS Tutorial >How to Identify the Element Causing a Blur Event in HTML?
Determining the Target Element Triggering a Blur Event
When you handle blur events in an HTML input element, you may wonder how to identify the element that caused the focus shift. This article explores methods to obtain the ID of the triggering element.
In the provided code snippet, the blur event is attached to an input field. However, the challenge lies in determining the element that initiated the blur event, like a clickable span element.
Solution Using the relatedTarget Property
According to the Event Target specification, the relatedTarget property of the event object provides information about the element that gained focus after the blur event occurred. For blur events:
relatedTarget: event target receiving focus
Example:
function blurListener(event) { event.target.className = 'blurred'; if (event.relatedTarget) event.relatedTarget.className = 'focused'; } // Add blur listeners to all input elements [].forEach.call(document.querySelectorAll('input'), function(el) { el.addEventListener('blur', blurListener, false); });
By attaching this blur listener to input elements, you can identify the triggering element when it gains focus (className = 'focused') and change the className of the blurred input element to 'blurred'.
The above is the detailed content of How to Identify the Element Causing a Blur Event in HTML?. For more information, please follow other related articles on the PHP Chinese website!