JavaScript - Cookie To Localstorage?
Hello all, I need some help here. I'm new to HTML 5 and I'm not sure how to convert my cookie script over to HTML 5 LocalStorage. If anyone could help, I would appreciate it greatly.
Here's my cookie script: Code: var currentRotation=null; function checkOrientAndLocation(){ if(currentRotation != window.orientation){ setOrientation(); } } function setOrientation(){ switch(window.orientation){ case 0: orient = 'portrait'; break; case 90: orient = 'landscape'; break; case -90: orient = 'landscape'; break; } currentRotation = window.orientation; document.body.setAttribute("orient",orient); setTimeout(scrollTo,0,0,1); } $(window).unload(function() { // On page unload $('.remember').each(function() { // Save each value to expire in a year $.cookie(this.id, this.value, {expires: 365}); }); $('.draggable').each(function() { // Save draggable positions var draggable = $(this); $.cookie(this.id, draggable.css('top') + '_' + draggable.css('left'), {expires: 365}); $.cookie('disp' + this.id, draggable.css('display'), {expires: 365}); }); }); $(function() { var val, pos, disp; setInterval(checkOrientAndLocation,1000); $('.remember').each(function() { var val = $.cookie(this.id); // Retrieve value for this element if (val) { this.value = val; } } ); $('.draggable').each(function() { var pos = $.cookie(this.id); // Retrieve values for this element if (pos) { pos = pos.split('_'); $(this).css({position: 'absolute', top: pos[0], left: pos[1]}); } var disp = $.cookie('disp' + this.id); if (disp) { this.style.display = disp; } } ).touch({animate: false, sticky: false, dragx: true, dragy: true, rotate: false, resort: false, scale: false }); }); Similar TutorialsI am working on a Phonegap app that sends emails that consist of form data that is filled out within the app. I need my app to send the emails which I have sorted out. The second part of the app needs to store the email subject of all the mails that are sent in local storage and then in a separate function needs to output all the saved data and send it. I will post my full code below and comment the important bits. Code: function sendMail(imageURI, click){ var d = new Date(); var dat = d.getDate(); var mon = d.getMonth(); var year = d.getFullYear(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var todayDate = dat+'-'+mon+'-'+year+' | '+hours+':'+minutes+':'+seconds; var agent = $('#agent').val(); var depot = $('#selection').val(); var date = $('#free').val(); var newURI = imageURI.replace("file:///storage/emulated/0/DCIM/Camera/",""); /* -----> the variable that needs to be stored */ var newFileName = 'N' + result + '_' + agent + '_' + todayDate + '_' + newURI + '_' + depot + '_' + date; /* -----> storing the variable */ var temp = localStorage.getItem('newFileName'); var somearray=temp.split(','); somearray_length=somearray.length; somearray[somearray_length]=newFileName; var somestring=somearray.join(','); localStorage.setItem('newFileName',somestring); /* <----- storing the variable */ var largeImage = document.getElementById('largeImage'); largeImage.style.display = 'block'; largeImage.src = imageURI; cordova.plugins.email.addAlias('gmail', 'com.google.android.gm'); cordova.plugins.email.open({ app: 'gmail', to: 'blah@gmail.com', subject: newFileName, body: '<ul><li style="font-weight:bold;text-decoration: underline;"><b><u>File: </b></u></li><li>'+newURI+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Agent Name: </b></u></li><li>'+agent+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Next Scheduled Date: </b></u></li><li>'+date+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Scanned: </b></u></li><li>'+todayDate+'</li><br><li style="text-decoration: underline;font-weight:bold;"><b><u>Depot: </b></u></li><li>'+depot+'</li></ul>', attachments: [imageURI], isHtml: true }); }; /* -----> The second function */ function endOfDay(data){ var d = new Date(); var dat = d.getDate(); var mon = d.getMonth(); var year = d.getFullYear(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var todayDate = dat+'-'+mon+'-'+year+' | '+hours+':'+minutes+':'+seconds; ending=localStorage.getItem('newFileName'); var salesman = $('#agent').val(); var newsFileName = 'End of Day Report for Agent: ' + salesman + '|' + todayDate; cordova.plugins.email.addAlias('gmail', 'com.google.android.gm'); cordova.plugins.email.open({ app: 'gmail', to: 'seth.v.staden@gmail.com', subject: newsFileName, body: 'end of day report: <br>' + ending, isHtml: true }); localStorage.setItem('newFileName',''); }; my problem is that instead of outputting all the sent subjects that have been stored like so: "subject 1, subject 2, subject 3, etc..." it is outputting it as the latest mail that was sent, i.e. "subject 3, subject 3". I have no clue why this is going wrong or how to fix it... any help would be greatly appreciated. Reply With Quote 01-15-2015, 11:13 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Instead of doing all this tortu Code: var temp = localStorage.getItem('newFileName'); var somearray=temp.split(','); somearray_length=somearray.length; somearray[somearray_length]=newFileName; var somestring=somearray.join(','); localStorage.setItem('newFileName',somestring); Why not simply do Code: localStorage.setItem('newFileName', localStorage.getItem('newFileName') + "," + newFilename ); Though I admit I don't see why your code won't work. It just causes a bunch of unneeded overhead. ********** COMMENTARY: I think your dates will be unreadable by humans. var mon = d.getMonth(); That will get a ZERO for January, 1 for February, etc. For human readable, you should do var mon = d.getMonth() + 1; Hello, I apologize if this is not in the right forum as part of my question may not be reated to javascript but I have the following problem(s). I am attempting to make a website that has three pages: index.html customize.html home.html The index page needs to have an onLoad script that does several things: 1. Checks whether the browser supports localStorage and branches to either LSYes() or LSNo() accordingly 2. LSYes has to check whether a value of NY=True or NY=False has been set in local storage. If neither has been set it redirects to customize.html, otherwise it redirects to home.html. 3. LSNo has to perform a similar check and redirect as LSYes by checking for a cookie containing the appropriate value. The customize page has to have an onLoad script that detects whether localStorage is supported and somehow be able to pass that value to another script that is called later on from a form on the page. It also has to have another script that is called from rhe form that can handle any/all of the following conditions: 1. Checking a zipcode entered in the form against a list of NY zipcodes to determine whether the person lives in NY. 2. Save the value of NY=True if it finds a match or NY=False if it doesn't in either localStorage or a cookie based on the results of the onLoad script. 3. Allow the user to clear any values that may be saved and save new values if the user moves in or out of NY. The home page needs to likewise detect whether localStorage is supported. If localStorage is not detected it has to: 1. Check for either NY=True or NY=False in the cookie 2. Change the expiration date on the cookie to one year from the current date even if the cookie has not expired. 3. Completely hide certain sections of the page if it detects a value of NY=false or if a person navigates to the page without NY value being set but show them if NY is set to true. If localStorage is detected it has to perform similar functions using localStorage. In each case, if the browser supports localStorage that is to be used instead of a cookie. There are several things this site needs to do that are beyond my current skill levels. 1. localStorage detection 2. Comparing a zipcode entered on the form to a list of NY zipcodes without making the script huge and slowing down page loading. 3. Automatically changing from index to either home or customize based on whether localStorage has been set for the site. 4. Hiding or showing sections of a page based on a value in localStorage. I have an idea how to do some of this with a cookie but when I try it it acts like no cookie is present even though I know it is so I am not sure what I am doing wrong there. I have been trying to teach myself by putting parts of various scripts that each perform part of what I need together but this approach isn't working right. Thanks for your help Anello I'm trying my hand at localstorage (which is HTML5), but I'm combining it with javascript (which is... erm, well, javascript ) so I decided to put this in the javascript forum. If I'm wrong, I apologize. Anyway, though I'm not a complete newbie when it comes to coding, this is new for me and frankly, I'm stuck. What I'm trying to do (nothing special, just messing around a bit) is show the current time and the time the visitor last visited. I made this: Code: var tijd = new Date(); var oudetijd = tijd.getTime(); localStorage.setItem('laatste bezoek', oudetijd); var laatstebezoek = localStorage.getItem('laatste bezoek'); document.write(laatstebezoek + "<br>"); document.write(oudetijd); Should work, right? Well, it does... partly. It shows the current time (woohoo!!! ) but the "old time" (oudetijd) is exactely the same! Now, I know I'm doing something wrong here, most likely something stupid like a missing comma, but whatever it is, I don't see it. Can someone shed some light on this? P.S. As you can probably see from the code, I'm Dutch. I dont know if it helps or not, but here's a translation: tijd= time oude tijd = old time laatste bezoek = last visit Thanks in advance! Hi all, I've been experimenting with Local Storage. I can do things like this just fine: localStorage.setItem('variable_name', variable_value); // write a value var variable_value = localStorage.getItem('variable_name'); // read a value localStorage.removeItem('variable_name'); // delete a value But if I do this: var object = { width : w, height : h }; ...then place it in local storage, reading it back gives me a TEXT STRING that says "[Object object]" and not the actual object. I would like to be able to store multiple values in one object, but it doesn't seem to work. I also tried to store a variable obtained with "document.getElementById" and when read back it just says [HTMLDivElement] (something like that) instead of the actual element. Am I doing something wrong, or does local storage not support objects? (btw, tested on FF 3.6). Thanks! -- Roger So. When I save a boolean to localStorage It converts it to string. PHP Code: localStorage["fixedBackground"] = document.getElementById("fBackground").checked; And that saves a 'true' or 'false' string. So to convert it to a boolean value, in the 'restore options' I use the function 'toBool' PHP Code: function toBool(str) { if ("false" === str) return false; else return str; } PHP Code: var value = localStorage["fixedBackground"]; if (null != value) document.getElementById("fBackground").checked = toBool(value); And that works just fine. However, I want to recall this saved data in a javascript. I want an PHP Code: if (value = true){ document.getElementsByTagName('body')[0].style.backgroundAttachment="fixed"; } But I can't get a 'toBool' type of function into that statement This is my method of retrieving the data: PHP Code: var port = chrome.extension.connect({name: "knockknock"}); port.postMessage({get: "fixedBackground"}); port.onMessage.addListener(function(msg) { //Set bgimage attachment javascript:value=msg.value; which makes the full if statement: PHP Code: var port = chrome.extension.connect({name: "knockknock"}); port.postMessage({get: "fixedBackground"}); port.onMessage.addListener(function(msg) { //Set bgimage attachment javascript:value=msg.value; if(value = true) { document.getElementsByTagName('body')[0].style.backgroundAttachment="fixed"; } }); any ideas? Howdy So i am working on a piece that using local storage and saves them to an un ordered list. I have been using Chrome for the console and inspector abilities and it has been going well. I've tested it before in Safari and Opera and I know it works. However, in Firefox (and IE but I don't care about that) I am getting a console error. Here is the code being executed: Code: var i=0; while (localStorage.key(i) != null) { var values = localStorage.getItem(localStorage.key(i)); values = values.split(";"); $("#logscreen").append("<li class='arrow logname'><a href='#' class='direct' onclick='...'>" + values[0] + "</a></li>"); i++; } There is some jQuery thrown in there but basically it says, test for a localStorage key of i, if it is not null create the list item, add one to i and repeat. I am getting the following error in firefox only: Index or size is negative or greater than the allowed amount" code: "1 [Break on this error] while (localStorage.key(i) != null) Any ideas folks? Hey there. I've recently written a small javascript library that creates a unified interface for localStorage and sessionStorage. The code is here http://github.com/AndrewLowther/StorageItem I'm looking for people to give me feedback and to help me work on it should you so wish. Feedback is most welcome! Hi everyone, I am using a jQuery cookie script to set the cookie of some elements on my website. One of the problems is that I need the cookie to not expire after one day, I need it to expire after a while (I'm going to start off with a year). Here's my script, the red part is what I've been editing. Code: /** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secu true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000 * 365)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // CAUTION: Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } }; Hi im new to working with cookies so would appreaciate a little help I using the w3c tuturial as a template so heres a link so you can see what im trying to do http://www.w3schools.com/JS/js_cookies.asp Code: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie(username) { var username=getCookie("username"); if (username!=null && username!="") { document.getElementById("feedback").innerHTML = " last time you scored " + username); setCookie("username",username,365); } else { if (username=null || username="") { setCookie("username",username,365); } } } I kept the variable names the same so you can follow and I don't confuse myself and make things more complected while im trying to debug it. Some extra information. checkcookie is been given a variable it is just a simple number. Im making a questionnaire which is done but I wont the top of the page to tell the user how much they scored last or tell them this is their first time trying it. The variable being passed to check cookie is their score . at the moment when I click the submit button nothing happens. Where it should trigger a score calculating function which should then call the checkcookie function while passing the score it calculated. I would love if someone can point me in the right direction or help me correct it or atleast explain to me whats going wrong. Thanks and a lots of appreciation if anyone can spare the time Hi everyone! Got a quick (cookie) question. I looked on the internet for some cookie scripts (redirect ones), but unfortunately haven't been too lucky with these. What I want to do is the following: When the cookie is not found it goes to my main page, for example: "www.anynamehere.com" On the main page I can select where I want to go - 'Contacts', 'News', 'Forums' and so on. The main page has a drop down list with these options, each option has it's own link. When I click on 'continue' and go to the specific link (ex. www.anynamehere.com/contacts.html) it should remember my selection, so next time I log into www.anynamehere.com it's automatically will take me to contacts.html. I will not see the main page anymore. Now, if from the contacts page I select 'News' and go to www.anynamehere.com/news.html it has to remember that link as well. So if I close my browser and then reopen it, it should take me to www.anyname.com/news.html. I hope that makes sense. If anyone can give me any pointers I would greatly appreciate it. Maybe there is a script like that available online, I just wasn't lucky enough to find one. Thank you in advance! Hello. I am a neewb, so bare with me. This code is not working correctly for some reason. If I use it in Internet Explorer it will work, but only if you bring up the history in the url tab. You cannot refresh it for whatever reason. so basically it works in Explorer but no refresh. The big problem is Mozilla. I will not work at all. I have all of the cookies set for third party, remember last visit and so on. It will only display the welcome page for first time visitor. Then it will show the subsequent page, however it will not increment the count +1. I am not sure what is going on here, Explorer works, but with no refresh, and Mozilla does not really work at all? Here is my script currently: <script type="text/javascript"> /* <![CDATA[ */ function hitMySite() { var lastDate = new Date(); lastDate.setMonth(lastDate.getMonth()); var dateString = (lastDate.getMonth() + 1) + "/" + lastDate.getDate() + "/" + lastDate.getFullYear(); if (document.cookie != "") { counter = document.cookie.split("=")[1]; counter = parseInt(counter) + 1; date = document.cookie.split(":")[2]; var expireDate = new Date(); expireDate.setMonth(expireDate.getMonth() + 12); document.cookie = "counter=" + counter + ":date:" + dateString + ";expires=" + expireDate.toGMTString(); document.write("<h1>You last visited this page on: " + date + "<br />You have been to this page " + counter + " times.</h1>"); } else { document.write("<h1>Welcome to my Web site! This is your first visit here so be sure to bookmark my page!</h1>"); var counter = 1; var expireDate = new Date(); expireDate.setMonth(expireDate.getMonth() + 12); document.cookie = "counter=" + counter + ":date:" + dateString + ";expires=" + expireDate.toGMTString(); } } /* ]]> */ </script> </head> <body onload="hitMySite()"> </body> </html> Hi im kind of new to cookies in Javascript. But after reading a few tutorials on how the work I started to wonder. Is it possible to grab a cookie made by my phpbb forum? I would love to be able to login on my site using my phpbb forum cookies. Anway if this is a bad idea ore won't work for any reason plz let me know. Thanks Hello there, Could someone tell me how a javascript can get a cookie and use it as a parameter like www.mysite.com?search=COOKIEDATA Thanks you (a) Hello I have below script i need add cookie to it . disable script untill cookie is not expired can you please help me <script language=javascript type="text/javascript"> <!-- Hide script from old browsers //new window script function jshow() {window.open("http://www.google.com","blank")} // End hiding script from old browsers --> </script> I am running a vBulletin and am using a script to set a cookie each time someone clicks a banner. When the user then reloads the page it looks for that cookie and hides the banner if the cookie exists. I now want to write the date into the cookie name so that the cookie name changes every day. I want to do this because for some reason the cookie gets re-written sometimes and never expires. Because of vBulletin and Firefox I have to use PHP to check initially if the cookie is even set. Here is my current script, any help would be appreciated. Code: <?PHP if( isset( $_COOKIE['noads139'] ) ) { } else { ?> <script type="text/javascript"> function as_click () { myDate = new Date(); myDate.setTime(myDate.getTime()+(1*24*60*60*1000)); document.cookie = 'noads139=noads139; expires=' + myDate.toGMTString()+"; path=/" } // incredibly funky onload add-event scripting, for all browsers if(typeof window.addEventListener != 'undefined') { //.. gecko, safari, konqueror and standard window.addEventListener('load', adsense_init, false); } else if(typeof document.addEventListener != 'undefined') { //.. opera 7 document.addEventListener('load', adsense_init, false); } else if(typeof window.attachEvent != 'undefined') { //.. win/ie window.attachEvent('onload', adsense_init); } //** remove this condition to degrade older browsers else { //.. mobile safari, mac/ie5 and anything else that gets this far //if there's an existing onload function if(typeof window.onload == 'function') { //store it var existing = onload; //add new onload handler window.onload = function() { //call existing onload function existing(); //call adsense_init onload function adsense_init(); }; } else { //setup onload function window.onload = adsense_init; } } function adsense_init () { if (document.all) { //ie var el = document.getElementsByTagName("iframe"); for(var i = 0; i < el.length; i++) { if(el[i].src.indexOf('googlesyndication.com') > -1) { el[i].onfocus = as_click; } } } else { // firefox window.addEventListener('beforeunload', doPageExit, false); window.addEventListener('mousemove', getMouse, true); } } //for firefox var px; var py; function getMouse(e) { px=e.pageX; py=e.pageY; } function findY(obj) { var y = 0; while (obj) { y += obj.offsetTop; obj = obj.offsetParent; } return(y); } function findX(obj) { var x = 0; while (obj) { x += obj.offsetLeft; obj = obj.offsetParent; } return(x); } function doPageExit(e) { ad = document.getElementsByTagName("iframe"); for (i=0; i<ad.length; i++) { var adLeft = findX(ad[i]); var adTop = findY(ad[i]); var inFrameX = (px > (adLeft - 10) && px < (parseInt(adLeft) + parseInt(ad[i].width) + 15)); var inFrameY = (py > (adTop - 10) && py < (parseInt(adTop) + parseInt(ad[i].height) + 10)); if (inFrameY && inFrameX) { myDate = new Date(); myDate.setTime(myDate.getTime()+(1*24*60*60*1000)); document.cookie = 'noads139=noads139; expires=' + myDate.toGMTString()+"; path=/" } } } //end for firefox </script> <?PHP } ?> <div id="adsense" style="display: none"> <script type="text/javascript"><!-- google_ad_client = "pub-xxxxxxxxxxxxxxx"; /* 728x90, created 4/15/10 */ google_ad_slot = "xxxxxxxxxxxxxx"; google_ad_width = 728; google_ad_height = 90; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </div> <script type="text/javascript"> if (document.cookie.indexOf('noads139') < 0) { document.getElementById('adsense').style.display = ''; } else { } </script> <script type="text/javascript"> if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) { document.getElementById('adsense').style.display = 'none'; } else { } </script> Hi i used cookies to store data using java script with 2 calculators, but there is a 3rd calculator that the cookies arent storing, can someone help me figure out where to implement the script?
Frnds,i need some help related to cookie handling in JS.Suppose i created a cookie with an expiration time of 1 month.Now,for the time my current browser session is running,the cookie is stored in browser memory.When the browser is closed,the cookie gets written to HD.(I need to know where it is written). Next day,when the script page is opened,the browser should check the cookie created last day and display its value in the page.. Does this operation handled by document.cookie call??I mean..setting cookie will definitely require this call,but what about fetching it back next day???what call should be used for fetching... Hi, i have a page with two links on it called link1 and link2, when link1 is clicked it creates a cookie called link with the value link1, when link2 is clicked it creates a cookie called link with the value link2. Also when the links are clicked they produce an overlay like light box with the cookie contents echod inside it. That all works fine apart from if i click link1 and then close the overlay and click link2 the overlay still displays "link1" instead of displaying "link2" even tho the cookie has updated correctly. See it live HERE and heres the source code im using: link.php: Code: <html> <head> <style> .black_overlay{ display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80); } .white_content { display: none; position: absolute; top: 25%; left: 25%; width: 50%; height: 50%; padding: 16px; border: 16px solid orange; background-color: white; z-index:1002; overflow: auto; } </style> <script language="JavaScript"> function lightbox() { document.getElementById('light').style.display='none'; document.getElementById('fade').style.display='none'; <? $link = $_COOKIE["link"]; ?> } function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); document.getElementById('light').style.display='block'; document.getElementById('fade').style.display='block'; } </script> </head> <body> <p><a href = "javascript:void(0)" onclick = setCookie('link','link1',365)>Link 1</a></p> <p><a href = "javascript:void(0)" onclick = setCookie('link','link2',365)>Link 2</a></p> <div id="divCustomerInfo"><?PHP echo $link;?></div> <div id="light" class="white_content"><? include('include_me.php'); ?> <a href = "javascript:void(0)" onclick = lightbox()></a></div> <div id="fade" class="black_overlay"></div> </body> </html> And include_me.php Code: <?PHP $link = $_COOKIE["link"]; echo $link ?> <html> <head> </head> <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a> </body> </html> Hi, I want to know how we can get the cookie size. In Mozilla firefox i got Name Value Host Path Expire. The same way i want to get cookie size also . Please advise me how can i get it using javascript. anyone can help me in cookie ? i couldn't get it to work. My objective is when i click the submit button in the guestbook page, the cookie will then capture just the 'name' and display it out in thankyou page. guestbook page var seconds = 0; function startTimer() { window.setInterval("updateTime()", 1000); } function updateTime() { seconds++; soFar.innerText = seconds; } function validate_email(field) { with (field) { apos=value.indexOf("@"); //find the position of the @ character dotpos=value.lastIndexOf(".");// find the last position of the . character if (apos<1||dotpos-apos<2) { alert("Not a valid e-mail address!"); return false; } } } function validate_length(field) { with(field) { if (value.length == 0) { alert("Please fill up the column!"); return false; } } } function getCookie(NameOfCookie){ if (document.cookie.length > 0) { begin = document.cookie.indexOf(NameOfCookie+"="); if (begin != -1){ begin += NameOfCookie.length+1; end = document.cookie.indexOf(";",begin); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(begin, end)); } } return null; } function setCookie(NameOfCookie, value, expiredays) { var ExpireDate = new Date (); ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 *3600 * 1000)); document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null)?"" : ";expires=" + ExpireDate.toGMTString()); } function delCookie (NameOfCookie){ if (getCookie(NameOfCookie)){ document.cookie = NameOfCookie + "=" + "; expires=Thu,01-JAN-70 00:00:01 GMT"; } } function validate_form(thisform) { with (thisform) { if (validate_length(yourname) == false) { yourname.focus(); return false; } if (validate_length(email)==false || validate_email(email)==false) { email.focus(); return false; } if ( ( document.contact_my.gender[0].checked == false ) && ( document.contact_my.gender[1].checked == false ) ) { alert ( "Please choose your Gender: Male or Female" ); valid = false; contact_my.focus(); return false; } } } </script> <form name="contact_my" action="thankyou.html" onSubmit="return validate_form(this)" && onClick="setCookie" method="post" > <input type="submit" value="Submit"> <input type="reset" value="Reset form" onClick="delCookie( 'username' )"> thankyou page function getCookie(NameOfCookie){ if (document.cookie.length > 0) { begin = document.cookie.indexOf(NameOfCookie+"="); if (begin != -1){ begin += NameOfCookie.length+1; end = document.cookie.indexOf(";",begin); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(begin, end)); } } return null; } function setCookie(NameOfCookie, value, expiredays) { var ExpireDate = new Date (); ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 *3600 * 1000)); document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null)?"" : ";expires=" + ExpireDate.toGMTString()); } function DoTheCookieStuff() { username=getCookie ('username'); if ( username!=null ) {document.writeln ('Hi there '+username+' - Good to see you again!')} } |