JSFiddle - React, Tailwind, and code Playground
by lborgman
HTML
<button id="btn0">
Click to focus me!
</button>
<button id="btn1">
Test
</button>
<label>
<input id="chk" type="checkbox">
Use .preventDefault();
</label>
<label>
<input id="chk-wait" type="checkbox">
Wait before .preventDefault();
</label>
<div>
NOTE: .preventDefault() should prevent focus change to "Test" on mousedown. This fails in Crome (79.0.3945.130 (Official Build) (64-bit) and Firefox (72.0.1 (64-bit))) if there is a promise wait before .preventDefault().
</div>
<h3>
Output (newest first):
</h3>
<section id="output">
</section>
CSS
#output {
padding: 1rem;
background: yellow;
}
:focus {
background: red;
}
label {
display: inline-block;
}
JavaScript
function waitSeconds(sec) {
return new Promise(resolve => {
function ready() {
resolve(sec);
}
setTimeout(ready, sec * 1000);
})
}
const btn0 = document.getElementById("btn0");
const btn1 = document.getElementById("btn1");
const output = document.getElementById("output");
const chk = document.getElementById("chk");
const chkWait = document.getElementById("chk-wait");
btn0.focus();
btn1.addEventListener("mousedown", async (evt) => {
const trg = evt.target;
const chkTxt = chk.checked ? "checked" : "NOT checked";
write("------ " + chkTxt + " (" + (new Date()).toLocaleTimeString() + ")");
if (chkWait.checked) {
trg.style.background = "yellow";
await waitSeconds(1.5);
trg.style.background = null;
}
if (chk.checked) evt.preventDefault();
checkFocus(trg);
flush();
})
let buffer;
function write(txt) {
buffer = buffer || document.createElement("p");
const div = document.createElement("div");
div.appendChild(document.createTextNode(txt));
buffer.appendChild(div);
}
function flush() {
const first = output.firstElementChild;
console.log("first", first)
output.insertBefore(buffer, first);
buffer = undefined;
}
function isFocused(target) {
const activeTxt = document.activeElement.textContent;
write("activeElement: " + activeTxt);
const targetTxt = target.textContent;
write("target: " + targetTxt);
if (!document.hasFocus()) return false;
if (!document.activeElement) return false;
const targetContains = target.contains(document.activeElement);
write("targetContains activeElement: " + targetContains);
if (targetContains) {
// write("target.contains(document.activeElement)")
return true;
}
return false;
}
function checkFocus(trg) {
const hasFocus =...