Skip to content

Instantly share code, notes, and snippets.

@ldmarz
Last active July 31, 2018 01:10
Show Gist options
  • Save ldmarz/ed86caa7186b17858f4f200e8b636a1f to your computer and use it in GitHub Desktop.
Save ldmarz/ed86caa7186b17858f4f200e8b636a1f to your computer and use it in GitHub Desktop.
Capture keydown in multiple divs using JQuery Running sample at: http://jsfiddle.net/gh/gist/jQuery/3.3.1/ed86caa7186b17858f4f200e8b636a1f
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;
}
<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>
// 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);
}
name: Keybindings to div elements
description: Add keyBind to any DOM element
authors:
- Ldmarz
resources:
- https://code.jquery.com/jquery-3.3.1.min.js
normalize_css: no
wrap: b
panel_js: 0
panel_css: 0
Just for name purpose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment