Home > Web Front-end > JS Tutorial > body text

How to Identify the Element Causing a Blur Event in HTML?

DDD
Release: 2024-10-19 14:38:31
Original
675 people have browsed it

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

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);
});
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!