0

I have input and div

    <input id="input" />
    <div id="div">Hello</div>

on this input i attached focus out event so whenever i click outside of the input - it gets triggered. That means also when i click on the div itself, the focus out event gets triggered.


let input = document.getElementById('input');
console.log(input);
input.addEventListener('focusout', () => {
    alert('focusout event happening');
})

but i need - when i click on this div - focus out event to not be triggered on the input itself.

How can i do this ?

peckoski
  • 105
  • 6

1 Answers1

0

An event handler can accept an event as an object. Events do include the DOM node that they were triggered by as their target property - however in case of a FocusEvent that is the element that lost focus, in that case your input. So this won't help. However FocusEvent does have an additional property called relatedTarget. In case of a focusout-Event this includes the DOM node that received the focus.

Using this, you could do something along those lines:

input.addEventListener('focusout', e => {
    if (e.relatedTarget === document.getElementById("div")) {
        alert('FocusOut event triggered by div');
    } else {
        alert('FocusOut event triggered by other element');
    }
})

However a focusout event is not canceable, so you cannot prevent the focus change from happening.

You CAN hoever re-focus the input right after the focus change by calling document.getElementById("input").focus()

Johannes H.
  • 5,875
  • 1
  • 20
  • 40