How do you trap the keypress or key down event on a DIV element (using jQuery)?
What is required to give the DIV element focus?
This question is related to
javascript
jquery
html
scripting
keypress
tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab
key). Read MDN Web Docs for full reference.
$( "#division" ).keydown(function(evt) {
evt = evt || window.event;
console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
width: 90px;
height: 30px;
background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="division" tabindex="0"></div>
_x000D_
var el = document.getElementById("division");
el.onkeydown = function(evt) {
evt = evt || window.event;
console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
width: 90px;
height: 30px;
background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
Here example on plain JS:
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
outline: none;_x000D_
}
_x000D_
<div _x000D_
id="myDiv"_x000D_
tabindex="0"_x000D_
>_x000D_
Press me and start typing_x000D_
</div>
_x000D_
(1) Set the tabindex
attribute:
<div id="mydiv" tabindex="0" />
(2) Bind to keydown:
$('#mydiv').on('keydown', function(event) {
//console.log(event.keyCode);
switch(event.keyCode){
//....your actions for the keys .....
}
});
To set the focus on start:
$(function() {
$('#mydiv').focus();
});
To remove - if you don't like it - the div
focus border, set outline: none
in the CSS.
See the table of keycodes for more keyCode
possibilities.
All of the code assuming you use jQuery.
#Source: Stackoverflow.com