JSFiddle - React, Tailwind, and code Playground

by lborgman

HTML

<input type="text" id="doc-input" />

CSS

#bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(30, 30, 30, 0.7);
    z-index: 100;
}
#form {
    margin-top: 50px;
    margin-left: auto;
    margin-right: auto;
    width: 200px;
    height: 200px;
    background: white;
}

JavaScript

var docInp = document.getElementById("doc-input");
docInp.focus();
docInp.addEventListener("keydown", function(ev){
    alert("Hi, it's me, docInp? Did u want something?");
});
var bgDiv = document.createElement("div");
bgDiv.setAttribute("id","bg");
var formDiv = document.createElement("div");
formDiv.setAttribute("id","form");
bgDiv.appendChild(formDiv);
formDiv.appendChild(document.createTextNode("Press ESC!"));

formInp = document.createElement("input");
formInp.setAttribute("type", "text");
formInp.setAttribute("tabindex", "0");
formInp.setAttribute("id", "formInp");
formDiv.appendChild(formInp);

formInp2 = document.createElement("input");
formInp2.setAttribute("type", "text");
formInp2.setAttribute("tabindex", "0");
formInp2.setAttribute("id", "formInp2");
formDiv.appendChild(formInp2);

formInp3 = document.createElement("input");
formInp3.setAttribute("type", "text");
formInp3.setAttribute("tabindex", "0");
formInp3.setAttribute("id", "formInp3");
formDiv.appendChild(formInp3);

document.body.appendChild(bgDiv);
formInp.focus();

bg.addEventListener("focusout", function(ev){
    ev.stopPropagation();
    var to = ev.relatedTarget;
    var from = ev.target;
    console.log("bg got focusout, to", to, "from", from);
    var inBg = false;
    n = 0;
    while (!inBg && to && n++ < 5) {
        to = to.parentNode;
        inBg = to === bgDiv;
    }
    if (!inBg) {
        console.log("trying to keep focus");
        from.focus();
        // setTimeout(function(){ from.focus(); }, 10);
    }
});

document.addEventListener("keydown", function(ev) {
    console.log("ev.keyCode", ev.keyCode);
    if (27 == ev.keyCode) {
        ev.stopPropagation();
        console.log("was 27");
        bgDiv.style.display = "none";
    }
});