JSFiddle - React, Tailwind, and code Playground

Detecting focusout on a container

by tonytlwu

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<div class="container">
  <input type="text" placeholder="Something to focus on" />
  <div id="target" class="targetable">
    <p>A paragraph with some text and <a href="#">a link</a> for testing.</p>
    <p>Another paragraph</p>
    <input type="text" placeholder="Something to focus on" />
    <button>Just a button</button>
  </div>
  <input type="text" placeholder="Something to focus on" />
</div>

<pre id="debug">Trigger count: </pre>

CSS

.targetable {
  border: 1px solid #999;
  padding: 10px;
  margin: 10px;
}

JavaScript

$('#target').focusout(function(event) {
	// If the target receiving the focus is within the container, do nothing
	if (event.currentTarget.contains(event.relatedTarget)) {
	  return;
  }
  
	$('#debug').append('+');
});