3

Feel free to edit the question title if you find something better.


I am writing a little plugin for my website,

var main = document.getElementById("main"),
  fakeInput = document.getElementById("fakeInput"),
  zone = document.getElementById("zone"),
  input = document.getElementById("input");

main.addEventListener("focusin", function() {
  zone.style.display = "block";
});
main.addEventListener("focusout", function() {
  zone.style.display = "none";
});
#main {
  width: 200px;
}
#fakeInput {
  background: blue;
  height: 22px;
}
#zone {
  background-color: red;
  height: 100px;
  text-align: center;
}
click in the blue zone :<br>
<div id="main" tabindex="-1">
  <div id="fakeInput"></div>
  <div id="zone" style="display:none">
    <p>Click in the input :</p>
    <input id="input" type="text" />
  </div>
</div>

when I click on it, it opens (great !). I can click (almost) anywhere, the "focusout" event is not triggered. Almost, because the input child steal the focus to its parent.

I read here : http://www.quirksmode.org/dom/events/blurfocus.html

focusin and focusout

Fire at the same time as focus and blur, but bubble

In my example, It seems that the focusin event of the input field never reach its parent.

I am looking for a way to fix this, any hints ?

Apolo
  • 3,844
  • 1
  • 21
  • 51

2 Answers2

1

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus from parent elements (in other words, it supports event bubbling).

Therefore there is a difference between this.

main.addEventListener("focusin", function() {
  zone.style.display = "block";
});
main.addEventListener("focusout", function() {
  zone.style.display = "none";
});

And this.

main.addEventListener("focus", function() {
  zone.style.display = "block";
});
main.addEventListener("blur", function() {
  zone.style.display = "none";
});

See this JSFiddle.

Enijar
  • 6,387
  • 9
  • 44
  • 73
  • In your JSFiddle, when I click the blue zone then the input, it still lose the focus (the red zone disapear). Is it only for me ? – Apolo Dec 23 '15 at 09:00
0

In my example, It seems that the focusin event of the input field never reach its parent.

In fact it does. Try to add some debug:

main.addEventListener("focusin", function(event) {
  console.log('focusin', event.target)
  zone.style.display = "block";
});
main.addEventListener("focusout", function(event) {
  console.log('focusout', event.target)
  zone.style.display = "none";
});

and you'll see enter image description here