There are a few potential causes to your unresponsive behaviour:
- You're waiting for the
keyup
event, so no matter how fast they push the spacebar, your code will only respond when they release it. - Inside your event you are doing a few slow things which can also call a (tiny) delay
- finding elements by selector is slow, cache the results where possible
- In my example I avoided caching
$('.chosen-search input')
as I wasn't sure whether that dynamically changes. - Either way, to speed it up you could still cache:
var $chosenSearch = $('.chosen-search')
and then later on select with:$('input', $chosenSearch)
- In my example I avoided caching
- any code which executes in an event handler should return ASAP unless it intends on delaying the native behaviour (and other handlers)
- It's complete overkill in this case, but I've shown how you can use
setTimeout()
to execute your code asynchronously so that the event handler returns, and then your code executes. - whilst it might not be obvious why you'd do this, imagine that your code took (say) 1.5 seconds to execute - in that case there would be a 1.5second delay before every key the user typed showed up in the input box
- by sticking it in a
setTimeout()
you ensure that no matter how long your processing takes, the key will at least react first.
- It's complete overkill in this case, but I've shown how you can use
- finding elements by selector is slow, cache the results where possible
I hope that helps!
$(function() {
// cache the selectors to avoid re-scanning inside the event handler
var $inputSwitch = $('#inputSwitch');
var $cbProduct = $('#cbProduct');
var $barcodeIn = $('#barcodeIn');
// Not strictly necessary, but saves the messiness of callback-in-callback
function swapContext() {
// SHOW CHOSEN MENU INSTEAD OF BARCODE INPUT BECAUSE WE'RE TYPING A PRODUCT NAME
$inputSwitch.trigger("click");
// AUTOMATICALLY OPEN THE CHOSEN MENU
$cbProduct.trigger("chosen:open");
// GRAB WHAT WAS ENTERED INTO THE BARCODE INPUT
var input = $("#barcodeIn").val()+" ";
// ENTER THE INPUT TEXT INTO THE CHOSEN SELECT MENU
$(".chosen-search input").val(input);
// CLEAR THE BARCODE INPUT BECAUSE WE"RE USING THE CHOSEN SELECT MENU INSTEAD
$barcodeIn.val("");
}
$("input#barcodeIn").on('keydown', function(e){
// CHECK FOR SPACEBAR PRESS IN THE BARCODE INPUT FIELD
if (e.keyCode == 32) {
// Ensures we can return from the handler quickly
setTimeout( swapContext, 0 );
return false;
}});
});
Since you're also new to Javascript, note that the
var
statements below are local to the wrapper function, definitely avoid using globals in JS - better to learn the slightly odd ways of avoiding them (and in the process, learn many cool tricks with javascript!)