Manipulaitng javascript cookie on blur , focus ,onload and tabclose? - javascript

I will try to be as clear as possible.
Ok.I am making a simple tracker where it becomes very important for me to track user behaviour .I am using a javascript cookie for this purpose.
what I do :
After tracking the user,I get some data which I store in a javascript object literal.
var object = {
home-page :0-30,
brand-page:0-90,
mark-page :0-20,
home-page :0-10
}
I JSON.stringify the object to store the object value in a cookie.
MyQuestion :
Considering that there are two tabs opened and that I write some data in my cookie on second tab...would I get that latest data on window.focus of first tab if i read the same cookie?
Now when I come on the first tab,I want to update a property of my object(for example..home-page:0-30 is to be updated ),without altering
its order and updating the wrong property.
Can anybody guide me on this?

First you json is incorrect, it should contain only one unique id
var object = {'home-page' :'0-30', 'brand-page': '0-90', 'mark-page' : '0-20'}
Answer to you first question, yes you will get the updated data from second tab if both the tab have same domain.
Second Question: Yes you can update the same cookie and update the user info in same cookie.
You can check the steps at http://jsfiddle.net/raunakkathuria/fhe27/2/

Related

activating checkbox on load with javascript or jQuery

hello I have a small project I'm working on.
the project is calling an API with ajax and getting info about currencies, one of the things I'm stuck on is that I have to write them in cards that include a checkbox that has to stay activated after I refresh the page.
any suggestions?.. please I'm desperate
When you make your call on your API just set the checked value on the correct checkbox, please have in mind that setting checked=false will still give you a checked checkbox.
<input type="checkbox" checked>
One way to preserve information against a page refresh is to use localStorage.
LocalStorage allows you to store key:value variable pairs in the local browser. You can view the localStorage values for any given website in DevTools F12, on the Application tab. The variables are stored by website, and remain as they are until (a) they are deleted, or (b) browser cache is cleared. (For more info on when localStorage is cleared, see this answer).
LocalStorage is dead-simple to use:
let myPet = 'Cat';
localStorage.setItem('animal', myPet);
And to read it:
let myPet = localStorage.getItem('animal');
What you might want to do in your project, perhaps on a timer - or after the ajax call - is loop through your fields and create an object with all the fieldnames/values. Then use JSON.stringify to turn the object into text that you can store in a localStorage variable.
Note that you will need to write something that on page load ( $(document).ready() ) will see if the fields are empty and if there is a RECENT localStorage variable (so, you might want to create second localStorage variable (you can have MANY) that has the last-updated datetime) then you read the JSON string into a javascript object and populate your field values.
I would recommend using a dictionary, putting something unique like an ID of those currencies that are checked at that time.
If the new answer you get has the same currencies as before plus more, you can use that dictionary in memory to check those items again. If you don't get the previous response, you can just add those new items to avoid unchecking the checked currencies.
Exmaple:
var dictionary = {};
// here you should do a forEach in currently checked currencies
...
dictionary[id] = value; // (true, because it is the value of checked)
Hope it helps you.

get Elements By Class Name from other page

