Reputation: 1764
I'm using a jQuery plugin to replace select-boxes and I want to add a hidden input if selecting an item while the shift key is held when pressing enter. My problem is that the select plugin listener is happening before my keydown listener. Is there a way to make my first on()
below execute before my second on()
? Or is there a way to check inside the second on()
if the shift key is being held? e.shiftKey
gives me undefined
if I put it inside the second on()
. Thanks for ideas!
var shiftHeld = false;
$(document).on('keydown', function(e) {
if(e.which == 13) {
shiftHeld = e.shiftKey;
}
});
$menu = $('#menu').select2();
$menu.on('select2:close', function (e) {
if(shiftHeld) { $('#form').append('<input type="hidden" name="shift" value="1" />'); }
form.submit();
});
Upvotes: 0
Views: 1808
Reputation: 9887
The event model in Javascript descends from the document element to the focused element (capturing phase), then ascends again (bubbling phase).
document -> element -> document
------- CAPTURE ------|----- BUBBLING ------
You normally capture events in the bubbling phase (target element -> document). Take a look at What is event bubbling and capturing? and https://www.quirksmode.org/js/events_order.html
However, you can also set a listener to the capturing phase, so you can react to a child event from a parent element before the child notices the event.
To do so:
function handleShift(e) { shiftHeld = e.shiftKey }
document.addEventListener("keydown", handleShift, true);
document.addEventListener("keyup", handleShift, true);
This handler will be called BEFORE the event arrives to your element. Note the last parameter "true" to indicate you want to set the handler in the capturing phase.
Upvotes: 1
Reputation: 1206
Just add keyup to your shift check so the shiftHeld value is updated when shift is released:
var shiftHeld = false;
$(document).on('keydown keyup', function(e) {
if(e.which == 13) {
shiftHeld = e.shiftKey;
}
});
function closeHandler() {
if(shiftHeld) { $('#form').append('<input type="hidden" name="shift" value="1" />'); }
form.submit();
}
$menu.on('select2:close', setTimeout("closeHandler()",100));
Upvotes: 0