I have an <input type="text">
field and I need to clear it when this field loses focus (whiech means that user clicked somewhere on the page). But there is one exception. Input text field should't be cleared when user clicks on a specific element.
I tried to use event.relatedTarget
to detect if user clicked not just somewhere but on my specific <div>
.
However as you can see in snippet below, it simply doesn't work. event.relatedTarget
is always returning 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>
<button>
) are not focused when clicking. – People