field and I need to clear it when this field loses focus (whiech means the user ...">

Blur event.relatedTarget returns null

I have a <input type="text"> field and I need to clear it when this field loses focus (whiech means the user clicked somewhere on the page). But there is one exception. The input text box should not be cleared when the user clicks on a specific item.

I tried using event.relatedTarget to detect if the user clicked not only somewhere, but also on my specific <div> .

However, as you can see in the snippet below, this just doesn't work. event.relatedTarget always returns null !

 function lose_focus(event) { if(event.relatedTarget === null) { document.getElementById('text-field').value = ''; } } 
 .special { width: 200px; height: 100px; background: #ccc; border: 1px solid #000; margin: 25px 0; padding: 15px; } .special:hover { cursor: pointer; } 
 <input id="text-field" type="text" onblur="lose_focus(event)" placeholder="Type something..."> <div class="special">Clicking here should not cause clearing!</div> 
+7
javascript events onblur lost-focus
source share
1 answer

Short answer: add the attribute tabindex="0" to the element that should appear in event.relatedTarget .

Explanation: event.relatedTarget contains the element that received focus. And the problem is that your particular div cannot get focus, because the browser believes that this element is not a button / field or some kind of control.

Here are the elements that can get focus by default:

  • <a> with the specified href attribute
  • <link> with the specified href attribute
  • <button> elements
  • <input> elements that are not hidden
  • <select> elements
  • <textarea> elements
  • <menuitem> elements
  • elements with attribute draggable
  • <audio> and <video> with the specified controls attribute

So event.relatedTarget will contain the above elements when onblur happens. All other elements will not be counted, and clicking on them will place null in event.relatedTarget .

But that can be changed. You can "mark" a DOM element as an element that can receive focus with the tabindex attribute. Here is what the standard says:

The tabindex content tabindex allows authors to indicate that the element should be focusable, whether it should be accessible using sequential focus navigation and, optionally, suggest where the element appears in the sequential navigation navigation order.

So here is the corrected code snippet:

 function lose_focus(event) { if(event.relatedTarget === null) { document.getElementById('text-field').value = ''; } } 
 .special { width: 200px; height: 100px; background: #ccc; border: 1px solid #000; margin: 25px 0; padding: 15px; } .special:hover { cursor: pointer; } 
 <input id="text-field" type="text" onblur="lose_focus(event)" placeholder="Type something..."> <div tabindex="0" class="special">Clicking here should not cause clearing!</div> 
+10
source share

All Articles