I am currently designing a function for website owners to track what is most commonly searched/entered on their website. To do this I have got a basic function recording what keys are pressed though I want to push these letters into an array so it is easier to manage but I am encountering a problem, it only pushes the last key entered into the array. I am new to programming so go easy on my code :P
Here is the code with the malfunctioning dynamic array:
$(document).ready(function() {
$(document).keyup(function(objEvent) {
(objEvent) ? keyCode = objEvent.keyCode : keyCode = event.keyCode;
varArray = [];
varLetter = String.fromCharCode(keyCode);
console.log(varLetter);
varArray.push(varLetter);
});
});
Thanks in advance
-Alex
Declare and initialize your array outside of the event handler so it can accumulate keypresses rather than get reset every time. Your current code is setting the array back to be empty on every keypress with varArray = [];
.
You can use something like this where varArray is declared and initialized once as a global variable. I also changed varLetter
to be a local variable since it is only used locally and there is no need for it to be global:
var varArray = [];
$(document).ready(function() {
$(document).keyup(function(objEvent) {
(objEvent) ? keyCode = objEvent.keyCode : keyCode = event.keyCode;
var varLetter = String.fromCharCode(keyCode);
console.log(varLetter);
varArray.push(varLetter);
});
});