Home > Web Front-end > JS Tutorial > How to Identify the Initiator of a Blur Event Using the relatedTarget Property?

How to Identify the Initiator of a Blur Event Using the relatedTarget Property?

Barbara Streisand
Release: 2024-10-19 14:43:30
Original
1012 people have browsed it

How to Identify the Initiator of a Blur Event Using the relatedTarget Property?

Determining the Element that Initiated a Blur Event

Problem Statement:

When a blur event occurs on an HTML input element, how can we ascertain the ID of the element that triggered the loss of focus?

Answer:

To identify the element that prompted a blur event, we can leverage the relatedTarget property of the event. This property represents the target element that received focus following the blur.

For example, consider the following scenario:

<code class="html"><input id="myInput" onblur="onBlurEvent()" />
<span id="mySpan">Hello World</span></code>
Copy after login

When you lose focus from myInput by clicking mySpan, the onBlurEvent() function will be triggered. To determine the ID of the element that received focus (mySpan), we can access the relatedTarget property within the function:

<code class="js">function onBlurEvent() {
  console.log(event.relatedTarget.id); // Output: "mySpan"
}</code>
Copy after login

Additional Context:

This technique finds application in scenarios where you need to suppress the default blur behavior and prevent the autocompleter from disappearing if a specific element is clicked. To achieve this, you can check the event.relatedTarget.id within the onBlurEvent() function and ignore the blur event if it originated from the desired element.

The above is the detailed content of How to Identify the Initiator of a Blur Event Using the relatedTarget Property?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template