0

I want to fire a function when my focus is out with tab key of a div #search no matter what is around it. I can't figure out how to do it. At the moment my console.log() fires when I focus out of my inputs in my #search div.

$("#search").focusout(function () {
   if ($(this).has(document.activeElement).length == 0) {
       console.log('OUT'); // need to fire when i'm on Link2 or button: "random" (with tab key, not only click)
   }
});
*:focus {
  outline: 4px solid red;
}

#search {
  margin: 30px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">Link1</a>
<a href="#">Link2</a>


<div id="search">
  <input type="text">
  <button>Search</button>
</div>


<button>Random</button>
Hotgeart
  • 384
  • 10
  • 34

2 Answers2

0

Try using onblur event for input:

$("body").on("blur","input",function() {
 console.log('OUT');
});
*:focus {
  outline: 4px solid red;
}

#search {
  margin: 30px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">Link1</a>
<a href="#">Link2</a>


<div id="search">
  <input type="text">
  <button>Search</button>
</div>


<button>Random</button>
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
0

Here's the solution:

$("#search, #search *").blur(function(e) {
  if (!$(e.relatedTarget).is("#search, #search *")) {
    console.log('OUT');
  }
});
*:focus {
  outline: 4px solid red;
}

#search {
  margin: 30px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">Link1</a>
<a href="#">Link2</a>


<div id="search">
  <input type="text">
  <button>Search</button>
</div>


<button>Random</button>
Hotgeart
  • 384
  • 10
  • 34