I have this
console.log(document.getElementsByClassName('value')[0].innerHTML);
Is there possibility to get this value from other page (without manually open this page)?
Can i get all value from page? Now when i use it i see only first value
Is there possibility to get this value from other page (without manually open this page)?
Without opening that page no, only from the current window (I assume this is what you mean when you're saying "page").
Can i get all value from page? Now when i use it i see only first value
Yes, document.getElementsByClassName('value') returns an array i.e exactly what you need. In your example you're just selecting the first element from the array, that's why you see only the first value.
Try this:
var all=document.getElementsByClassName('value');
for(var i=0;i<all.length;i++){
console.log(all[i].innerHTML);
}
....
Yes it's possible.
Create an AJAX request to get the website you need to extract values from. This StackOverflow answer provides dependency-free example code.
You can then parse the request using DOMParser, which is supported by all major browsers.
Set your value to local storage :
Set value to local storage localStorage.setItem('key', 'value');
Get value from another page localStorage.getItem('key');
Set your data
var data = document.getElementsByClassName('value')[0].innerHTML;
localStorage.setItem('value', data);
Get it from another page
localStorage.getItem('value');
Documentation : https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
Otherwise you can use sessionStorage, Web SQL, IndexedDB & Cookies.

Overwriting Javascript cookie with data from another cookie

This seems like a fairly simple question... I am trying to overwrite the data from cookie a with the data that is stored in cookie b but without changing either of the names of the cookies. Cookie b contains the particular user's defaults while cookie a stores the users current selections.
I have looked online and taken a few shots in the dark but, I have no leads! Everything that I've tried overwrites the entire cookie and I only want the data in cookie a to be changed, with no changes to the names of the cookies or to the data of any other cookies
Is this possible? If so how can I accomplish this task?
Thank you in advance!
Here's the code. It's commented enough to answer the question:
//first, get the "b" cookie's value
var cooks=document.cookie;
//just the "b" part of the cookie string
var bStartIndex=cooks.indexOf('b=')+2; //get the start of the b part of the string
var bEndIndex=cooks.indexOf(';',bStartIndex); //and the end of it
//and then extract the actual variable value from it
var b=cooks.slice(bStartIndex,bEndIndex!==-1?bEndIndex:null); //in case b was the last var, there would be no ; after it, so bEndIndex would be -1
//now, we set a to that
document.cookie='a='+b; //I don't THINK this will overwrite other cookies
I haven't tested it, but it SHOULD work. Tell me if it doesn't and I'll try to fix it
There are probably libraries out there that could make this a lot easier, if you're planning to use this in production

Get Titanium.App.Properties in another win or make it global available

Please don’t answer this if you don’t take the time to understand my question or have a reasonable answer. I have got a few answers that is far on the side and I think I explain my problem very clear. Shall this problem drive me nuts or is there somebody out there with a straight and clear answer on Titanium.App.Properties?
I have a login form that stores the username in one:
Titanium.App.Properties.setString("userName",e.value);
and the password in another:
Titanium.App.Properties.setString("passWord",e.value);
The forms TextFields holds these values(after a store) even if I close the window, shut down and restarts the app. This because of the App.Properties.getString("value"); I suppose….?!
But when I copy the hole form with its App.Properties.getString("value"); to another window, the TextFields are empty and contains no value at all. I understand that the Properties string must be there some where in App.Properties, but how can grab it and use it another place in the app?
My question is: How to get the value from my
var userNameValue = Titanium.App.Properties.getString("userNameValue");
to be available in another window or for the hole app(global)? How can I grab it and make use of it a another place in the app? I don’t see a good reason to make these, only separate words, into objects(JSON) since the userName only contains a e-mail address and the passWord consist only of continuing letters or numbers. But if you mean I have too, -how do I set this from my TextField and get it in another TextField somewhere else in my app. I have not had any luck so far. I hope you can help me out and I can keep sane.
Titanium.App.Properties.getString("userNameValue");
This is globally Available, any Propertie of the Titanium Object is accessible in each file.
but if for some reason this doesnt work for you and you want to set a global variable,
you could do the following:
Create a file called myGlobals.js //or anything else,
//Put this in there e.g
var myProperties = {};
in any file you want to use it write in the first line
Ti.include('myGlobals.js');
Then you can make a propertie global available, for example write this in app.js somewhere where the app initializes
myProperties.Username = Titanium.App.Properties.getString("userName");
Then you can get the value in each file by accesing the propertie
myProperties.Username
//of course the Propertie has to be set before you can get them
( Titanium.App.Properties.setString("userName",e.value); ) //like you do it
But, Titanium.App.Properties.getString("userName");
should be avilable from any file anyway, (but you can give this a try although i dont think its nice to do it like this)
i had a similar problem where this didnt get any value from a propertie set in the ios settings as default value.
I had to go to the settings and manually change or edit the default value and then after a restart
Titanium.App.Properties.getString("userName");
returned the value as it should,
i hope this helps you =)
Answer to the Comment
I'm glad i could help you =)
Yes you can Use an focus EventHandler like this :
textfield.addEventListener("focus",function(){
textfield.value = "Test";
});
Beside that , are you using the identical Textfield for both windows ? like
var Textfield = Ti.Ui.createTextField({...});
and add it to 2 different windows ?
win1.add(Textfield);
win2.add(Textfield);
That led for me to Problems with labels in TableViewRows, using an identical Row 2 times in the TableView
The Text displayed only on 1 Label, sometimes it switched the Labels
I think you can't add one and the same titanium object to more then one other object
Maybe that could be the culprit,
dunno just an idea =)

How to use a var that has been set in one html file in another html file?

I have a html page that sets a value onclick using a js function. I need to use this value in another html page. I am unable to do it. It seems to reset the value when I use the value from the second page. The .js file has been included in both the html pages. How do I retain the set value across multiple html pages?
Within JavaScript itself, you cannot keep track of variables across page loads. To pass the variable from one page to another, you will need to use a 'man in the middle' to help out. Either a cookie, or a query string.
A cookie would work great! I won't go into specifics of setting/getting cookies in JavaScript as there is excellent documentation here:
http://www.w3schools.com/JS/js_cookies.asp
Using those set and get methods (which of course you could customise to suit your needs):
First page:
var yourVariableToSave = 'I like cheese and crackers';
var numDays = 10; //How long the cookie should last.
setCookie('SomeCookieName', yourVariableToSave, numDays);
Second page:
var yourVariable = getCookie('SomeCookieName');
alert(yourVariable); //Displays 'I like cheese and crackers'
If you only want the cookie to last the duration of the current settings, you can modfy the setCookie function to not specify an expiry date.
If this is for a single request, a query string might be useful. To do this, you could append ?someQueryStringName=YourVariableValue to all links on the page, or inject the query string when the user is about to load another page. I won't go in depth with this option as I suspect a cookie may be a bit better.

Categories