JSFiddle - React, Tailwind, and code Playground
HTML
<div id="keypress">
<div>Key Press</div>
<div class="character"> </div>
<div>
<span class="key shiftKey">Shift</span>
<span class="key ctrlKey">Control</span>
<span class="key altKey">Alt</span>
<span class="key metaKey">Meta</span>
</div>
</div>
<div id="keydown">
<div>Key Down</div>
<div class="character"> </div>
<div>
<span class="key shiftKey">Shift</span>
<span class="key ctrlKey">Control</span>
<span class="key altKey">Alt</span>
<span class="key metaKey">Meta</span>
</div>
</div>
<div id="keyup">
<div>Key Up</div>
<div class="character"> </div>
<div>
<span class="key shiftKey">Shift</span>
<span class="key ctrlKey">Control</span>
<span class="key altKey">Alt</span>
<span class="key metaKey">Meta</span>
</div>
</div>
CSS
.key {
width:200px;
height:200px;
border: 1px solid;
}
.selected {
background-color: greenyellow!important;
}
JavaScript
function RespondToKeyEvent(parentElementId, event){
var parentElement = document.getElementById(parentElementId);
parentElement.querySelector('.character').innerText = event.which;
ApplyOrRemoveSelectedClass(parentElement, '.shiftKey', event.shiftKey);
ApplyOrRemoveSelectedClass(parentElement, '.ctrlKey', event.ctrlKey);
ApplyOrRemoveSelectedClass(parentElement, '.altKey', event.altKey);
ApplyOrRemoveSelectedClass(parentElement, '.metaKey', event.metaKey);
}
function ApplyOrRemoveSelectedClass(parentElement, querySelector, selected){
var element = parentElement.querySelector(querySelector);
if(selected){
element.classList.add('selected');
}
else{
element.classList.remove('selected');
}
}
function stopBubblingEvent(event) {
event.cancelBubble = true;
event.preventDefault();
event.stopPropagation();
event.returnValue = false;
return false;
}
plkplkplkplkreturn stopBubblingEvent(event);
});
document.addEventListener("keydown", function (event) {
RespondToKeyEvent('keydown', event);
return stopBubblingEvent(event);
});
document.addEventListener("keyup", function (event) {
RespondToKeyEvent('keyup', event);
return stopBubblingEvent(event);
});