Having trouble with image preload code - javascript

I have this object constructor function that has a preload method for preloading
rollover images pairs.
So, I have two questions:
1: why is the alert dialog just doing 'STR: ' with no data attached? (this type of problem is generally due to my blindness.
2: is it possible to treat the this.buttons_on and this.buttons_off as objects in that instead of
a numerical index, use a sting index so the rollover event handler does not need to loop through
the buttons_on and buttons_off arrays to get the one that should be swapped out;
function _NAV()
{
this.list_off = [];
this.list_on = [];
this.buttons_on = [];
this.buttons_off = [];
this.buttons_all = {}; // .on and .off
this.button_events = {};
this.img = true;
this.img_ids = {}
this.preLoad = function()
{
if(document.images) //creates image object array for preload.
{
var STR = '';
for(var i = 0; i < list_off.length; i++)
{
var lab_on = list_on[i].replace('\.jpg', '');
var lab_off = list_off[i].replace('\.jpg', '');
STR += lab_on+'||'+lab_off+"\n";
this.buttons_on[i] = new Image();
this.buttons_on[i].src = srcPath+list_on[i];
this.bottons_on[i].id = img_ids[i];
this.buttons_off[i] = new Image();
this.buttons_off[i].src = srcPath+list_off[i];
this.buttons_off[i].id = img_ids[i];
}
alert("STR: "+STR);
}
else
{
this.img = false
}
}
//// ...etc...
Here is the call before the onload event fires
var rollover = new _NAV();
rollover.preLoad();
Here are the arrays used
var srcPath = '../nav_buttons/';
var list_off = new Array(); // not new Object;
list_off[0] = "bio_off.jpg";
list_off[1] = "cd_off.jpg";
list_off[2] = "home_off.jpg";
list_off[3] = "inst_off.jpg";
list_off[4] = "photo_off.jpg";
list_off[5] = "rev_off.jpg";
list_off[6] = "samp_off.jpg";
var list_on = new Array();
list_on[0] = "bio_on.jpg";
list_on[1] = "cd_on.jpg";
list_on[2] = "home_on.jpg";
list_on[3] = "inst_on.jpg";
list_on[4] = "photo_on.jpg";
list_on[5] = "rev_on.jpg";
list_on[6] = "samp_on.jpg";
var img_ids = new Array();
Thanks for time and attention.

1:
Try PHPGlue's suggestion and add this. in front of all your member variables (this.list_on, this.list_off, this.img_ids)
You also have a typo on one line. bottons_on is misspelled.
this.bottons_on[i].id = img_ids[i];
2:
Yes, you can use a string as an index. Just make buttons_on and buttons_off objects instead of arrays.
function _NAV()
{
this.buttons_on = {};
this.buttons_off = {};
// For example:
this.buttons_off[lab_off] = new Image();
}

Related

I have a misunderstanding with localStorage

I'm currently beginning to learn how to use javascript, and I have a small problem.
I'm making a minigame of 'find the random number', and I'm trying to implement a localStorage savestate that let me keep my game as it was when I closed it, but without success. Here's the part of my JS
where I'm stuck.
let Rndm = Math.floor(Math.random() * 100) + 1;
var tentatives = document.querySelector('.tentatives');
var resultat = document.querySelector('.resultat');
var plusoumoins = document.querySelector('.plusoumoins');
var valider = document.querySelector('.valider');
var essai = document.querySelector('.essai');
var nmbrmax = 1000;
var nmbrtent = 1;
let j1 = document.getElementById("j1");
let j2 = document.getElementById("j2");
var joueur1 = document.getElementById("joueur1");
var joueur2 = document.getElementById("joueur2");
let nomsjoueurs = document.getElementById("nomsjoueurs");
let tour = document.getElementById("tour");
var playerTurn = 0;
const partiesauvee = []
function sauvegarder() {
partiesauvee.push(tentatives.textContent);
partiesauvee.push(resultat.textContent);
partiesauvee.push(plusoumoins.textContent);
partiesauvee.push(nmbrmax);
partiesauvee.push(nmbrtent);
partiesauvee.push(joueur1.value);
partiesauvee.push(joueur2.value);
localStorage.setItem('sauvegard', JSON.stringify(partiesauvee))
}
function refresh() {
const partiesauvee = JSON.parse(localStorage.getItem('sauvegard'));
var tentatives = JSON.parse(localStorage.getItem('sauvegard'));
var resultat = JSON.parse(localStorage.getItem('sauvegard'));
var plusoumoins = JSON.parse(localStorage.getItem('sauvegard'));
var nmbrmax = localStorage.getItem('sauvegard');
var nmbrtent = localStorage.getItem('sauvegard');
var joueur1 = JSON.parse(localStorage.getItem('sauvegard'));
var joueur2 = JSON.parse(localStorage.getItem('sauvegard'));
}
window.addEventListener('DOMContentLoaded', refresh);
When the sauvegarder function is activated, the console.log(localstorage) find all the values,
but I can't find a way to return them to their places. Someone have an idea? Thanks !
You're storing an array. You need to assign each array element to a different DOM element.
function refresh() {
const storage = localStorage.getItem('sauvegard');
if (!storage) { // nothing saved
return;
}
const partiesauvee = JSON.parse(storage);
tentatives.textContent = partiesauvee[0];
resultat.textContent = partiesauvee[1];
plusoumoins.textContent = partiesauvee[2];
nmbrmax.textContent = partiesauvee[3];
nmbrtent.textContent = partiesauvee[4];
joueur1.textContent = partiesauvee[5];
joueur2.textContent = partiesauvee[6];
}

How to get the total number of objects created in javascript for a class?

Lets say I have the following code snippet:
function Airplane(id) {
this.id = id;
}
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
Is there any way to get the total number of Airplane objects created something like Airplane.getCreatedLength()?
You could keep track of those in a property attached to the constructor:
function Airplane(id) {
this.id = id;
Airplane.instances += 1;
}
Airplane.instances = 0;
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
console.log(Airplane.instances) // 3

certain global(class) variables disappearing in javascript? (photoshop)

I'm working on a plug-in script for photoshop and I'm encountering a really weird problem, the closest person to have this problem is here : Why do class variables in Javascript disappear when trying to call them multiple times or assigning them to local variables?
So reading his solution I combed over my syntax and I can't find any issues that I didn't correct and try again. I'll include the full code in a bit but here is the gist of the problem, I'm declaring this object in global space by declaring it and it's members outside of functions:
prefs = new Object();
prefs.db_file = "";
prefs.bk_file = "";
prefs.text = new Object();
prefs.text.top = 0.6;
prefs.text.bottom = 0.9;
prefs.text.padding = 0.05;
prefs.text.size = 12;
prefs.text.shadow = true;
basic outline (pseudocode):
declare global variables
main() {
Dialogue()
do stuff with the variables
}
Dialogue() {
declare new window
accept user interaction
store in global variable
}
I've run through this several times, step by step in the extendscript debugger watching the variables, every time the variables exist and the values are correct, until they exit the Dialogue() function then the only variables that exist are prefs.text.shadow and prefs.text.size
everything I've tried, including removing the ".text." part has returned the same. I can't find if my syntax is wrong, if it is wrong than why don't all the prefs. variables disappear? and I'm fairly certain that all the variables are treated the same way.
Update 10-22-2013: To help rule out syntax issues I found JSlint and ran my code through it and went through and corrected the issues it presented. The only issues left are grouping 'var' selections. It changed my object declaration method, some code ordering, unnecessary ';'s standardizing my indents. The Result: The same. The same variables are dropped and the same output is returned.
Here is the full code:
#target photoshop
app.bringToFront();
prefs = new Object();
prefs.db_file = "";
prefs.bk_file = "";
prefs.text = new Object();
prefs.text.top = 0.6;
prefs.text.bottom = 0.9;
prefs.text.padding = 0.05;
prefs.text.size = 12;
prefs.text.shadow = true;
function main() {
Dialogue();
var db_file2 = new File(prefs.db_file);
db_file2.open('r');
var data = Array();
var str = "";
var data_str = "";
while(!db_file2.eof) {
str = db_file2.readln();
data.push(str.split(","));
data_str += str;
};
db_file2.close();
alert(data_str);
};
function Dialogue() {
var dlg = new Window ("dialog","Create New Slide Set");
dlg.orientation = "row";
dlg.alignChildren = "fill";
dlg.pref_group = dlg.add("group");
dlg.pref_group.orientation = "column";
dlg.pref_group.alignChildren = "fill";
dlg.pref_group.db_val = dlg.pref_group.add("edittext",undefined,prefs.db_file);
dlg.pref_group.db_find = dlg.pref_group.add("button",undefined,"select data file");
dlg.pref_group.db_find.onClick = function() {
selectedFile = File.openDialog("Please select CSV file.","CSV File:*.csv");
if(selectedFile != null) {
dlg.pref_group.db_val.text = decodeURI(selectedFile.fsName);
prefs.db_file = dlg.pref_group.db_val.text;
};
};
dlg.pref_group.db_val.onChange = function() {
prefs.db_file = dlg.pref_group.db_val.value;
alert("db_file has been changed!");
};
dlg.pref_group.bk_val = dlg.pref_group.add("edittext",undefined,prefs.bk_file);
dlg.pref_group.bk_find = dlg.pref_group.add("button",undefined,"select background image");
dlg.pref_group.bk_find.onClick = function() {
selectedFile = File.openDialog("Please select PNG file.","Image File:*.png");
if(selectedFile != null) {
dlg.pref_group.bk_val.text = decodeURI(selectedFile.fsName);
prefs.bk_file = dlg.pref_group.bk_val.text;
};
};
dlg.pref_group.bk_val.onChange = function() {
prefs.bk_file = dlg.pref_group.bk_val.value;
};
dlg.pref_group.tt_grp = dlg.pref_group.add("group");
dlg.pref_group.tt_grp.orientation = "row";
dlg.pref_group.tt_grp.alignChildren = "fill";
dlg.pref_group.tt_grp.tt = dlg.pref_group.tt_grp.add("statictext",undefined,"Text Top");
dlg.pref_group.tt_grp.tt_dsp = dlg.pref_group.tt_grp.add("edittext",undefined,prefs.text.top);
dlg.pref_group.tt_grp.tt_dsp.preferredsize = [100,200];
dlg.pref_group.tt_grp.tt_dsp.onChange = function() {
prefs.text.top = dlg.pref_group.tt_grp.tt_dsp.value;
};
dlg.pref_group.bt_grp = dlg.pref_group.add("group");
dlg.pref_group.bt_grp.orientation = "row";
dlg.pref_group.bt_grp.alignChildren = "fill";
dlg.pref_group.bt_grp.bt = dlg.pref_group.bt_grp.add("statictext",undefined,"Text bottom");
dlg.pref_group.bt_grp.bt_dsp = dlg.pref_group.bt_grp.add("edittext",undefined,prefs.text.bottom);
dlg.pref_group.bt_grp.bt_dsp.preferredsize = [100,200];
dlg.pref_group.bt_grp.bt_dsp.onChange = function() {
prefs.text.bottom = dlg.pref_group.bt_grp.bt_dsp.value;
};
dlg.pref_group.pd_grp = dlg.pref_group.add("group");
dlg.pref_group.pd_grp.orientation = "row";
dlg.pref_group.pd_grp.alignChildren = "fill";
dlg.pref_group.pd_grp.pd = dlg.pref_group.pd_grp.add("statictext",undefined,"Padding");
dlg.pref_group.pd_grp.pd_dsp = dlg.pref_group.pd_grp.add("edittext",undefined,prefs.text.padding);
dlg.pref_group.pd_grp.pd_dsp.preferredsize = [100,200];
dlg.pref_group.pd_grp.pd_dsp.onChange = function() {
prefs.text.padding = dlg.pref_group.pd_grp.pd_dsp.value;
};
dlg.pref_group.sd_grp = dlg.pref_group.add("group");
dlg.pref_group.sd_grp.orientation = "row";
dlg.pref_group.sd_grp.alignChildren = "fill";
dlg.pref_group.sd_grp.sd = dlg.pref_group.sd_grp.add("statictext",undefined,"Shadow");
dlg.pref_group.sd_grp.sd_dsp = dlg.pref_group.sd_grp.add("checkbox",undefined,"");
dlg.pref_group.sd_grp.sd_dsp.value = prefs.text.shadow;
dlg.pref_group.sd_grp.sd_dsp.onChange = function() {
prefs.text.shadow = dlg.pref_group.sd_grp.sd_dsp.value;
};
dlg.ok_group = dlg.add('group');
dlg.ok_group.orientation = "column";
dlg.ok_group.ok_btn = dlg.ok_group.add("button",undefined,"ok");
dlg.ok_group.ok_btn.onClick = function() {
prefs.text.shadow = dlg.pref_group.sd_grp.sd_dsp.value;
prefs.text.padding = dlg.pref_group.pd_grp.pd_dsp.value;
prefs.text.bottom = dlg.pref_group.bt_grp.bt_dsp.value;
prefs.text.top = dlg.pref_group.tt_grp.tt_dsp.value;
prefs.bk_file = dlg.pref_group.bk_val.value;
prefs.db_file = dlg.pref_group.db_val.value;
dlg.close(0);
};
dlg.center();
dlg.show();
};
main();
it was so simple...
'edittext' boxes don't have .value properties they have .text properties, trying to access .value returned a null and destroyed the variable.
my research took me into a lot of areas, syntax conventions, JSlint, object definitions, ironically looking into a different problem (onChange functions aren't being called) made me realize that the only variables that weren't being disregarded were the shadow checkbox, and the font size parameter, but the font size parameter wasn't being edited at all at this point, and the shadow was the only thing being defined by a checkbox. Lesson learned: when something is partially working compare the similarities of the working part

Why can't i access the x variable of the bitmap? (javascript)

I'm trying to loop through 3 images in my array and add it to the stage (using easelJS). I want to position it as well. When I try to access the images in the array i get an error saying that the I can't set x of undefined. Why can't the x variable of the easeljs Bitmap be accessed?
function displayPosters() {
getPosters(); //get all images and assign it to designated array
console.log(frontPosters);
console.log(frontPosters.length);
if(currentCat == Category.HOME) { //if current category is HOME
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
}
}
here is the code for loading and pushing those images into the frontPosters arrray.
var frontPosters = new Array(3);
function getPosters() {
var games = new Image(); //create 3 images
var apps = new Image();
var aboutme = new Image();
games.onload = function() { //add image to frontImages array on load
var gamesPost = new createjs.Bitmap(games);
frontPosters[0] = gamesPost;
};
apps.onload = function() {
var appPost = new createjs.Bitmap(apps);
frontPosters[1] = appPost;
};
aboutme.onload = function() {
var amPost = new createjs.Bitmap(aboutme);
frontPosters[2] = amPost;
};
games.src = "images/assets/posters/games_poster.jpg";
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
}
Using for(poster in frontPosters) is bad practice, because you're actually iterating over the Array Object and not the values (a.k.a. the Array itself). Use for(var i=0; i<frontPosters.length; i++) instead. It's the easiest solution, IMO.
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
Edit
I think you are dealing with a race-condition. You are going over your array before all images were loaded. By setting var frontPosters = new Array(3); you automatically set three values to undefined which are pushed into the new array.
You should check that all images were loaded before proceeding with the script.
Here's an idea for you. Set a callback that will run only after the third image was loaded.
var frontPosters = new Array(3);
function getPosters(callback) {
var games = new Image(),
apps = new Image(),
aboutme = new Image(),
loaded = 0;
games.onload = function() {
frontPosters[0] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
apps.onload = function() {
frontPosters[1] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
aboutme.onload = function() {
frontPosters[2] = new createjs.Bitmap(this);
if (++loaded === 3) callback();
};
games.src = "images/assets/posters/games_poster.jpg";
apps.src = "images/assets/posters/apps_poster.jpg";
aboutme.src = "images/assets/posters/aboutme_poster.jpg";
}
function displayPosters() {
getPosters(function() {
if(currentCat == Category.HOME) { //if current category is HOME
for(var i = 0; i < frontPosters.length; i++) { //loop through posters
frontPosters[i].x = 40; //set x position for testing, also where error occurs
stage.addChild(frontPosters[i]); //add poster to stage
}
}
}); //get all images and assign it to designated array, only after all images were loaded
}

JavaScript, advanced .replace()

function changeText(getString){
var smiles_from_to = new Array();
smiles_from_to[":)"] = "ab"; smiles_from_to[":-)"] = "ab";
smiles_from_to[":("] = "ac"; smiles_from_to[":-("] = "ac";
smiles_from_to["B)"] = "af"; smiles_from_to["B-)"] = "af";
smiles_from_to[";("] = "crygirl2"; smiles_from_to[";-("] = "crygirl2";
smiles_from_to[":-*"] = "aw"; smiles_from_to[":*"] = "aw";
smiles_from_to[":D"] = "ag"; smiles_from_to[":-D"] = "ag";
smiles_from_to["(devil)"] = "aq"; smiles_from_to["(wtf)"] = "ai";
smiles_from_to["(sos)"] = "bc"; smiles_from_to["(boom)"] = "bb";
smiles_from_to["(rofl)"] = "bj"; smiles_from_to["xD"] = "bj";
smiles_from_to["(music)"] = "ar"; smiles_from_to["(angel)"] = "aa";
smiles_from_to["(beer)"] = "az"; smiles_from_to["(omg)"] = "bu";
smiles_from_to["(dance)"] = "bo"; smiles_from_to["(idiot)"] = "bm";
smiles_from_to["(clap)"] = "bi"; smiles_from_to["(gotkiss)"] = "as";
var replaced = getString;
for(var key in smiles_from_to){
replaced = replaced.replace(key, "<img src='"+chrome.extension.getURL("images/"+smiles_from_to[key]+".gif")+"' />");
}
return replaced;
}
Hi everyone ,I need to optimize code for something more simple, so try to avoid for loop..
"var replaced" is a huge html code (content of div that contains 100 lines of messages with date, username, userinfo(tooltip), message,.....)
This code is a piece from my chrome extension. so i cant do it php side.
You can use a single giant regex, of the form /:\)|:\(|.../g, then pass a callbacka as the replacement that looks up the match in your lookup object.

Categories

Resources