Home >Web Front-end >JS Tutorial >How to Identify the Target of a Blur Event in JavaScript
Identifying the Target of a Blur Event
When an HTML input field loses focus due to a user clicking or tabbing away, a 'blur' event is triggered. If you want to determine which element caused this focus loss, this article presents a solution using the 'relatedTarget' property.
'relatedTarget' Property
The 'relatedTarget' property of a blur event references the element that gained focus after the initial element relinquished it. This property effectively pinpoints the element that triggered the blur.
Example Implementation
Consider the following JavaScript function attached to an input field:
<code class="javascript">function blurListener(event) { if (event.relatedTarget) { event.relatedTarget.className = 'focused'; } }</code>
In this script, whenever the input field loses focus, the code checks if there is a 'relatedTarget'. If so, the 'focused' class is applied to it, highlighting the element that gained focus.
The above is the detailed content of How to Identify the Target of a Blur Event in JavaScript. For more information, please follow other related articles on the PHP Chinese website!