Javascript key listener press any key - javascript

I have a problem and I need to find a solution. :D
So here's my code:
var inputEnabled = true
var pressedKey = {}
window.addEventListener('keydown',function(e) {
pressedKey[e.keyCode || e.which] = true;
}, true);
window.addEventListener('keyup',function(e) {
pressedKey[e.keyCode || e.which] = false;
}, true);
function keyBinding() {
if (*my problem*) {
loadMenu()
}
if (inputEnabled == true) {
setTimeout("keyBinding()", 25)
}
}
What I want is that when any key is pressed I want to load a menu but I don't what how am I supposed to detect that key press.
Any help would be appreciated.

try this where *my problem* is in your code:
if(Objects.keys(pressedKey).length>0){ // checks if the object 'pressedKey' contains atleast one key
loadMenu()
}
However I recommend checking for the key press directly inside the key listener:
var inputEnabled = true
var menuLoaded = false; // this will indicate if the menu is loaded already
var pressedKey = {}
window.addEventListener('keydown', function (e) {
if(!menuLoaded){ // check if menu is not open
loadMenu()
menuLoaded = true
}
pressedKey[e.keyCode || e.which] = true;
}, true);
window.addEventListener('keyup', function (e) {
pressedKey[e.keyCode || e.which] = false;
}, true);

Related

Input eventListener on Enter Key goes on loop

I tried to set eventListener for two input fields. I can press Enter on every input field and it runs ProductInsertPhp() function which save data to MySQL base. When I click on Submit button everything works perfectly. If I press Enter on any input field it works OK only on the first time. But if I run script again it make two inserts. Again - three inserts to base. Every time it is raised by 1.
I tried code with getElementById but it works only with one field.
<script>
//Works ok but only for one field.
//var polaText = document.getElementById("txtInput");
//polaText.addEventListener('keyup', function (e) {
var inputText = document.querySelectorAll(".inpt");
inputText = addEventListener('keyup', function (e) {
e = e || window.event;
var isEsc = false;
var isEnter = false;
if ("key" in e) {
isEsc = (e.key === 'Escape' || e.key === 'Esc');
isEnter = (e.key === 'Enter');
}
if (isEsc) {
funct()
}
if (isEnter) {
//document.getElementById("submitButton").click();
ProductInsertPHP();
console.log("insert");
}
});
</script>
There is no error messages on console. What can I do to set it to only one insert?
There are two things off in your code.
You are not adding the eventListener to every inputText element, you are overriding the variable
your if() has one } too much
Check the comments in this corrected solution:
<script>
var inputText = document.querySelectorAll(".inpt");
// add for loop to query all inputs and add eventlistener to every one of them
inputText.forEach(inp => {
inp.addEventListener('keyup', (e) => {
e = e || window.event;
var isEsc = false;
var isEnter = false;
if ("key" in e) {
isEsc = (e.key === 'Escape' || e.key === 'Esc');
isEnter = (e.key === 'Enter');
}
if (isEsc) {
funct()
}
if (isEnter) {
//} <-- remove this
document.getElementById("submitButton").click();
ProductInsertPHP();
console.log("insert");
}
})
});
</script>

jquery scannerDetection ignoreIfFocusOn:'input' not working

