JSFiddle - React, Tailwind, and code Playground

by yonran

HTML

<div tabindex=0>tabindex=0</div>

<div id=messages>
The <code>div</code> has the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#sequential-focus-navigation-and-the-tabindex-attribute">tabindex focus flag</a> set (previously known affectionately as “specially focusable”). What this means is that you can <span class=kbd>Tab</span> to it and activate it by pressing <span class=kbd>Enter</span> (it has an <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#activation-behavior">activation behavior</a> even though the behavior is a no-op). Pressing <span class=kbd>Enter</span> should cause a synthetic <code>click</code> to be dispatched. This works properly in Opera 11.60 but fails in Firefox 11 and Chrome 19 <br>
</div>

CSS

strong {
    font-weight: bold;
}

[tabindex] {
    display: inline-block;
    padding: .5em;
    border: 1px solid black;
    background: #87e0fd; /* Old browsers */
    background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#87e0fd), color-stop(40%,#53cbf1), color-stop(100%,#05abe0)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%); /* IE10+ */
    background: linear-gradient(top, #87e0fd 0%,#53cbf1 40%,#05abe0 100%); /* W3C */
}
.kbd {
    display: inline-block;
    padding: 3px 5px;
    color: 
    black;
    font-family: Monaco,"Courier New","DejaVu Sans Mono","Bitstream Vera Sans Mono",monospace;
    font-size: 11px;
    background: #FEFEFE;
    background: -moz-linear-gradient(#FEFEFE,#E7E7E7);
    background: -webkit-linear-gradient(#FEFEFE,#E7E7E7);
    border: 1px solid #CFCFCF;
    border-radius: 2px;
}

JavaScript

var messages = document.getElementById("messages");
var focusable = document.querySelector("[tabindex]");
var clickHappened = false, isDoingKeyPress = false;
focusable.addEventListener("click", function(event) {
    if (event.button != 0)
        return;
    if (! isDoingKeyPress)
        messages.innerHTML += new Date + ": Got click!<br>";
    clickHappened = true;
}, false);
focusable.addEventListener("keypress", function(event) {
    if (event.keyCode !== 13) return;
    if (event.repeat) return;
    clickHappened = false;
    isDoingKeyPress = true;
    setTimeout(function() {
        var clickInfo = clickHappened ? "and click" : "<strong>but no click!</strong>"
        messages.innerHTML += new Date + ": Got enter keypress " + clickInfo + "<br>";
        isDoingKeyPress = false;
    }, 1);
}, false);