Tracking Element Focus Recipients After Blur Event
Problem:
Consider an HTML input box with an attached blur function. Is there a method within this function to identify the element that triggered the blur event (i.e., received focus)?
Example:
<code class="html"><input id="myInput" onblur="function() { ... }"></code>
If a span with ID "mySpan" is clicked after the input element has focus, how can the blur function determine that it was mySpan that was focused?
Solution:
According to the UI Events specification, the relatedTarget property of the event can be used:
For Blur Events:
Code Example:
<code class="javascript">function blurListener(event) { event.target.className = 'blurred'; if (event.relatedTarget) event.relatedTarget.className = 'focused'; } [].forEach.call(document.querySelectorAll('input'), function(el) { el.addEventListener('blur', blurListener, false); });</code>
In this example, blurred elements will turn orange, while focused elements will turn lime.
The above is the detailed content of Can Blur Events Identify the Element That Triggered the Event?. For more information, please follow other related articles on the PHP Chinese website!