I am using scannerDetection.js to scan barcodes:
jQuery(document).ready(function () {
$(document).scannerDetection({ ignoreIfFocusOn: 'input[type="text"]' });
});
But the above setting does not work, as every time i focus an input element the barcode is displayed in the input box, plus form submit event is fired as well.
I tried using: $(document).scannerDetection({ preventDefault:true });
Which works, but unfortunately it also blocks my keyboard input.
I tried using different versions of jquery library with no success.
According to this article, plug-in and its settings should work just fine.
I tried looking at the source code for the plugin, but cannot quite figure it out:
(function ($) {
$.fn.scannerDetection = function (options) {
// If string given, call onComplete callback
if (typeof options === "string") {
this.each(function () {
this.scannerDetectionTest(options);
});
return this;
}
// If false (boolean) given, deinitialize plugin
if (options === false) {
this.each(function () {
this.scannerDetectionOff();
});
return this;
}
var defaults = {
onComplete: false, // Callback after detection of a successfull scanning (scanned string in parameter)
onError: false, // Callback after detection of a unsuccessfull scanning (scanned string in parameter)
onReceive: false, // Callback after receiving and processing a char (scanned char in parameter)
onKeyDetect: false, // Callback after detecting a keyDown (key char in parameter) - in contrast to onReceive, this fires for non-character keys like tab, arrows, etc. too!
timeBeforeScanTest: 100, // Wait duration (ms) after keypress event to check if scanning is finished
avgTimeByChar: 30, // Average time (ms) between 2 chars. Used to do difference between keyboard typing and scanning
minLength: 6, // Minimum length for a scanning
endChar: [9, 13], // Chars to remove and means end of scanning
startChar: [], // Chars to remove and means start of scanning
ignoreIfFocusOn: false, // do not handle scans if the currently focused element matches this selector
scanButtonKeyCode: false, // Key code of the scanner hardware button (if the scanner button a acts as a key itself)
scanButtonLongPressThreshold: 3, // How many times the hardware button should issue a pressed event before a barcode is read to detect a longpress
onScanButtonLongPressed: false, // Callback after detection of a successfull scan while the scan button was pressed and held down
stopPropagation: false, // Stop immediate propagation on keypress event
preventDefault: false // Prevent default action on keypress event
};
if (typeof options === "function") {
options = { onComplete: options }
}
if (typeof options !== "object") {
options = $.extend({}, defaults);
} else {
options = $.extend({}, defaults, options);
}
this.each(function () {
var self = this, $self = $(self), firstCharTime = 0, lastCharTime = 0, stringWriting = '', callIsScanner = false, testTimer = false, scanButtonCounter = 0;
var initScannerDetection = function () {
firstCharTime = 0;
stringWriting = '';
scanButtonCounter = 0;
};
self.scannerDetectionOff = function () {
$self.unbind('keydown.scannerDetection');
$self.unbind('keypress.scannerDetection');
}
self.isFocusOnIgnoredElement = function () {
if (!options.ignoreIfFocusOn) return false;
if (typeof options.ignoreIfFocusOn === 'string') return $(':focus').is(options.ignoreIfFocusOn);
if (typeof options.ignoreIfFocusOn === 'object' && options.ignoreIfFocusOn.length) {
var focused = $(':focus');
for (var i = 0; i < options.ignoreIfFocusOn.length; i++) {
if (focused.is(options.ignoreIfFocusOn[i])) {
return true;
}
}
}
return false;
}
self.scannerDetectionTest = function (s) {
// If string is given, test it
if (s) {
firstCharTime = lastCharTime = 0;
stringWriting = s;
}
if (!scanButtonCounter) {
scanButtonCounter = 1;
}
// If all condition are good (length, time...), call the callback and re-initialize the plugin for next scanning
// Else, just re-initialize
if (stringWriting.length >= options.minLength && lastCharTime - firstCharTime < stringWriting.length * options.avgTimeByChar) {
if (options.onScanButtonLongPressed && scanButtonCounter > options.scanButtonLongPressThreshold) options.onScanButtonLongPressed.call(self, stringWriting, scanButtonCounter);
else if (options.onComplete) options.onComplete.call(self, stringWriting, scanButtonCounter);
$self.trigger('scannerDetectionComplete', { string: stringWriting });
initScannerDetection();
return true;
} else {
if (options.onError) options.onError.call(self, stringWriting);
$self.trigger('scannerDetectionError', { string: stringWriting });
initScannerDetection();
return false;
}
}
$self.data('scannerDetection', { options: options }).unbind('.scannerDetection').bind('keydown.scannerDetection', function (e) {
// If it's just the button of the scanner, ignore it and wait for the real input
if (options.scanButtonKeyCode !== false && e.which == options.scanButtonKeyCode) {
scanButtonCounter++;
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Add event on keydown because keypress is not triggered for non character keys (tab, up, down...)
// So need that to check endChar and startChar (that is often tab or enter) and call keypress if necessary
else if ((firstCharTime && options.endChar.indexOf(e.which) !== -1)
|| (!firstCharTime && options.startChar.indexOf(e.which) !== -1)) {
// Clone event, set type and trigger it
var e2 = jQuery.Event('keypress', e);
e2.type = 'keypress.scannerDetection';
$self.triggerHandler(e2);
// Cancel default
e.preventDefault();
e.stopImmediatePropagation();
}
// Fire keyDetect event in any case!
if (options.onKeyDetect) options.onKeyDetect.call(self, e);
$self.trigger('scannerDetectionKeyDetect', { evt: e });
}).bind('keypress.scannerDetection', function (e) {
if (this.isFocusOnIgnoredElement()) return;
if (options.stopPropagation) e.stopImmediatePropagation();
if (options.preventDefault) e.preventDefault();
if (firstCharTime && options.endChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = true;
} else if (!firstCharTime && options.startChar.indexOf(e.which) !== -1) {
e.preventDefault();
e.stopImmediatePropagation();
callIsScanner = false;
} else {
if (typeof (e.which) != 'undefined') {
stringWriting += String.fromCharCode(e.which);
}
callIsScanner = false;
}
if (!firstCharTime) {
firstCharTime = Date.now();
}
lastCharTime = Date.now();
if (testTimer) clearTimeout(testTimer);
if (callIsScanner) {
self.scannerDetectionTest();
testTimer = false;
} else {
testTimer = setTimeout(self.scannerDetectionTest, options.timeBeforeScanTest);
}
if (options.onReceive) options.onReceive.call(self, e);
$self.trigger('scannerDetectionReceive', { evt: e });
});
});
return this;
}
})(jQuery);
Any suggestions?
The original source code contained this line of code:
.bind('keypress.scannerDetection',function(e){
if (this.isFocusOnIgnoredElement()) return;
As you can see, it returns nothing. Just add false after the return statement:
.bind('keypress.scannerDetection',function(e){
if (this.isFocusOnIgnoredElement()) return true;
That worked for me. Although there is another issue:
barcode appears on focused input field

in keydown event when press key(40),(38),(13) any of them, then immediately other function will stop.and current function will start

if i press any key of them (38)(40)(13) then immediately other function will stop.and current function will start.like if i press key(40) then function verticalSlideUp() will start.after that if i press key (38) then immediately function verticalSlideDown() will be start.and this verticalSlideUp() function will be stop.
i need help to do this.
This is my jsfiddle.net code here
here is my js code :
var allowed = true;
$(document).keydown(function (e) {
if (e.repeat != undefined) {
allowed = !e.repeat;
}
if (!allowed) return;
allowed = false;
if (controlsEnabled)
{
if (e.keyCode == 38) {
allowed = true;
verticalSlideDown();
console.log("pressed key for Down : "+e.keyCode);
}
if (e.keyCode == 40) {
allowed = true;
verticalSlideUp();
console.log("pressed key for Up: "+e.keyCode);
}
if (e.keyCode == 13) {
allowed = true;
var div= $(".scroll-inner-container");
console.log("pressed key for stop : "+e.keyCode);
div.stop();
}
}
});
I assume those slide functions have some infinite loop. Maybe you can try to have some variable like functionFired and at the beginning of function setting some value and if that loop detects change it will break.

Prevent spaces in input field on keypress event

I'm using the following code to detect multiple keys on a keypress event:
var down = [];
$(document).keydown(function (e) {
down[e.keyCode] = true;
}).keyup(function (e) {
if (down[17] && down[32]) {
// Do something
}
down[e.keyCode] = false;
});
However, this hotkey (CTRL + SPACE) is meant to be used while an input field has focus. So whenever I press the key combination, it also adds a space to the input field.
How can I prevent this from happening? I've looked at ways to disable spaces in input (like this), but I can't figure out how to make it work inside my keypress event only.
You may try this. I hope it helps.
var down = [];
$(document).keydown(function (e) {
down[e.keyCode] = true;
}).keypress(function (e) {
if (down[17] && down[32]) {
var $sampleTextBox = $("input#sampleTextBox");
$sampleTextBox.val($sampleTextBox.val().replace(/\s/g, ''));
alert($sampleTextBox.val().length)
alert("Ctrl + Space Pressed!");
}
down[e.keyCode] = false;
}).keyup(function (e) {
if (down[17] && down[32]) {
var $sampleTextBox = $("input#sampleTextBox");
$sampleTextBox.val($sampleTextBox.val().replace(/\s/g, ''));
alert($sampleTextBox.val().length)
alert("Ctrl + Space Pressed!");
}
down[e.keyCode] = false;
});
--
Thanks,
SuperCoder
I ended up using a different approach, as MelanciaUK suggested.
On the keyup event, it removes the last character in the input field.
var down = [];
$(document).keydown(function (e) {
down[e.keyCode] = true;
}).keyup(function (e) {
if (down[17] && down[32]) {
// Do something
input = $(':focus');
input.val(function (index, value) {
return value.substr(0, value.length - 1);
});
}
down[e.keyCode] = false;
});
While it doesn't prevent the space from being added, it removes it immediately.

Detecting keystrokes without textboxes?

I have to use javascript to make links instead of for several unimportant reasons, and I want for it to behave like even though im not using it. Not the affects thats easy, but I want to be able to hold down shift while clicking to open a new window and to open it in a new tab if they are holding down ctrl. How would I do this? Also, it has to be compatible with IE9.
[edit] Also, this is going to be in an iframe
I guess you want something like this:
JSFiddle
http://jsfiddle.net/MXuVY/3/
JavaScript
var ctrlPressed = false;
$('#link').click(function () {
var link = 'http://stackoverflow.com/';
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
$(document).keydown(function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
​
HTML
<span id="link">Link to stackoverflow</span>​
​Version without jQuery
JSFiddle
http://jsfiddle.net/MXuVY/6/
JavaScript
function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
} else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
} else {
el['on' + eType] = fn;
}
}
var ctrlPressed = false,
a = document.getElementById('link'),
link = 'http://stackoverflow.com/';
addEvent(a, 'click', function () {
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
addEvent(document, 'keydown', function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
addEvent(document, 'keyup', function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
​
Bind a keystroke event listener to window or document and use it's callback function to do whatever you need.
If you use jquery, its a bit easier to make a more reliable keystroke listener, imho. http://blog.cnizz.com/2008/10/27/javascript-key-listener/
So, this is what you want: http://jsfiddle.net/DerekL/V8yzF/show
$("a").click(function(ev) {
if (ev.ctrlKey) { //If ctrl
window.open(this.attr("href"));
retrun false;
} else if (ev.shiftKey) { //If shift
window.open(this.attr("href"),"_blank", "width=400,height=300");
retrun false;
} else { //If nothing
//do nothing
}
});​

Categories

Resources