I'm working on a website with Jquery tabs dynamically generated. Each tab has an ID.
For the purpose of my script I need to know how many times the user has clicked in a tab.
To record the number of clicks I was thinking of doing an array like this:
var i = new Array(my_tab_id);
(...)
i[my_tab_id] = 0;
Where my_tab_id dynamically changes depending on the tab we're in. Sadly, it doesn't seem like the value of my_tab_id is translated into the array. I don't have i[5] = 0, i[6] = 0, etc. but rather i[my_tab_id], which doesn't help more than a simple var.
Any advice? Thanks!
In that case you shouldn't use an array, you should use an object, which you can treat like a hash.
var o = {};
var id = 'x';
o[id] = 1;
alert(o[id]);
This should allow you to store the click count onto each tab using the .data() function in jQuery each time a tab is clicked.
$('#example').bind('tabsselect', function(event, ui) {
var count = parseInt(ui.tab.data("clickCount"));
if (isNaN(count)) count = 0;
count++;
ui.tab.data("clickCount", count);
});
I think I understand your problem.
You are saying that the var i only has one element. This happens because the var i is newly instantiated every time you open a new tab. I'm guessing every tab is a new page or at least is a new context for var i.
If you want to keep an instance of an object (like an array) in between different pages, take a look at jStorage, it allows you to keep data locally on the browser and it makes it easier to maintain context between page loads.
If all tabs are on the same page then the solution is easier, you need to keep the array in a global variable for the page.
Are you sure my_tab_id is an integer when i[my_tab_id] = 0; is called?
Related
I have a html5 Canvas animation that I am doing on Adobe Animate and tweaking with some code.
I have a portion on the animation that will be like a combobox with all the links to navigate through the different frames. The thing is, I don't want to be creating a bunch of EventListener to many buttons because from experience I know that doesn't work so well. So I am trying to think of a more creative solution. This is my idea.
Create an array that will contain all the buttons.
Assing a variable for each target frame.
Create a for loop with a function inside that assigns the listener to the selected button and then points it to the desired frame (variable)
This is what I have got so far, (not much)
var combobox = [this.btncasco , this.btnbanyera , this.btnLumbrera , this.btnproapopa, this.btnestriborbabor ];
for (var i=0; i<combobox.length; i++) {
var clipcasco = gotoAndStop(0);
var clipbanyera = gotoAndStop(2);
var cliplumbera = gotoAndStop(4);
var clipproapoa = gotoAndStop(6);
var clipestriborbabor = gotoAndStop(8);
}
Would that be feasible ?
In your example, you are just assigning the result of gotoAndStop (with no scope, so likely you're getting an error in the console)
I think you are looking for something like this:
for (var i=0; i<combobox.length; i++) {
// This is kind of complex, but if you just reference "i" in your callback
// It will always be combobox.length, since it references the value of i
// after the for loop completes variable.
// So just store a new reference on your button to make it easy
combobox[i].index = i*2; // x2 lines up with your code 0,2,4,etc.
// Add a listener to the button
combobox[i].on("click", function(event) {
// Use event.target instead of combobox[i] for the same reason as above.
event.target.gotoAndStop(event.target.index);
}
}
You might have the same problem as your other StackOverflow post where the button is undefined (check the console). There is actually a bug in Animate export right now where children of a clip are not immediately available. To get around this, you can call this.gotoAndStop(0); at the start to force it to update the children.
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]);
}
}
I currently have the following jQuery code working. Here's what it does: when I click a button, it will swap between classes. Each of those classes contains a background image. So, as I click this single button, it cycles through the background images. (edit: I just need to store whatever the current variable is, so when they swap pages, that variable is what's loaded).
$('.button').mousedown(function () {
$('#backgrounds').each(function(){
var classes = ['bg1','bg2','bg3','bg4'];
this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
});
});
However, my website has multiple pages. So, what I need to do is store the current variable to the session storage or local storage, and then retrieve that variable on page load. That way as I jump from one page to another, the same class (and therefore background image) will be displayed. I don't need to (nor want to) use cookies -- I just need this to last the current session.
Additionally, if possible (though much less important than storing the variable), I'd also like this jQuery function to neatly fade when swapping from one background image to another. Right now it "snaps" from one image to the next as it swaps out the classes.
Thanks in advance -- any help greatly appreciated!
Use the Window.sessionStorage API for a single session.
Just set by getting the value from the sessionStorage if applicable (if not, set a default value):
var classes = sessionStorage.getItem(classes) || ['bg1','bg2','bg3','bg4'];
and set it when you need to:
sessionStorage.setItem("classes", classes);
The selector #backgrounds should only match one element. So it is unnecessary to use each:
// Define classes & background element.
var classes = ['bg1','bg2','bg3','bg4'],
$bg = document.getElementById('backgrounds');
// On first run:
$bg.className = sessionStorage.getItem('currentClass') || classes[0];
// On button click:
$('.button').mousedown(function () {
// (1) Get current class of background element,
// find its index in "classes" Array.
var currentClassIndex = classes.indexOf($bg.className);
// (2) Get new class from list.
var nextClass = classes[(currentClassIndex + 1)%classes.length];
// (3) Assign new class to background element.
$bg.className = nextClass;
// (4) Save new class in sessionStorage.
sessionStorage.setItem('currentClass', nextClass);
});
In this demo I've used getElementById to select the #backgrounds DOM element, rather than selecting it using jQuery. This is because jQuery element representations don't actually have a className property, and the ordinary JavaScript API is simpler in this case.
I have a function that returns a javascript array which has been passed from local storage to a html ordered list tag. the function runs on document load and works ok. The thing is I want to be able to update the list. The array in local storage updates ok but I cant get the list to dynamically append or update. The best way I can think of achieving this is by removing the original list and then recalling the scoresListDisplay() method after updating local storage. But various attempts at removeChild do not work or if they do work the method will not recall.
Global variables:
var currentScore = 0;
var storedEntries = [];
var highScoreList;
var gamescorelist;
The Function:
function scoresListDisplay(){
storedEntries = JSON.parse(localStorage.getItem("localstoragekey"));
highScoreList = game.querySelector("section#game ol.high-scores");
for(var i = 0; i < 10; i++){
var s = storedEntries[i];
gamescorelist = document.createElement('li');
gamescorelist.innerHTML = (typeof(s) != "undefined" ? s : "" );
highScoreList.appendChild(gamescorelist);
}
The method call after local storage has been updated:
highScoreList.removeChild(gamescorelist);
scoresListDisplay();
also tried:
highScoreList.removeChild(document.getElementById("game"));
gamescorelist.remove();
I was expecting the remove child method to work but it does not.
If anyone has any help on this I would greatly appreciate it.
ok. I have a dropdown. well call it dropdownA. I have several arrays already fashioned, that i want to loop through, and put each individual value out onto the page into it's own input field, based on the selection in the dropdown. I know how to put together the loop to get the values out onto the page. anyway, here is the meta code.
meta1array=new Array('','','','','','');
meta2array=new Array('','','','','','');
meta3array=new Array('','','','','','');
function metacode(id){
{
var a=get.the.dd.selIndex;
var b=get.the.dd.options[a].value; //comes back as 'meta1'. other opts are meta2, meta3
var c=b+'array';
for(i=0;i<c.count;i++)
{
loop here to popout values
}
}
i have looked everywhere, and i haven't come up with anything. I also admit that my brain is starting to mushify from a few weeks straight of coding, and this is the first time i have come across this. so, please. i would be greatful for any help.
Global variables are members of the window object.
var c = window[b + 'array'];
It might be wise to make your arrays members of some other object though, for tighter scoping (avoid cluttering the global namespace).
metaobject = {
meta1array: ['','','','',''],
meta2array: ['','','','',''],
meta3array: ['','','','','']
};
// snip
var arr = metaobject[b + 'array'];
for(var i=0;i<arr.length;i++) {
//do work
}
Check out the fiddle using jquery here.