Javascript dynamic Array not working - javascript

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

You are resetting the array with every key press on this line...
varArray = [];

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

Related

keeping localStorage objects that iterate whilst using clear() within the same function

I'm trying to clear all local storage when the user either completes the game loop or starts a new game, but also keep some values.
I can do this already with my sound values for volume:
// inside a conditional statement that fires when the user chooses to start a new game.
if (newGameBool === '1') {
var tst = myAu;
//myAu is the stored value that the user sets as sound using a range type input
localStorage.clear();
localStorage.setItem("Au", tst);//A newly cleared localStorage just got a new value, and it's the same as it was before.
UI.myLoad();//reload the function that uses LS to do things.
}
How do I do this for key's that have an iterating number attached to them?
Here is how I save them:
var i = +v + +1;
localStorage.setItem("v", i);
var vv = localStorage.getItem("v");
localStorage.setItem("LdrBrd_" + vv, JSON.stringify(LdrBrd));//saves all data with the iterating key name.
Calling them the way i did the sound function:
var gv = v + 1;//v calls the value from LS and adjusted for off-by-one error. gv is a local variable.
if (newGameBool === '1') {
var ldd, vg;
for (var ii = 0; ii < gv; ii++) {
var ld = localStorage.getItem("LdrBrd_" + ii);
if (ld != null) {
//these are the values that i want to pass beyond the clear point
ldd = JSON.parse(ld);//JSON string of data saved
vg = ii;//how many of them.
}
}
localStorage.clear();
for (var xx = 0; xx < vg; xx++) {
var nld = localStorage.getItem("LdrBrd_" + xx);
if (nld != null) {
localStorage.setItem("LdrBrd_" + ii, JSON.stringify(ldd));
}
}
localStorage.setItem("v", vg);
UI.myLoad();
}
I have been using console.log() in various spots to see what is going on. I comment-out the clear function just to see if the values were wrong and they don't save all all. I tried to make a fiddle, but the local storage wasn't working at all there. In visual studio, it works fine but the script to this file is almost 2000 lines long, so i tried to dress it up the best i knew how.
Thanks in advance for any help or guidance.
I was stuck on this for a few days, but i think i found something that will work, so i'll answer my own question in case there is value in posterity.
locatStorage.clear();
/* ^LS clear() function is above all new setItem codes, some variables are declared globally and some are declared at the top of the functional scope or as param^ */
var itemClass = document.querySelectorAll(".itemClass");//the strings are here
if (itemClass) {//make sure some exist
for (var p = 0; p < itemClass.length; p++) {//count them
mdd = JSON.parse(itemClass[p].innerText);//parse the data for saving
localStorage.setItem("v", v);//this is the LS item that saves the amount of items i have, it's declared at the top of the functions timeline.
localStorage.setItem("LdrBrd_" + p, JSON.stringify(mdd));//this setItem function will repeat and increment with 'p' and assign the right string back to the key name it had before.
}
}
The key is to keep the strings physically attached to an element, then call the class name. The i ran a loop counting them. 'mdd' will spit back each item i want. So then all that is left to do is re-set the item back to it's original status.
This has allowed me to create a way for my users to collect trophies and keep them even after clearing the localStorage when the he/she decides to start a new game.
I use CSS to hide the text from the string.
color:transparent;
In my gameLoop, i have a function that will read the saved strings and show them as cards just below the hidden strings.
Since you want to keep some values I recommend one of two things:
Don't call localStorage.clear() and instead only wipe out the values that you want using localStorage.removeItem('itemName'). Since you said the item names have a numeric component, maybe you can do this in a loop to reduce code.
Pull item(s) that you want saved first and restore them after calling clear(). This option is best if there are way more items that you want removed rather than saved (see below)
function mostlyClear() {
var saveMe = {};
saveMe['value1'] = localStorage.getItem('value1');
saveMe['anotherValue'] = localStorage.getItem('anotherValue');
localStorage.clear();
for(var prop in saveMe) {
if(!saveMe.hasOwnProperty(prop)) continue;
localStorage.setItem(prop, saveMe[prop]);
}
}

Why wont this event listener work for multiple keys when in an array in javascript?

