0

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

1
  • 2
    You should be declaring your variables with var here! Commented Aug 26, 2012 at 0:34

2 Answers 2

3

You are resetting the array with every key press on this line...

varArray = [];
Sign up to request clarification or add additional context in comments.

1 Comment

@AlexSaunders - you might be able to remove it.
0

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);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.