I have code that loads the variables and turns them into numbers, I can do math with these, and can display them on page, but i have functions, that worked before the loading was added, that use these variables to automatically add 1 to the variables. I have a loop that runs this automatic addition. however the loop does not seem to be working after the addition of the loading.
if(typeof(Storage)!=="undefined") {
var hotdogs = parseInt(localStorage.getItem('hotdogs'), 10);
var bread = parseInt(localStorage.getItem('bread'), 10);
var hotdog = parseInt(localStorage.getItem('hotdog'), 10);
var sauce = parseInt(localStorage.getItem('sauce'), 10);
var bakeries = parseInt(localStorage.getItem('bakeries'), 10);
var butchers = parseInt(localStorage.getItem('butchers'), 10);
var sauceries = parseInt(localStorage.getItem('sauceries'), 10);
}
else {
var hotdogs = 0;
var bread = 0;
var hotdog = 0;
var sauce = 0;
var bakeries = 0;
var butchers = 0;
var sauceries = 0;
}
function buyBakery(){
var bakeryCost = Math.floor(20 * Math.pow(1.05,bakeries));
if(hotdogs >= bakeryCost){
bakeries = bakeries + 1;
hotdogs = hotdogs - bakeryCost;
document.getElementById('bakeries').innerHTML = bakeries;
document.getElementById('hotdogs').innerHTML = hotdogs;
};
var nextCostBakery = Math.floor(20 * Math.pow(1.05,bakeries));
document.getElementById('bakerycost').innerHTML = nextCostBakery;
};
(function loop(timer) {
setTimeout(function() {
breadClick(bakeries);
hotdogClick(butchers);
sauceClick(sauceries);
customers(custom);
loop(1000);
}, timer)
})(1000)
For starters you don't appear to be calling the buyBakery() method within your loop.
Secondly, even though 'Storage' is defined the item you are looking for may not be on it.in that case it'll return null instead and parseInt() will convert into NaN(Not a Number)
also make sure the other functions you are calling within the loop are exist and not throwing any errors.use the web console for that.
you might wanna consider saving values back on localStorage (if you are not already doing that) so you can get it later. I've added function to do that on my example.
Try some thing like this.
function loadFromLS(item) {
var ret = 0;
if (typeof (Storage) === 'undefined') {
return ret;
}
if (null === (ret = localStorage.getItem(item))) {
ret = 0;
}
return parseInt(ret, 10);
}
function saveToLS(item, val) {
if (typeof (Storage) === 'undefined') {
return;
}
localStorage[item] = val;
}
var hotdogs = loadFromLS('hotdogs');
var bread = loadFromLS('bread');
var hotdog = loadFromLS('hotdog');
var sauce = loadFromLS('sauce');
var bakeries = loadFromLS('bakeries');
var butchers = loadFromLS('butchers');
var sauceries = loadFromLS('sauceries');
function buyBakery() {
var bakeryCost = Math.floor(20 * Math.pow(1.05, bakeries));
if (hotdogs <= bakeryCost) {
bakeries = bakeries + 1;
hotdogs = hotdogs - bakeryCost;
document.getElementById('bakeries') .innerHTML = bakeries;
document.getElementById('hotdogs').innerHTML = hotdogs;
};
var nextCostBakery = Math.floor(20 * Math.pow(1.05, bakeries));
document.getElementById('bakerycost') .innerHTML = nextCostBakery;
};
(function loop(timer) {
setTimeout(function () {
breadClick(bakeries);
hotdogClick(butchers);
sauceClick(sauceries);
customers(custom);
loop(1000);
}, timer)
}) (1000)
Related
I am creating a program which will sort people's names into different tables(table1, table2, table3, table4) which are represented by arrays and it will add any preferences that people would like to sit by into the same table as them. I have a function, check(), which makes sure there are no duplicate names and that the tables' length does not exceed 6. The problem is the check() function moves the preferences out of the table they need to be in. Is there any way to keep this from happening? Thank you.
JavaScript:
$(document).ready(function () {
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
function seat() {
for (var i = 0; i < names.length; i++) {
if (pref != "") {
if (pref == names[i]) {
var who = names[i];
function prandomize(min, max) {
var pr = Math.floor(Math.random() * (max - min + 1)) + min;
if (pr == 1) {
table1.push(names[i]);
table1.push(who);
} else if (pr == 2) {
table2.push(names[i]);
table2.push(who);
} else if (pr == 3) {
table3.push(names[i]);
table3.push(who);
} else if (pr == 4) {
table4.push(names[i]);
table4.push(who);
} else {
return "Error: Contact Source Code Author!!";
}
}
}
}
function randomize(min, max) {
var r = Math.floor(Math.random() * (max - min + 1)) + min;
if (r == 1) {
table1.push(names[i]);
} else if (r == 2) {
table2.push(names[i]);
} else if (r == 3) {
table3.push(names[i]);
} else if (r == 4) {
table4.push(names[i]);
} else {
return "Error: Contact Source Code Author!!";
}
}
randomize(1, 4);
};
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("first call");
};
var htable1 = document.getElementById('t1');
var htable11 = document.getElementById('t11');
var htable111 = document.getElementById('t111');
var htable1111 = document.getElementById('t1111');
var htable11111 = document.getElementById('t11111');
var htable111111 = document.getElementById('t111111');
var htable2 = document.getElementById('t2');
var htable22 = document.getElementById('t22');
var htable222 = document.getElementById('t222');
var htable2222 = document.getElementById('t2222');
var htable22222 = document.getElementById('t22222');
var htable222222 = document.getElementById('t222222');
var htable3 = document.getElementById('t3');
var htable33 = document.getElementById('t33');
var htable333 = document.getElementById('t333');
var htable3333 = document.getElementById('t3333');
var htable33333 = document.getElementById('t33333');
var htable333333 = document.getElementById('t333333');
var htable4 = document.getElementById('t4');
var htable44 = document.getElementById('t44');
var htable444 = document.getElementById('t444');
var htable4444 = document.getElementById('t4444');
var htable44444 = document.getElementById('t44444');
var htable444444 = document.getElementById('t444444');
function check() {
var stable1 = table1.slice().sort();
for (var i = 0; i < table1.length - 1; i++) {
if (stable1[i + 1] == stable1[i]) {
table1.splice(i, 1);
console.log("removed");
}
}
if (table1.length > 6) {
while (table1.length > 6) {
var lastvalue = table1.pop();
table2.push(lastvalue);
console.log("moved to table2");
}
}
if (table2.length > 6) {
while (table2.length > 6) {
var lastvalue2 = table2.pop();
table3.push(lastvalue2);
console.log("moved to table3");
}
}
if (table3.length > 6) {
while (table3.length > 6) {
var lastvalue3 = table3.pop();
table4.push(lastvalue3);
console.log("moved to table4");
}
}
if (table4.length > 6) {
while (table4.length > 6) {
var lastvalue4 = table4.pop();
table1.push(lastvalue4);
console.log("moved to table1");
}
}
}
function changeHTML() {
htable1.innerHTML = table1[0];
htable11.innerHTML = table1[1];
htable111.innerHTML = table1[2];
htable1111.innerHTML = table1[3];
htable11111.innerHTML = table1[4];
htable111111.innerHTML = table1[5];
htable2.innerHTML = table2[0];
htable22.innerHTML = table2[1];
htable222.innerHTML = table2[2];
htable2222.innerHTML = table2[3];
htable22222.innerHTML = table2[4];
htable222222.innerHTML = table2[5];
htable3.innerHTML = table3[0];
htable33.innerHTML = table3[1];
htable333.innerHTML = table3[2];
htable3333.innerHTML = table3[3];
htable33333.innerHTML = table3[4];
htable333333.innerHTML = table3[5];
htable4.innerHTML = table4[0];
htable44.innerHTML = table4[1];
htable444.innerHTML = table4[2];
htable4444.innerHTML = table4[3];
htable44444.innerHTML = table4[4];
htable444444.innerHTML = table4[5];
}
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
function prefsdefine() {
pref.push(document.getElementById('prefone').value);
pref.push(document.getElementById('preftwo').value);
pref.push(document.getElementById('prefthree').value);
pref.push(document.getElementById('preffour').value);
pref.push(document.getElementById('preffive').value);
pref.push(document.getElementById('prefsix').value);
pref.push(document.getElementById('prefseven').value);
pref.push(document.getElementById('prefeight').value);
pref.push(document.getElementById('prefnine').value);
pref.push(document.getElementById('preften').value);
pref.push(document.getElementById('prefeleven').value);
pref.push(document.getElementById('preftwelve').value);
pref.push(document.getElementById('prefthirteen').value);
pref.push(document.getElementById('preffourteen').value);
pref.push(document.getElementById('preffifthteen').value);
pref.push(document.getElementById('prefsixteen').value);
pref.push(document.getElementById('prefseventeen').value);
pref.push(document.getElementById('prefeightteen').value);
pref.push(document.getElementById('prefnineteen').value);
pref.push(document.getElementById('preftwenty').value);
pref.push(document.getElementById('preftwentyone').value);
pref.push(document.getElementById('preftwentytwo').value);
pref.push(document.getElementById('preftwentythree').value);
pref.push(document.getElementById('preftwentyfour').value);
}
document.getElementById('sbm').addEventListener('click', function (e) {
e.preventDefault();
namesdefine();
prefsdefine();
seat();
check();
check();
check();
changeHTML();
});
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
console.log(pref);
});
I would suggest that you first focus on the data structures that you are using before you try to go too much further. The preferences handling is trickier than it seems at first because you could have person1 who wants to sit with person2, but person2 wants to sit beside person6. This creates a chain of preferences that is not trivial to handle.
Before you try to tackle that, I would suggest you try creating a single data structure (rather than four tables). This data structure might be an array of size 24 holding objects that looks something like this:
{ name: 'xxx', preference: 'yyy', table: n }
If you are not comfortable with objects, or arrays of objects, I would suggest that you focus your efforts on learning them since they are absolutely essential in JavaScript. Arrays are handy but, in practice, they tend to be for very simple lists or as containers to hold objects.
I could provide you code that will do what you want but I don't think that will help you in your learning curve. Take a stab at applying a different data structure and if you get stuck there, maybe post a new question on SO. There are plenty of people that want to help but you will need to do your homework to get assistance along the way.
I am trying to add multiple instances of different objects to another object's array. I'm having trouble however.
*Creates the player*
function Player(){
this.name = "";
this.status = "Alive";
this.primaryClass = null;
this.secondaryClass = null;
this.strength = 0;
this.stamina = 0;
this.mystica = 0;
this.health = 0;
this.primaryWeapon = null;
this.offHand = null;
this.accuracy = 0;
this.block = 0;
this.baseDamage = 0;
this.maxDamage = 0;
this.attackSpeed = 0;
this.shield = null;
this.armor = null;
this.armorRating = 0;
this.exp = 0;
}
*Creates the sword weapon*
function LongSword(){
this.name = "";
this.attackSpeed = 1;
this.baseDamage = 10;
this.maxDamage = 15;
this.durability = 100;
this.block = 5;
this.exp = 0;
}
*Creates the Long Sword skills*
function Stab(){
this.name = "Stab";
this.status = "Unlocked";
this.damage = 0;
this.damageModifier = 0.75;
this.cooldown = 5;
this.exp = 0;
this.desc = "Stabs your opponent for an additional " +parseInt(this.damageModifier * 100) +"% of your base damage.";
}
*Equips the Player weapon(s)*
Player.prototype.equipWeapon = function equipWeapon(main, offHand){
if(this.primaryClass.dualWield){
this.primaryWeapon = main;
if(offHand){
this.offHand = offHand;
this.baseDamage += (this.strength + (main.baseDamage + (offHand.baseDamage / 2))) / 10;
this.maxDamage += (this.strength + (main.maxDamage + (offHand.maxDamage / 2))) / 5;
this.attackSpeed += main.attackSpeed + (offHand.attackSpeed / 2);
this.block += main.block + offHand.block;
}
}
else{
this.primaryWeapon = main;
this.offHand = null;
this.baseDamage += (this.strength + main.baseDamage) / 10;
this.maxDamage += (this.strength + main.maxDamage) / 5;
this.attackSpeed += main.attackSpeed;
this.block += main.block;
}
if(!this.primaryClass.dualWield && offHand){
console.log("Your class can not wield dual weapons.");
}
}
*Equips the Weapon skills*
LongSword.prototype.skills = function skills(skill){
this.skills = [];
skill.damage = parseFloat((this.baseDamage / skill.damageModifier).toFixed(1));
this.skills.push(skill);
}
These objects construct the basic elements of what I'm trying to do. So when I go to instantiate each one,
var Robert = new Player();
Robert.equipWeapon(new LongSword());
Robert.primaryWeapon.skills(new Stab());
I am getting the results I want. However, if I were to try to add another instance of Stab() so that it looks like this
var Robert = new Player();
Robert.equipWeapon(new LongSword());
Robert.primaryWeapon.skills(new Stab());
Robert.primaryWeapon.skills(new Stab());
I get the TypeError: Robert.primaryWeapon.skills is not a function. Why would it work correctly once, but not a second time. The end result of which I'm trying to achieve is that if consoled out Robert.primaryWeapon.skills, I should see two instances of the Stab object.
There are two issues in your Longsword's prototype.
First, you are replacing your function with your storing skill array, which have the same name :
LongSword.prototype.skills = function skills(skill){
this.skills = []; //Overrides your function
...
Which leads to your error, Robert.primaryWeapon.skills is not a function, cause once you call it, it is an array indeed.
To fix it, just change the name of one of the function or of the array.
Secondly, you are initializing your skills array to an empty array each time you call the function, resetting it every time. You should initialize it in Longsword's protoype.
Here's a an example with these fixes (fiddle with it if you want):
function LongSword(){
this.skills = [];
...
LongSword.prototype.addSkill = function skills(skill){
...
Then, you'll be able to add multiple skills :
var Robert = new Player();
Robert.equipWeapon(new LongSword());
Robert.primaryWeapon.addSkill(new Stab());
Robert.primaryWeapon.addSkill(new Stab());
Js beginner here.
I have a function like this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay,delay);
};
var playAudioOnDelay = function() {
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
};
}
}
What it does is generate data from JSON and display animated elements one by one on delay. Animation part work fine. I can assign required animations and delay to DOM elements and show them in right order.
But what I want to do in the same time is also to play an audio on delay (so I use setTimeout). Everything is almost fine, I play audio in right time (correct delay value) but I always play the same audio (which is last element) because audioPlayer always is the same DOM node.
I think this have something to do with this or I mixed a scope?
Try this:
generateSteps: function() {
var stepsLength = this.data.steps.length;
var dataStepsInit = this.data.steps;
for (var i = 0; i < stepsLength; i++) {
var stepsItem = dataStepsInit[i].ITEM;
var arrayItem = this.animationNodes[stepsItem - 1];
var transition = this.animationParameters[i].transition;
var options = this.animationParameters[i].options;
var speed = this.animationParameters[i].speed;
var delay = this.animationParameters[i].delay;
arrayItem.delay(delay).show(transition, options, speed);
if (dataStepsInit[i].AUDIOID) {
var audioClass = dataStepsInit[i].AUDIOID;
var audioPlayer = this.template.find("audio." + audioClass);
setTimeout(playAudioOnDelay(audioPlayer),delay);
};
}
function playAudioOnDelay(audioPlayer){
return function(){
audioPlayer[0].pause();
audioPlayer[0].currentTime = 0;
audioPlayer[0].play();
}
}
}
Essentially, your problem looks like this: http://jsfiddle.net/po0rLnwo/
The solution is : http://jsfiddle.net/gpfuo1s8/
Check the console in your browser.
So I have a form with two dropdowns. The first dropdown is the options, and the other is more options. So it's like a mix and match, now I want to calculate the total from the two selected dropdowns. Here's what I got going
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
$("#repair_drop").change(function (event) {
getRepair();
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair
}
});
$("#colorize_drop").change(function (event) {
getColor();
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color
}
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
total();
I end up getting
Uncaught ReferenceError: getRepair is not defined
So for example I'd choose repairCost["minor"] and colorCost["group_scene"], then my result would be $30. I have a timer in there so it automatically calculates the total. Any ideas?
You defined the getRepair function inside another function. Therefore you cannot access it from outside. You have to define it outside the function to be able to access it, like so :
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair;
}
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color;
}
$("#repair_drop").change(function (event) {
getRepair();
});
$("#colorize_drop").change(function (event) {
getColor();
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
Why are you declaring functions within your events, and then calling them from there? Either declare them outside the events, or just inline the code - don't do both.
I'm running the JavaScript below to place horizontal scrolling text on the banner of my website. It works in one server but not another. I get the following error:
Error: 'this.mqo' is null or not an object
JavaScript:
function start() {
new mq('m1');
/* new mq('m2');
*/
mqRotate(mqr); // must come last
}
window.onload = start;
// Continuous Text Marquee
// permission to use this Javascript on your web page is granted
// provided that all of the code below in this script (including these
// comments) is used without any alteration
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
var mqr = [];
function mq(id) {
this.mqo = document.getElementById(id);
var wid = objWidth(this.mqo.getElementsByTagName('span')[0]) + 5;
var fulwid = objWidth(this.mqo);
var txt = this.mqo.getElementsByTagName('span')[0].innerHTML;
this.mqo.innerHTML = '';
var heit = this.mqo.style.height;
this.mqo.onmouseout = function () {
mqRotate(mqr);
};
this.mqo.onmouseover = function () {
clearTimeout(mqr[0].TO);
};
this.mqo.ary = [];
var maxw = Math.ceil(fulwid / wid) + 1;
for (var i = 0; i < maxw; i++) {
this.mqo.ary[i] = document.createElement('div');
this.mqo.ary[i].innerHTML = txt;
this.mqo.ary[i].style.position = 'absolute';
this.mqo.ary[i].style.left = (wid * i) + 'px';
this.mqo.ary[i].style.width = wid + 'px';
this.mqo.ary[i].style.height = heit;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j = mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i = 0; i < maxa; i++) {
var x = mqr[j].ary[i].style;
x.left = (parseInt(x.left, 10) - 1) + 'px';
}
var y = mqr[j].ary[0].style;
if (parseInt(y.left, 10) + parseInt(y.width, 10) < 0) {
var z = mqr[j].ary.shift();
z.style.left = (parseInt(z.style.left) + parseInt(z.style.width) * maxa) + 'px';
mqr[j].ary.push(z);
}
}
mqr[0].TO = setTimeout('mqRotate(mqr)', 10);
}
The reason is most likely that there is no element with the id "m1". Place this line first in the start function to diagnose this:
alert(document.getElementById('m1'));
If it shows "[Object]" (or similar), the element exists and it's some other problem, but if it shows "undefined" it means that there is no such element in the page.