First code--> My first example does not work, and I am not sure why. I would say a condition, like if(keys[38]) where 38 in the example would be the event.keyCode. If true, it should execute the if statement.
second code--> The second example only works when there is one key being pushed, and I am not sure why it does not work for multiple keys, either. For multiple keys I would say something like if(keys[38] && keys[40]), but that will not work, it should be noted, however, that it would work for just one key, like just if(keys[38]).
I know that there are other ways to get this to work, but my objective is to figure out why these code pieces do not work.
first code piece:
var keys = [];
addEventListener("keydown", function(event) {
keys[event.keyCode] = event.type == "keydown";
event.preventDefault();
});
/*conditions*/
second code piece:
var keys = [];
addEventListener("keydown", function(event) {
keys[event.keyCode] = event.type == "keydown";
event.preventDefault();
/* conditions with multiple keys accessing by if(keys[38] && keys[40]*/
});
thanks ahead of time :)
When you press multiple keys, your addEventListener no longer listens to your first keypress. That's why your if statement is failing. You can test that out on the first example on http://api.jquery.com/event.which/ Try holding one key, then holding a second key, and then releasing the second key. You'll notice that the first key won't be logged anymore.
*edit: A way around that would be to implement it like this:
var keys = {};
$(document).keydown(function (e) {
keys[e.which] = true;
});
$(document).keyup(function (e) {
delete keys[e.which];
});
The difference is that in this case, nothing is getting overwritten, where as in your example your first key press is getting overwritten (and no longer saved) by the second key press.

How can I catch 2+ key presses at once?

Well lately i got interested in creating JS games. (not an area i have experience with but it interests me).
i know there are several gaming engines for JS out there but i dont really want to create a game. rather i am curious on how things work / how can i create one.
I have several questions:
Anyone with suggestions on where can I read about it? Prerequisite (what knowledge is needed).
I tried making a small game of something walking in a rectangular. By binding keyup to the window and checking the event.which to get the key that was pressed. I realized that if i clicked on 2 buttons same time only 1 of them is being registered. how can i overcome that?
$(window).keyup(function(event){
globalEvent = event.which;
});
To directly answer your second question.
Here is one way:
var keyPressed = {};
$(window).keydown(function(e) {
keyPressed[e.which] = true;
}).keyup(function(e) {
keyPressed[e.which] = false;
});
Now you can use keyPressed whenever you want to determine if a key is down:
// wherever
var key1 = 65, key2 = 66; // A and B
if (keyPressed[key1] && keyPressed[key2]) {
// A and B are both being pressed.
}
In order to detect multiple keys being held down, use the keydown and keyup events.
var keys = {};
$(document).keydown(function (e) {
keys[e.which] = true;
});
$(document).keyup(function (e) {
delete keys[e.which];
});

How to clean up keyDown array

I'm fiddling around trying to build a game, and added some even listeners to find out which keys are down. I stack 'm up into one array, and use that array to manipulate the game-state.
If this is the wrong way to go about it, feel free to comment on that specifically, but I'm just going to assume for a moment that this is one of the ways to Rome.
My question; when someone presses multiple keys at once (or lots of them in the case of PS2 boards) these case might get "stuck" in the array, while not being down.
How would one prune this array, without removing keys that are actually down at that very moment?
var keysDown = []; // this is where I toss all they keyCodes
function keyDown(e) {
e = e || event;
if (keysDown.indexOf(e.keyCode) < 0) {
keysDown.push(e.keyCode)
console.log(keysDown);
};
};
function keyUp(e) {
e = e || event;
if (keysDown.indexOf(e.keyCode) > -1) {
keysDown.splice(keysDown.indexOf(e.keyCode), 1);
console.log(keysDown);
};
};
document.onkeydown = keyDown;
document.onkeyup = keyUp;
.edit: Fiddled it.
It looks like, with JS this just isn't possible.
The neatest way to handle this is to do nothing.
Alternatively you can consider keeping track of the total number of keys punched in and if it exceeds a certain number (hard to say how many) you could delete the first pressed keys, but that's more like patching a leaking barrel with some tape.

Swap the contents of 2 JavaScript variables from one to the other

Basically what I am wanting to do is take the variable named FROM and swap it with the variable named TO and vice visa, the reason for this is to allow the user to press a button which swaps the variables over when pressed. Exactly how it does when you press the swap button on google translate. Below is the code for the variables ect, but I have no idea on how to code the button so they swap over so to speak.
function save_options_from() {
var select = document.getElementById("FROM");
var FROM = select.children[select.selectedIndex].value;
localStorage["default_currency"] = FROM;
var
}
function save_options_to() {
var select = document.getElementById("TO");
var TO = select.children[select.selectedIndex].value;
localStorage["default_currency_to"] = TO;
The FROM and TO variables are local to the two functions and don't exist at the same time. I think what you want is this:
var originalDefault = localStorage['default_currency'];
localStorage['default_currency'] = localStorage['default_currency_to'];
localStorage['default_currency_to'] = originalDefault;
I would suggest two hidden fields FROM_old and TO_old for doing the swapping, as you need to capture the value before you change it.

Categories