I have a page with multiple elements which are made draggable via JQuery-ui.
I want to make it so that when the user clicks on one of these elements, and presses any key, another function will be called for further processing (and checking the keycode)
Given the HTML:
<div id="drag-el" class="drsel"> </div>
If I use the javascript:
$(document).ready(function() {
$('.drsel').each(function() {
$(this).on('keyup', function(e) {
alert("Keyup event");
});
});
});
Then the event will never ever fire.
Instead I have to use the javascript:
$(document).ready(function() {
$(document).on('keyup', 'body, .drsel', function() {
alert("Keyup event");
});
});
However, in this case the event will only fire if the user clicks the main body (i.e. not the draggable element), then clicks the element, then presses a key.
Another issue is that the event will then fire if the user presses a key when focus is on the document body, but the event will never fire if 'body' is not included in the selector.
Here is a jsfiddle that you can play around with.
Is there a way around this? I even went so far as to add
$(document.body).focus();
to the ready function, but found that only works for the first time the page loads - if the page reloads, then that solution no longer helps.
As we said in comments, you can workaround the issue of the focus element with a click or mousedown event:
https://jsfiddle.net/mhobd21k/3/
$('.drsel').on('click', function(e){
$(this).focus();
});
OR
$('.drsel').on('mousedown', function(e){
$(this).focus();
});