How to bind keyboard events to div elements? – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and jquery. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about How to bind keyboard events to div elements?.
Problem :
Is there a way to listen to keyboard events on a DIV element?
My code:
<div id="div" style="height:50px" class="ui-widget-content"></div>
<input id="input">
$('#div,#input').keyup(function(event){
console.log(event.keyCode);
});
Actually, the code triggers only for the input, can I handle it for the div?
Solution :
You can add a tabindex
in that div
to catch keyboard events like this
<div id="div" style="height:50px" class="ui-widget-content" tabindex="0"></div>
Like answered here.
Add a tabindex
and it should work
<div id="div" style="height:50px;" class="ui-widget-content" tabindex="1"></div>
Why not place the input inside the div and then simply find $(‘#input’).closest(‘div’) ?
Otherwise, if your example is a pattern of how your inputs relate to your divs then simply $(‘#input’).prev() ?