Keybindings to div elements
Add keyBind to any DOM element
author(s):
Ldmarz
HTML
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<h3 class="titulo">
Presiona en los elementos y presiona las flechas
</h3>
<div id="banner-message" class="banner-message" tabindex="1">
<p id="result">Un elemento</p>
</div>
<div id="banner-message2" class="banner-message" tabindex="1">
<p id="result2">otro Elemento</p>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.titulo {
color: #fff;
}
.banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
margin-bottom: 20px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
.banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
.banner-message.alt button {
background: #fff;
color: #000;
}
JavaScript
// find elements
var banner = $("#banner-message")
bindTeclas("#banner-message", "#result");
bindTeclas("#banner-message2", "#result2");
// handle click and add class
function bindTeclas(ele, idResult) {
$(ele).keydown(function(e) {
switch(e.which) {
case 37: // left
result(idResult, 'left');
break;
case 38: // up
result(idResult, 'up');
break;
case 39: // right
result(idResult, 'right');
break;
case 40: // down
result(idResult, 'down');
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
}
function result(idResult, clicked) {
$(idResult).html(clicked);
}