Trying to set dynamic JS variables in a function globally - javascript

I'm trying to set local storage values using dynamic variables from within a function what will be looped through. Basically i'm just trying to do this (which works but isn't dynamic):
localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
using this:
counterMarkers[numberID] = maxMarkers[numberID];
but it's not affecting 'localStorage.lvlZeroValue' at a global level
$('#spellCountTackMax').click(function() {
var counterMarkers = [
localStorage.lvlZeroValue,
localStorage.lvlOneValue,
localStorage.lvlTwoValue,
localStorage.lvlThreeValue,
localStorage.lvlFourValue,
localStorage.lvlFiveValue,
localStorage.lvlSixValue,
localStorage.lvlSevenValue,
localStorage.lvlEightValue,
localStorage.lvlNineValue
];
var maxMarkers = [
localStorage.lvlZeroMaxValue,
localStorage.lvlOneMaxValue,
localStorage.lvlTwoMaxValue,
localStorage.lvlThreeMaxValue,
localStorage.lvlFourMaxValue,
localStorage.lvlFiveMaxValue,
localStorage.lvlSixMaxValue,
localStorage.lvlSevenMaxValue,
localStorage.lvlEightMaxValue,
localStorage.lvlNineMaxValue
];
jQuery.fn.onTackSet = function(numberID){
return this.each(function(){
if(maxMarkers[numberID] == "" || maxMarkers[numberID] == null || maxMarkers[numberID] == 0 ) {
alert("not else ran");
$(this).attr('value', "0");
$('#spin' + numberID).attr('value', "0");
counterMarkers[numberID] = "0";
maxMarkers[numberID] = "0";
} else {
alert("else ran");
$(this).attr('value', maxMarkers[numberID]);
$(this).attr('max', maxMarkers[numberID]);
// localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
alert(counterMarkers[numberID]);
alert(maxMarkers[numberID]);
// this works but isn't dynamic
localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
// my attempt at making it dynamic doesn't seem to work globally
counterMarkers[numberID] = maxMarkers[numberID];
}
});
};
$("#spin0").onTackSet(0);
So i'm pretty sure my issue is scope, yet i can't seem to get it right. Please, help. Thanks!

Do you need to keep the keys for your storage values the way you have them? If you could change them from lvlZeroValue to lvl0Value you could use the approach below:
jQuery.fn.onTackSet = function(numberID){
return this.each(function(){
if(localStorage['lvl'+numberID+'MaxValue'] == "" || localStorage['lvl'+numberID+'MaxValue'] == null || localStorage['lvl'+numberID+'MaxValue'] == 0 ) {
alert("not else ran");
$(this).attr('value', "0");
$('#spin' + numberID).attr('value', "0");
localStorage['lvl'+numberID+'Value'] = "0";
localStorage['lvl'+numberID+'MaxValue'] = "0";
} else {
alert("else ran");
$(this).attr('value', localStorage['lvl'+numberID+'MaxValue']);
$(this).attr('max', localStorage['lvl'+numberID+'MaxValue']);
localStorage['lvl'+numberID+'Value'] = localStorage['lvl'+numberID+'MaxValue'];
}
});
};
If you need to keep the keys you have now you still could adapt the above approach to your needs by building your arrays different:
var markers = [
'lvlZeroValue',
'lvlOneValue',
'lvlTwoValue',
'lvlThreeValue',
'lvlFourValue',
'lvlFiveValue',
'lvlSixValue',
'lvlSevenValue',
'lvlEightValue',
'lvlNineValue'
];
var maxMarkers = [
'lvlZeroMaxValue',
'lvlOneMaxValue',
'lvlTwoMaxValue',
'lvlThreeMaxValue',
'lvlFourMaxValue',
'lvlFiveMaxValue',
'lvlSixMaxValue',
'lvlSevenMaxValue',
'lvlEightMaxValue',
'lvlNineMaxValue'
];
and use them like this:
localStorage[markers[numberID]] = localStorage[maxMarkers[numberID]];
Here is a fiddle to see how it works.

i think i fixed it doing this:
jQuery.fn.onTackSet = function(countLocation, numberID){
return this.each(function(){
if(maxMarkers[numberID] == "" || maxMarkers[numberID] == null || maxMarkers[numberID] == 0 ) {
// alert("not else ran");
$(this).attr('value', "0");
$('#spin' + numberID).attr('value', "0");
counterMarkers[numberID] = "0";
maxMarkers[numberID] = "0";
} else {
// alert("else ran");
$(this).attr('value', maxMarkers[numberID]);
$(this).attr('max', maxMarkers[numberID]);
// localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
alert(countLocation);
alert(maxMarkers[numberID]);
// this works but isn't dynamic
// localStorage.lvlZeroValue = localStorage.lvlZeroMaxValue;
localStorage.setItem(countLocation, maxMarkers[numberID]);
// my attempt at making it dynamic doesn't seem to work globally
// counterMarkers[numberID] = maxMarkers[numberID];
}
});
};
$("#spin0").onTackSet("lvlZeroValue", 0);
...but your answer is cleaner. Thanks a lot for your input. I will try it your way. Actually i still need to update the if null, if "" section of this...

Related

JS Retain Initial Value Obtained from Div after Changes to Div from JS itself

I have the following code:
<script>
document.getElementsByName("region").forEach(function(node) {
node.addEventListener("keyup", myFunction);
});
function myFunction() {
var currentPrice = document.getElementById('ms2_order_cost').innerHTML;
if (document.getElementById("region").value == "Ohio" || document.getElementById("region").value == "ohio") {
var currentPriceF = parseFloat(currentPrice);
var newPrice = currentPriceF * 1.0725;
document.getElementById("ms2_order_cost").innerHTML = newPrice;
}
else {
document.getElementById("ms2_order_cost").innerHTML = newPrice;
}
return false;
}
</script>
What I would like is that in the else statement, I get the original value of the div (not the one which is displaying after the If condition is trigerred).
How can I achieve that?
Once you get the initial price from ms2_order_cost and store it in currentPrice, you're not actually manipulating this variable any further. As such, you can simply change your else statement to use currentPrice instead of newPrice:
else {
document.getElementById("ms2_order_cost").innerHTML = currentPrice;
}
As can be seen in the following:
document.getElementsByName("region").forEach(function(node) {
node.addEventListener("keyup", myFunction);
});
function myFunction() {
var currentPrice = document.getElementById('ms2_order_cost').innerHTML;
if (document.getElementById("region").value == "Ohio" || document.getElementById("region").value == "ohio") {
var currentPriceF = parseFloat(currentPrice);
var newPrice = currentPriceF * 1.0725;
document.getElementById("ms2_order_cost").innerHTML = newPrice;
} else {
document.getElementById("ms2_order_cost").innerHTML = currentPrice;
}
return false;
}
Assuming you want to get the value on page load rather than after your trigger, you need to assign the variable after the page loads, but before the function is triggered:
window.onload = function() {
var initialPrice = document.getElementById('ms2_order_cost').innerHTML;
}
And then make use of this variable, as is seen in the following:
window.onload = function() {
var initialPrice = document.getElementById('ms2_order_cost').innerHTML;
}
document.getElementsByName("region").forEach(function(node) {
node.addEventListener("keyup", myFunction);
});
function myFunction() {
var currentPrice = document.getElementById('ms2_order_cost').innerHTML;
if (document.getElementById("region").value == "Ohio" || document.getElementById("region").value == "ohio") {
var currentPriceF = parseFloat(currentPrice);
var newPrice = currentPriceF * 1.0725;
document.getElementById("ms2_order_cost").innerHTML = newPrice;
} else {
document.getElementById("ms2_order_cost").innerHTML = initialPrice;
}
return false;
}
Note that this will only work if the element is available on page load! If it is not, substitute window.onload() for whatever causes your element to be added to the DOM.
Hope this helps! :)

Javascript AddtoCart code not working

I am trying to create essentially a bot that can add a product on Foot Action to my cart. I have this code but it does not work. Can anybody debug it and just explain what I've done incorrectly. My browser is Chrome and I use TamperMonkey.
This an example of the product page:
Footaction product
window.addEventListener('load'
, function() {
var added = false;
function interval1(){
return window.setInterval(function(){
if(document.getElementById("addToCart") != null){
added = true;
window.location = "http://www.footaction.com/checkout/";
}
else if(added == false){
var cartbtn = document.getElementById("addToCartLink");
cartbtn.click();
}
}, 1000);
}
var id1 = interval1();
window.setInterval(function(){
if(added == true){
window.clearInterval(id1);
}
}, 100);
looks like you are missing the last closing squiggly bracket for window.load event
window.addEventListener('load', function() {
var added = false;
function interval1(){
return window.setInterval(function(){
if(document.getElementById("addToCart") != null){
added = true;
window.location = "http://www.footaction.com/checkout/";
}
else if(added == false){
var cartbtn = document.getElementById("addToCartLink");
cartbtn.click();
}
}, 1000);
}
var id1 = interval1();
window.setInterval(function(){
if(added == true){
window.clearInterval(id1);
}
}, 100);
}; // you were missing this line .. the ending squiggly bracket

Javascript Events using HTML Class Targets - 1 Me - 0

I am trying to create collapsible DIVs that react to links being clicked. I found how to do this using "next" but I wanted to put the links in a separate area. I came up with this which works...
JSFiddle - Works
function navLink(classs) {
this.classs = classs;
}
var homeLink = new navLink(".content-home");
var aboutLink = new navLink(".content-about");
var contactLink = new navLink(".content-contact");
var lastOpen = null;
$('.home').click(function() {
if(lastOpen !== null) {
if(lastOpen === homeLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-home').slideToggle('slow');
lastOpen = homeLink;
}
);
$('.about').click(function() {
if(lastOpen !== null) {
if(lastOpen === aboutLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-about').slideToggle('slow');
lastOpen = aboutLink;
}
);
$('.contact').click(function() {
if(lastOpen !== null) {
if(lastOpen === contactLink) {
return; } else {
$(lastOpen.classs).slideToggle('fast');
}
}
$('.content-contact').slideToggle('slow');
lastOpen = contactLink;
}
);ā€‹
I am now trying to create the same result but with a single function instead of one for each link. This is what I came up with....
function navLink(contentClass, linkClass, linkId) {
this.contentClass = contentClass;
this.linkClass = linkClass;
this.linkId = linkId;
}
var navs = [];
navs[0] = new navLink(".content-home", "nav", "home");
navs[1] = new navLink(".content-about", "nav", "about");
navs[2] = new navLink(".content-contact", "nav", "contact");
var lastOpen = null;
$('.nav').click(function(event) {
//loop through link objects
var i;
for (i = 0; i < (navsLength + 1); i++) {
//find link object that matches link clicked
if (event.target.id === navs[i].linkId) {
//if there is a window opened, close it
if (lastOpen !== null) {
//unless it is the link that was clicked
if (lastOpen === navs[i]) {
return;
} else {
//close it
$(lastOpen.contentClass).slideToggle('fast');
}
}
//open the content that correlates to the link clicked
$(navs[i].contentClass).slideToggle('slow');
navs[i] = lastOpen;
}
}
});ā€‹
JSFiddle - Doesn't Work
No errors so I assume that I am just doing this completely wrong. I've been working with Javascript for only about a week now. I've taken what I've learned about arrays and JQuery events and tried to apply them here. I assume I'm way off. Thoughts? Thanks
You just forgot to define navsLength:
var navsLength=navs.length;
Of course you could also replace it with a $().each loop as you're using jQuery.
[Update] Two other errors I corrected:
lastOpen=navs[i];
for(i=0; i < navsLength ; i++)
Demo: http://jsfiddle.net/jMzPJ/4/
Try:
var current, show = function(){
var id = this.id,
doShow = function() {
current = id;
$(".content-" + id).slideToggle('slow');
},
toHide = current && ".content-" + current;
if(current === id){ //Same link.
return;
}
toHide ? $(toHide).slideToggle('fast', doShow): doShow();;
};
$("#nav").on("click", ".nav", show);
http://jsfiddle.net/tarabyte/jMzPJ/5/

How to local storage expand/collapse CSS settings

I'm looking for way to use local storage to remember the CSS settings of a expand/collapse element
so for my JavaScript looks like this (which grabs the id and handles the expand/collapse)
function toggleHeight(id, link) {
var e = document.getElementById(id);
if(e.style.maxHeight == '450px') {
e.style.maxHeight = '0px';
} else {
e.style.maxHeight = '450px';
}
}
So what I am looking for is something that grabs the div id pƄ clicking a link and stores the changes when clicking and then remembering is when refreshing.
Maybe something like this
var height = localStorage.getItem(id+"-height");
localStorage.setItem(id+"-height", height);
As promised here is my solution:
<script type="text/javascript">
function toggleHeight(id, link) {
var e = document.getElementById(id);
var height = localStorage.getItem(id);
if(e.style.maxHeight == '450px' || e.style.maxHeight == 'inherit') {
e.style.maxHeight = '0px';
localStorage.setItem(id,"closed");
} else {
e.style.maxHeight = '450px';
localStorage.setItem(id, "open");
}
}
function load() {
var setting
var e
var link
for (x in localStorage){
setting = localStorage.getItem(x);
e = document.getElementById(x);
link = document.getElementById('forumlink'+x);
if (setting == 'open')
{
e.style.maxHeight = '450px';
}
else
{
e.style.maxHeight = '0px';
}
}
}
</script>
This stores the state of the div when clicked and sets in to open/closed
On page load it grabs the stored value and sets the max-height css after the open/closed value..
Hope some others can make use of this
This is how I solved it: working fiddle
//extra methods to get and set objects in staid of strings
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
//fetch the object or make a new and set constant values
var toggleState = localStorage.getObject('toggleState') || {},
MIN_SIZE= '0px',
MAX_SIZE= '450px';
//shown is an optional parameter
function toggleHeight(id, shown) {
var e = document.getElementById(id);
if(shown === true || (typeof shown === "undefined" && e.style.maxHeight == MIN_SIZE)) {
show(id);
} else {
hide(id);
}
}
function show(id){
var e = document.getElementById(id);
e.style.maxHeight = MAX_SIZE;
toggleState[id] = true;
localStorage.setObject('toggleState',toggleState);
}
function hide(id){
var e = document.getElementById(id);
e.style.maxHeight = MIN_SIZE;
toggleState[id] = false;
localStorage.setObject('toggleState',toggleState);
}
//loop over it to set initial values
for(var i in toggleState){
toggleHeight(i, toggleState[i]);
}
//do manual toggle, hide, show
toggleHeight('someID');ā€‹
You see I separated the show and hide so you can show hide them individually too, if you want or you can still use the toggle method.

Requirejs, Backbonejs browser support function

I need to check whether the browser is supported by my application and I do this the following way:
main.js (main require.js module)
define(['underscore', 'backbone', 'views/mainView', 'views/oldBrowser', 'ui', function(_, Backbone, mainView, oldBrowser){
var _browserHandshaking = function(){
var browserSupportedCookie = $.cookie('browserSupported');
var browserNameCookie = $.cookie('browserName');
var browserVersionCookie = $.cookie('browserVersion');
if(browserSupportedCookie === null){
if(/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'chrome';
} else if(/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'opera';
/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
} else if(/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
$.ui.browserName = 'ie';
} else if(/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'safari';
/Version[\/\s](\d+\.\d+)/.test(navigator.userAgent);
} else if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
$.ui.browserName = 'firefox';
} else if(/webOS/i.test(navigator.userAgent)){
$.ui.browserName = 'webos';
} else if(/Android/i.test(navigator.userAgent)){
$.ui.browserName = 'android'
} else if(/iPhone/i.test(navigator.userAgent)){
$.ui.browserName = 'iphone';
} else if(/iPod/i.test(navigator.userAgent)){
$.ui.browserName = 'ipod';
} else if(/BlackBerry/i.test(navigator.userAgent)){
$.ui.browserName = 'blackberry';
}
if($.ui.browserName !== false){
// Set browser version.
if(!$.ui.browserVersion){
$.ui.browserVersion = parseFloat(new Number(RegExp.$1));
}
for(var browserName in $.ui.supportedBrowsers){
if($.ui.browserName === browserName){
if($.ui.browserVersion >= $.ui.supportedBrowsers[browserName]){
$.ui.browserSupported = true;
break;
}
}
}
$.cookie('browserVersion', $.ui.browserVersion, { expires: 7 });
$.cookie('browserName', $.ui.browserName, { expires: 7 });
$.cookie('browserSupported', $.ui.browserSupported, { expires: 7 });
}
} else {
$.ui.browserSupported = browserSupportedCookie;
$.ui.browserName = browserNameCookie;
$.ui.browserVersion = browserVersionCookie;
}
};
_browserHandshaking.call(this);
var Router = Backbone.Router.extend({
routes: {
"old-browser": "oldBrowser",
"*actions": "main",
},
oldBrowser: function(){
oldBrowser.render();
},
main: function(){
mainView.render();
}
});
$.ui.router = new Router();
// Start routing.
Backbone.history.start({
pushState: true,
root: $.ui.rootDir
});
});
Is there a function in Backbone.js that triggers at every action, there I could easily implement this:
preRouting: function(){
if(!$.ui.browserSupported){
return false;
}
return true;
}
I just need to check, if the browser is supported, and if it is supported it can call the mainView, else the oldBrowser view should be triggered, I just don't want to do this at each route function call.
Someone has a better solution for this? And does someone know if it is possible to create a check that is basically a prelimiter for a route function call.
Thanks for help :)
Based on comments, you can check for push state with: (from Can use pushState )
var hasPushstate = !!(window.history && history.pushState);
css3 animations with: ( from Detect css transitions using javascript (and without modernizr)? )
function supportsTransitions() {
var b = document.body || document.documentElement;
var s = b.style;
var p = 'transition';
if(typeof s[p] == 'string') {return true; }
// Tests for vendor specific prop
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'],
p = p.charAt(0).toUpperCase() + p.substr(1);
for(var i=0; i<v.length; i++) {
if(typeof s[v[i] + p] == 'string') { return true; }
}
return false;
}
var hasCSS3Transitions = supportsTransitions();
There's no need to check the browser name/version if you can simply check to see if the browser has the functionality your application needs.

Categories