Testing Focus(in/out) events
by Admiral Potato
HTML
<form
id="a"
>
<div><input type="text"></div>
<div><input type="radio" name="cake"></div>
</form>
<form
id="b"
>
<div><input type="text"></div>
<div>
<select>
<options>there are no options</options>
</select>
</div>
</form>
<div>
<pre id="output"></pre>
</div>
CSS
form, div {
padding: 8px;
background-color: #9998;
border: 2px solid #999;
margin: 2px 0;
}
form:focus-within {
background-color: #f908;
}
JavaScript
const formA = document.getElementById('a')
const formB = document.getElementById('b')
const outputPre = document.getElementById('output')
// Good reference if I really need to see whether focus is
// lost from the parent, and not just refocusing inside:
// https://danburzo.ro/focus-within/
const createFocusChangeHandler = (target) => {
return (event) => {
console.log(event);
const result = {
type: event.type,
target: target.id,
didFocusActuallyChange: !target.contains(event.relatedTarget)
}
outputPre.innerHTML += `${JSON.stringify(result, null, ' ')}\n`
}
}
const handlerA = createFocusChangeHandler(formA)
const handlerB = createFocusChangeHandler(formB)
formA.addEventListener('focusin', handlerA)
formA.addEventListener('focusout', handlerA)
formB.addEventListener('focusin', handlerB)
formB.addEventListener('focusout', handlerB)