JavaScript - Cookie Reading/incrementing/updating
Novice Javasript query.
My requirement: Each time a visitor arrives at a specific webpage i want the main image on the page to be different, or more specifically, one of 6 images which will be shown in rotation. Solution: Set a cookie. Each time the visitor access the page read the cookie and display the corresponding image. Then increment the value and rewrite the cookie, so that next time they'll see the next image in sequence. NB: if the cookie does not exist (first timer) or is at 6, then the value is set to zero (and then incremented). Problem: Can't get my coding to work. Specifically it just doesn't do anything - no error message, no cookie written. I'm a very novice scripter, as in I've cobbled the coding together from bits off the net that i think i've managed to grasp some kind of an understanding of. Very suck it and see - so far lots of sucking and no seeing! Anyway here's my code - if someone could cast a beady eye it would be much appreciated. Hopefully I'm not a million miles out !!! Code: <script type="text/javascript"> /*<![CDATA[*/ var cookies = document.cookie; if (cookies.indexOf(pookie) == -1) { var pookey = 0; } else { var startpos = cookies.indexOf(name)+name.length+1; var endpos = cookies.indexOf(";",startpos)-1; if (endpos == -2) endpos = cookies.length; var pookey = cookies.substring(startpos,endpos); if (pookey == 6) pookey = 0; } pookey = pookey++; var expire = new Date (); expire.setTime(expire.getTime() + 1000 * 60 * 60 * 24 * 365); document.cookie = name + "=" + pookie + "; expires=" + expires.toGMTString() + "; path=/"; if (pookey == 1) document.write ("<img src=\"../HomePage/Image1.jpg\" />"); if (pookey == 2) document.write ("<img src=\"../HomePage/Image2.jpg\" />"); if (pookey == 3) document.write ("<img src=\"../HomePage/Image3.jpg\" />"); if (pookey == 4) document.write ("<img src=\"../HomePage/Image4.jpg\" />"); if (pookey == 5) document.write ("<img src=\"../HomePage/Image5.jpg\" />"); if (pookey == 6) document.write ("<img src=\"../HomePage/Image6.jpg\" />"); /*]]>*/ </script> Thanks in advance for any help... Similar TutorialsHello, I'm working with a cooking script that redirects a user if he has already visted the page. Currently, it's set to expire every 24 hours. However, I'd like to have it expire at midnight everyday. How would I change this? Code: <script> num_days = 24; function ged(noDays){ var today = new Date(); var expr = new Date(today.getTime() + noDays*60*60*1000); return expr.toGMTString(); } function readCookie(cookieName){ var start = document.cookie.indexOf(cookieName); if (start == -1){ document.cookie = "seenit=yes; expires=" + ged(num_days); } else { window.location = go_to; } } var go_to = "/development"; readCookie("seenit"); </script> 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; } }; This works: Code: <div id="oDiv" style="width:300;height:100;background-color:#000000;"></div> <a href="#" onclick="getHght('exp');">Expand</a> <a href="#" onclick="getHght('con');">Contract</a> <script type="text/javascript"> <!-- function getHght(act){ var doc = document.getElementById("oDiv"); if (act == "exp"){ doc.style.height = 300 ; } else if (act == "con"){ doc.style.height = 100 ; } } //--> </script> This is exhibits the desired functionality, but it doesn't work: Code: <div id="oDiv" style="width:300;height:100;background-color:#000000;"></div> <a href="#" onclick="getHght('exp');">Expand</a> <a href="#" onclick="getHght('con');">Contract</a> <script type="text/javascript"> <!-- function getHght(act){ var doc = document.getElementById("oDiv"); if (act == "exp"){ doc.style.height += 30 ; } else if (act == "con"){ doc.style.height -= 30 ; } } //--> </script> IE give an "invalid argument" error. No error in FF. I had the same [failed] result using .getAttribute(), and .setAttribute(). How should I approach this? -james Hello. This is my first post here... I'm a bit baffled by IE7 javascript engine. I created a very simple game called the "Word Smith"...basically the user has to guess words by clicking a letter or guessing the entire word. Points are assigned accordingly. After the user clicks "NEW GAME" and then clicks an imagemap of some "dice" to invoke my random number generator, javascript increments the Round number to 2! Here's the rub... If I uncomment that "alert" statement just after I increment my currentRound variable, the code works perfectly! WTH? See code below. Here is a snippet of the code where I am incrementing that variable: Code: function generateNumber() { //display the current Round currentRound++; //debug //alert("currentRound = " + currentRound); //debug if(currentRound <= 10) { //display the Round Number on the page var roundNumberString = 'Round ' + currentRound; document.getElementById('RoundNumber').value = roundNumberString; }//end if . . . I declare currentRound as a global var. This is the only place I increment the variable. It is also important to mention that this code works great in Firefox, Chrome and Safari -meaning the currentRound variable is incremented once on each iteration. To reiterate - if you play the game in IE, you will first play not Round 1 but Round 2, followed by Round 4, then Round 6, etc... Any thoughts? And yes, I am using "onmouseup" not "onclick" in my XHTML. Thanks for any suggestions. Cheers. Hi all, working on building a website at the moment. and i need to create a script that will increment a number by 0.01, then stop and decrease by 0.03, then increase again by one. I wrote code to increment by 0.01 continuouly but now i can't stop it. and change to decreasing <script type = "text/javascript"> num = 0.87; var tim = 0; function makeNum() { num = ((num*1) + .01).toFixed(2); document.getElementById('count').innerHTML = num-.01; tim = window.setTimeout("makeNum()", 2000); } makeNum(); </script> And now I'm Completly stuck. Help would be grately appreciated Thanks Simply put, I need to take a variable (The number '20' in this case) that is displayed by an input box on my web page and plug it into a function so that whenever I click on a button, the number in the input box will decrease by 1. Seems simple enough, though for hours I've been going at it with no luck. Skipping the rest of my code - I currently have: Code: <head> <title> Online Slots </title> <script type="text/javascript" src="http://dave-reed.com/book/random.js"> </script> <script type="text/javascript"> function DoSpin() { var count; count = 20 document.getElementById("countBox") = count - 1; } </script> </head> <body> <div style="text-align:center"> <input type="button" value="Click to Spin" onclick="DoSpin()" /> <br /><br /> Current Funds: <input type="text" id="countBox" size="4" value="20" onfocus="blur();" /> </div> </body> The entire code is a slot machine project that's supposed to be extremely simple where you hit the button and it spins 3 wheels, 3 of the same image and you win. Every spin takes $1, every win gives $13. The majority of the code is already working, however for some reason I appear to be failing badly at getting the read out to show a decrement of $1 every time you push the button. I know this is a bit newbie of a question to be asking; but I've tried so many different ideas that I've found across w3schools, webdevelopersnotes, dave-reed, ect - and so far I haven't been able to get any of them to work correctly. Any help would be great! I would like to modify an old script retrieve a registry key and sifting through the many forums put this together but not sure if this is correct? Thanks Code: <html> <head> <script language="javascript"> <!-- var value; var Shell; var cicserver; Shell = new ActiveXObject("WScript.Shell"); value = Shell.RegRead("HKLM\\Software\\Interactive Intelligence\\EIC\\Notifier"); if value = "servername1" { cicserver = "servername1" } else { cicserver = "servername2" } Hi all, I am having trouble trying to use the substring String method. Relevant HTML code: Code: <img id="news" src="../images/news.png" alt="News" onmouseover="change(this)" /> Relevant JavaScript code: Code: function change(element) { if (element.id == "news" && element.src.substring(3,5) != "../") { element.src = "../images/news.png"; alert(element.src.substring(3,5)); } else if (element.id == "news" && element.src.substring(3,5) == "../") { element.src = "../../images/news.png"; } } I want the image to change to another image, but depending on the src in the HTML code. This is so that it can locate the correct folder. However, it doesn't work, and I tried using an alert statement to show me what JavaScript is reading and it seems to read "e:", which is not correct. It never reads "../", which it should. I don't know how to solve this problem, any ideas? need help.... I need to create a web page that can pull data from sensatronics senturion sensor probe. The unit has a web server that displays temperature, humidity,etc. You can also query it for from telnet or webpage which kicks back xml. My page needs to read the values of the probes. I don't know much about javascript and have been unsuccessful trying to use httprequest. I guess this would be considered cross domain as well? Here is the XML that is generated from the unit. I get this by pulling through a web browser x.x.x.x/xmldata Thanks <?xml version="1.0" encoding="ISO-8859-1"?> <Sensatronics id="S10604" hb="10554"> <Group id="1"> <Probe id="100"><Value>75.2</Value></Probe> </Group> <Group id="2"> </Group> <Group id="3"> </Group> <Group id="4"> </Group> <Group id="5"> </Group> <Group id="6"> </Group> <Group id="7"> </Group> <Group id="8"> </Group> <Group id="9"> <Probe id="99"><Value>1.0</Value></Probe> <Probe id="1"><Value>79.5</Value></Probe> <Probe id="2"><Value>34.3</Value></Probe> <Probe id="3"><Value>35.6</Value></Probe> <Probe id="4"><Value>0.0</Value></Probe> </Group> </Sensatronics> Hi there! I'm having a little bit of trouble, I've read through tutorials on parsing XML to Javascript and such, but the XML file I'm working with is very different to the ones the tutorial showed me. Normally it'd be like Code: <here> <there></there> </here> But the one I'm wanting to work in looks like this: Code: <rowset name="names" columns="name"> <row name="this"> <rowset name="fun" columns="name"> <row name="that"> </rowset> </row> </rowset> To make it more clear, my question to you is: How can I parse <row name="that"> where only we only have <row name="this"> All, Say I have the following code: Code: <!DOCTYPE html> <html> <head> <style>img{ height: 100px; float: left; }</style> <script src="http://code.jquery.com/jquery-1.7rc2.js"></script> </head> <body> <div id="images"> </div> <script> $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: "cat", tagmode: "any", format: "json" }, function(data) { $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });</script> </body> </html> This came from the jQuery website. What I would like to do is change the link to something like this: https://graph.facebook.com/me/friend...ss_token=12345 The data that comes back is something like: Code: { "data": [ { "review_comment": "Here is a comment", "id": "12" }, { "review_comment": "Testing With more", "id": "34" }, { "review_comment": "Third comment", "id": "643" }, { "review_comment": "More Comments", "id": "120" }, { "review_comment": "Testing", "id": "3455" } ] } What I would like to do is basically read all of the review_comment tags and basically rotate these to display them on the webpage. So have "Here is a comment" be displayed for like 10 seconds and then fade out and have "Testing with More" fade in and be displayed for another 10 seconds etc. What is the best way to do this? I'm not sure how to change my JSON code above to acheive this. Would I need to basically put the comments in a div and then use jQuery to fade in the divs in and out? Any help you could provide would be greatly appreciated!! Hi, I am a newbie at XML and this issue is proving to be a tough nut to crack for me. My AJAX query returns me an XML response of the following structure for a query on "ind": <countries> <country> <name>India</name> <capital>New Delhi</capital> </country> <country> <name>Indonesia</name> <capital>Jakarta</capital> </country> </countries> How do I transform the XML response into a HTML layout? Particularly, how do I get down to the value at each node?How do I traverse the XML document using JS? Is this (using XML) better than JSON (other than the obvious platform-independence)? Which is better? Thanks! Hi All, Im trying to write a html with javascript page that reads values from an XML file and outputs to a table. Thats easy i hear you say? Trouble is the application that is outputing the XML file doesnt output a simple XML file. Below is a section of the file: Code: <?xml version="1.0" encoding="UTF-8"?> <CVES name="EUREX" datetime="09 Aug 10 14:40:41"> <thread name="DB 0" state ="active" nb="0" tempo="00:00:02" action="Wait"/> <thread name="DB 1" state ="active" nb="0" tempo="00:00:02" action="Wait"/> <thread name="match" state ="active" nb="0" tempo="00:00:02" action="Wait"/> <MatchingList> <Tickets value="142"/> <TicketsCleared value="23"/> <TicketsNotCleared value="119"/> <Orders value="21"/> <OrdersCleared value="21"/> <OrdersNotCleared value="0"/> </MatchingList> <thread name="exch 1" state ="active" nb="0" tempo="00:00:10" action="Wait"/> <Exchange> <Tickets value="142"/> <TicketsWithUnknownExternalCodes value="212"/> <ClearingInProgress value="4"/> <Clearing> <AverageClearingTime value="00:00:00"/> <LastClearingTime value="14:26:37"/> <LastUnclearingTime value="14:27:55"/> <TotalQtyCleared value="705"/> <TotalQtyUnCleared value=""/> </Clearing> <Reading> <LastReadingTime value="14:40:31"/> <NextReadingTime value="14:41:00"/> im able to read the contents of the CVES tag (Name and datetime) but cannot get any others to load. how can i get details from LastReadingTime? Thread name="Exch 1" Having googled reading XML into HTML file and cannot find anything that covers this kind of xml file THanks Dear frnd I wanna read on html page , and i have script : " [I]<html> <head> <script type="text/javascript" language="javascript"> function Read() { var Scr = new ActiveXObject("Scripting.FileSystemObject"); var CTF = Scr .OpenTextFile("C:\\123.txt", 1, true); data = CTF .ReadAll(); document.write("<pre>" + data + "</pre>"); CTF .Close(); } </script> </head> <body onLoad="Read()" > </body> </html> [I] " But as its using activex control not allowing in all browser . Have you any other way with pure js to read the file contains ? or allowing activex in all browser ? i am thinking of using a xml file as a data base for example , the xml file stores a list of reference numbers which is allocated to a url or a name such as 0123456789 and i have a text box on a webpage and the user types in a reference number and the javascripts reads the xml file to check if its a valid reference number i.e a registered number i am new to working with xml etc... so would be nice to have a little help here EXAMPLE <DATA> <REF> <0123456789>JOE</01234567890> <1111111111>www.google.com</1111111111> </REF> </DATA> id like it to read the specific data thats contained within the tag such as 0123456789's tag = JOE I am trying to make a simple alert come up stating a checkbox is checked when it changes, and then another alert for when the checkbox is unchecked. Problem is, only the alert for when the box is checked is coming up. Anyone know why? Code: function displayCheckPopUp() { if(document.activeElement.checked=true) { alert("A check box has been selected"); } else if(document.activeElement.checked=false)<!--if(document.getElementById().checked=false)--> { alert("****"); } } Code: <input type="checkbox" name="Checkbox 1" value="Checkbox 1" id="first_cbox" onchange="displayCheckPopUp(this)" /> <p class="custom_style2"> Checkbox 1 </p> Hi, ive just been debugging my script in IE, and came across this: Code: OrbitTool.prototype.handleMouseUp = function(e) { if (e.button == g_o3d.Event.BUTTON_LEFT) { this.mouseLeftDown = false; } else if (e.button == g_o3d.Event.BUTTON_MIDDLE) { this.mouseMiddleDown = false; } }; its giving me an error on the second line, the error reads ('button' is null or not an object). does anyone know why this might be? im not a pro with javascript so my knowledge only stretches so far. Simon Reply With Quote hi Guys , I have some instructions in property files , now I wat to retrive that fmt tag values in scriptlets So that I can modify the content in property file So i have written the code in jsp as <c:set var="mailBodyData" value='<fmt:message key="confirmemail.body.message"/>' scope="request"/> <% out.println("hero "+request.getAttribute("mailBodyData")); %> but its displays empty , Also I have tried as <% String str ="<fmt:message key="confirmemail.body.message"/>' %> but its throughs the Compilation error , Pls help , So that I can retrive the data from fmt to Scriptlets I am having an issue reading from a div that is being changed. The div in question was initially empty. A function that was called upon the selection of something in the drop down list creates another drop down list within that div (sets the inner html). Now, I have another function that needs to read from this new drop down list. However, when I use alert(document.getelementbyid('divid').innerhtml) in the function it returns undefined. The drop down list is created successfully and populated by the relevant data. The method of creation was calling another php file that created the list after querying a database. Any ideas? I can post the code if it will help.
hi, (JAVASCRIT) the actual program reads and prints values from a checkbox tree and this piece of code does it. Code: dhtmlXTreeObject.prototype.getAllChecked=function(){ return this._getAllChecked("","",1); } dhtmlXTreeObject.prototype.getAllCheckedBranches=function(){ return this._getAllChecked("","",0); } dhtmlXTreeObject.prototype._getAllChecked=function(htmlNode,list,mode){ if(!htmlNode)htmlNode=this.htmlNode; if(((mode)&&(htmlNode.checkstate==1))||((!mode)&&(htmlNode.checkstate>0))){if(list)list+=","+htmlNode.id;else list=htmlNode.id;} var j=htmlNode.childsCount; for(var i=0;i<j;i++) { list=this._getAllChecked(htmlNode.childNodes[i],list,mode); }; if(list)return list;else return ""; }; the values are returned to alertbox. Code: <a href="javascript:void(0);" onclick="alert(tree2.getAllChecked());">Get list of checked</a><br><br> kindly help me with reading the returned values in to an array or list (but bot in alertbox) ...so that i can pass them to next JSP page. waiting for ur answer, BeanBoy ! |