Home > Web Front-end > JS Tutorial > Can Blur Events Identify the Element That Triggered the Event?

Can Blur Events Identify the Element That Triggered the Event?

DDD
Release: 2024-10-19 14:42:02
Original
807 people have browsed it

Can Blur Events Identify the Element That Triggered the Event?

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>
Copy after login

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:

  • relatedTarget: Event target receiving focus.

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template