Home  >  Article  >  Web Front-end  >  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
Barbara StreisandOriginal
2024-10-19 14:43:30903browse

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>

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>

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!

Statement:
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