JavaScript - Save Image Url To Cookie
Hey guys, I think this is some pretty basic JavaScript but I'm not too familiar with the language and would really appreciate some help here.
I have an image switcher script setup. Its very basic and changes the image displayed on click of a link. Here is what I currently have: Javascript: Code: <script type="text/javascript"> function changeIt(imageName,objName) { var obj = document.getElementById(objName); var imgTag = "<img src='"+imageName+"' border='0' />"; obj.innerHTML = imgTag; return; } </script> HTML: Code: <div id="image1"> <img src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/49057_100001550995222_9679_q.jpg" border="0" alt="one" /> </div> <br> <a id="one" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/49057_100001550995222_9679_q.jpg','image1');">one</a> <a id="two" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/174411_100002333675750_7453320_q.jpg','image1');">two</a> <a id="three" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/41512_100000999943382_7276_q.jpg','image1');">three</a> <a id="four" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/41477_100001406980454_629_q.jpg','image1');">four</a> <a id="five" href="#" onclick="changeIt('http://www.dead-paramour.org/fans/fanMCR4.jpg','image1');">five</a> Its very basic but does what I want. What I'm attempting to do is store the image selected as a cookie so that when users refresh/navigate to other pages the image stays to the one they selected. Is anyone able to help me out with this? Any help is greatly appreciated. Thanks, Chris Similar TutorialsHi all, I found this script online that lets users on an iPhone drag boxes around the screen. The problem is that when you reload the page, the boxes are in different positions than what they were before the reload. Like, you would drag the boxes around and then reload the page, but the boxes would be in the default locations. I want the boxes to stay in the same spot that they were the previous time they moved them. Does that make sense? Anyways, here's the example I found online: http://www.manifestinteractive.com/iphone/touch/ Only works on iPad/iPhone/iPod Touch. It uses jQuery too so if you know of any way to do this, that would be excellent. Thanks. Hi , i have got this img src html.. how do i write a javascript to auto save this image in C:\ without right click on the image? <img src="/user_images/V/VI/VIR/Virgo001/1135356474_ylittlekid.jpg" alt="1135356474_ylittlekid.jpg"></img> thanks for help! Hi, In Google Chrome the 'chrome.tabs.captureVisibleTab(integer windowId, function callback)' method will return a data URL of the JPEG encoding of the visible area of the captured tab. We want to save that content as image to hard disk without opening/passing the contents into new html page. Does anybody know how it can be done by javascript. Please provide help. Thanks. Dear Friends, I am breaking my head over this since yesterday. Can anyone help me with a javascript which can be used to replace the inner text (count of downloads) with new text based on how many people save my image using Right-Click Save Image As option. Thank you PS: Without database support. Code: <table border="0" cellspacing="1" cellpadding="1" width="200"> <tbody> <tr> <td><img border="0" id="s1" alt="" src="s1.gif" /></td> <td><img border="0" id="s2" alt="" src="s2.gif" /></td> </tr> <tr> <td style="text-align: center">7 Download(s)</td> <td style="text-align: center">1 Download(s)</td> </tr> <tr> <td><img border="0" id="s3" alt="" src="s3.gif" /></td> <td><img border="0" id="s4" alt="" src="s4.gif" /></td> </tr> <tr> <td style="text-align: center">0 Download(s)</td> <td style="text-align: center">10 Download(s)</td> </tr> </tbody> </table> I am wondering if it would be possible to add a Cookie to this code i found, i am wanting the browser to remember the chosen background image and save it when the user closes the browser. Currently when the option is selected it does not remember the choice when you then go back to the page, any help on this would be much appreciated! Many Thanks Code: <script type="text/javascript"> function changeTheme() { var e = document.getElementById("themes"); var theme = e.options[e.selectedIndex].value; console.log(theme); document.getElementById("shelf").style.backgroundImage = "url("+theme+")"; } </script> <body id="shelf"> <select id="themes" onChange="changeTheme()"> <option value="images/background1.jpg">Default</option> <option value="images/background2.jpg">Oriental</option> </select> Hello everyone. I am trying to put together a browser based game which uses javascript and cookies, and am looking for help with one of it's functions. I need a script which checks a cookie value, then displays a certain image, depending on what that value is. So, if the value is 50, it displays one, if it's 60 it display another one etc. What script would I use? 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; } }; Hey, I'm trying to make a game, I learned how to do so by reading tutorials but the problem is that I do not know how to implement the save/load function into the game, the tutorial surrounding that area was very unclear to me, and here I am... Any tips on how to make this work is greatly appreciated, I wouldn't asked if I hadn't tried my best and every way I could think of. I'm still quite new to coding so... The first piece of code is the game, the second one is what I'm trying to make the game work with. I tried for a while and got the game to reset back to values, but only the values I set in the code so it never actually worked. The tutorial doesn't give any live examples and I really am... not that bright when it comes to coding Sorry and thanks, all inputs are appreciated. I read tutorial from links below, Javascript String Compression | Almost Idle Tutorial for save code Incremental Lesson 9 - For Loops | Almost Idle Tutorial for the game code Code: /*Pleae refer to Lesson 9.txt for a full description on this lesson*/ //The timer to run code every second var Timer = window.setInterval(function(){Tick()}, 1000); var buildings = []; //The object declaration for game saves function GameSave() { this.money = 0; this.buildings = []; for (var i = 0;i < buildings.length;i++) { this.buildings[i] = 0; } } //The object declaration for buildings function Building() { this.Name = "Lemonade Stand"; this.Cost = 10; this.PerSec = 1; } //The function to initialise all buildings function InitBuildings() { LoadBuilding("Lemonade Stand",10,1); } //The function to automatically load a building into the buildings array function LoadBuilding(name,cost,persec) { var cur = buildings.length; buildings[cur] = new Building(); buildings[cur].Name = name; buildings[cur].Cost = cost; buildings[cur].PerSec = persec; } //The function used to gather money function GatherMoney() { game.money++; //++ tells javascript to add 1 to the variable //Display the player's current money document.getElementById("money").innerHTML = game.money; } //The function that gets run every second function Tick() { for (var i = 0;i < buildings.length;i++) { game.money += game.buildings[i] * buildings[i].PerSec; } document.getElementById("money").innerHTML = game.money; } //The function to buy a lemonade stand function Build(id) { if (game.money >= buildings[id].Cost) { //Check if the player has enough money, then subtract it and add a new building if they do game.money -= buildings[id].Cost; game.buildings[id] = game.buildings[id] + 1; document.getElementById("money").innerHTML = game.money; document.getElementById("Building1Qty").innerHTML = game.buildings[id]; } } //Run this code once the page has loaded fully window.onload = function() { InitBuildings(); window.game = new GameSave(); }; Code: /*Pleae refer to Compression.txt for a full description on this lesson*/ function NewGame() { this.name = "Our Game"; this.description = "Our Game's Description"; this.numbers = []; for (var i=0;i<10;i++) { this.numbers[i] = i; } } var Game = new NewGame(); window.onload = function() { var SaveGame = JSON.stringify(Game); SaveGame = encode_utf8(SaveGame); SaveGame = lzw_encode(SaveGame); window.localStorage['SaveName'] = SaveGame; SaveGame = window.localStorage['SaveName']; SaveGame = lzw_decode(SaveGame); SaveGame = decode_utf8(SaveGame); window.GameTwo = JSON.parse(SaveGame); document.getElementById("name").innerHTML = "Name: " + GameTwo.name; document.getElementById("desc").innerHTML = "Description: " + GameTwo.description; var numbers = ""; for (var i=0;i<10;i++) { if (numbers.length == 0) {numbers = i;} else {numbers += ", " + i;} } document.getElementById("numbers").innerHTML = "Numbers: " + numbers; } // LZW-compress a string function lzw_encode(s) { var dict = {}; var data = (s + "").split(""); var out = []; var currChar; var phrase = data[0]; var code = 256; for (var i=1; i<data.length; i++) { currChar=data[i]; if (dict['_' + phrase + currChar] != null) { phrase += currChar; } else { out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0)); dict['_' + phrase + currChar] = code; code++; phrase=currChar; } } out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0)); for (var i=0; i<out.length; i++) { out[i] = String.fromCharCode(out[i]); } return out.join(""); } // Decompress an LZW-encoded string function lzw_decode(s) { var dict = {}; var data = (s + "").split(""); var currChar = data[0]; var oldPhrase = currChar; var out = [currChar]; var code = 256; var phrase; for (var i=1; i<data.length; i++) { var currCode = data[i].charCodeAt(0); if (currCode < 256) { phrase = data[i]; } else { phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar); } out.push(phrase); currChar = phrase.charAt(0); dict['_'+code] = oldPhrase + currChar; code++; oldPhrase = phrase; } return out.join(""); } function encode_utf8(s) { return unescape(encodeURIComponent(s)); } function decode_utf8(s) { return decodeURIComponent(escape(s)); } Reply With Quote 01-16-2015, 05:52 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts the problem is that I do not know how to implement the save/load function into the game save it where? that particular question is important as JavaScript has only limited places where it can save something at all. 1) save it on the server => call a server script with the appropriate data (e.g. via AJAX) 2) cookies, very limited storage space, only works on the same browser 3) WebStorage, more space than cookies, but still only the same browser 4) IndexedDB (same as above) Hello, Is it possible to store the edited value in the div tag in the original file, such that next time i open the HTML file the new edited value appears. Thanks in advance. Have a Good day. Hello. I am new to the forums (I just started my Javascript journey last week), and was hoping to get help with something. I am currently developing a page which allows access to music on a server. This music is being streamed, but users are also able to download this music (assuming they have the license to do so). All of the music uploaded is of the .mp3 format, however they have no filetype extensions, and were not named using any particular naming convention. Because of this, I was hoping to change the filename (when a downloaded is initiated) to variables I have stored based on the current song. I am currently simply opening a new page, in Chrome is looks like this: Code: chrome.tabs.create({ "url": song.url }) Hit presents the user with a prompt to save the file, however, its default name is a random alphanumeric string with no extension, as per their file name on my server. Is there an easy way to do this without renaming all the music server side? I do have the variables song.title and song.artist setup! All help is appreciated! Edit: Since this page is only for Chrome users, I listed the code I am using. I understand window.open and was originally using this. It functions the same, and if I need to revert back to using is instead, I shall. I am trying to do this and have some code im working with. I can load the file through a browse button then save it using the existing code. However, I want instead of the browse option to just preload the file into the textarea and then be able to save it. Code: <script language="javascript"> <!--// var oFileSystem; oFileSystem = new ActiveXObject("Scripting.FileSystemObject"); function ShowFile(sFilePath){ frmEditHTML.tarHTMLText.value = oFileSystem.OpenTextFile(sFilePath).ReadAll(); } function SaveAfterEditing(){ var oFile; oFile = oFileSystem.CreateTextFile(frmEditHTML.filPath.value,1); oFile.WriteLine(frmEditHTML.tarHTMLText.value); oFile.Close(); } </script> Code: <form name="frmEditHTML"> <input type="file" name="filPath" onchange="ShowFile(this.value)"> <br><textarea name="tarHTMLText" cols=60 rows=20></textarea><br> <input type="button" value="Save" name="cmdSave" onclick="SaveAfterEditing()"> </form> im trying to have it save the values in the menu, i was think either cookies or storing it in the .window thing but i am unsure of how to do these, any help would be great. Code: <script type="text/javascript"> 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 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); } } } <!-- // initialise shortcuts on page load var selectObj1=null, selectObj2=null// global function init() { selectObj1=document.getElementById("select_1"); selectObj2=document.getElementById("select_2"); selectObj2.disabled=true; // ========== end init() ============== // second select box options list var A= new Array() A["remote 1"]=["0","yup","DVD-1"]; A["remote 2"]=["0","VCR-1","DVD-2"]; // // global variables var saveObj=null, indx=null, targetObj=null, selectNo=null; // function process(obj,sNumb) { // disable unused select boxes if(sNumb==1) { selectObj1.selectedIndex="0"; selectObj1.disabled=true; } else if( sNumb==2) { selectObj1.selectedIndex="0"; selectObj1.disabled=true; } // // store selected index indx=obj.options.selectedIndex; // invalid selection if(indx==0){ return; } // --------- // save passed parameters for use after timeout deleay saveObj=obj, selectNo=sNumb; // put object items list into next select box after clearing targetObj=document.getElementById("select_"+selectNo) targetObj.disabled=false; // clear any existing options note that this starts from end of list, not beginning for(var i=targetObj.options.length-1;i>-1;i--) { targetObj.options[i]=null; } // build in short delay here to avoid error in Opera browser setTimeout("finishOff()",50) } // ----------- 50ms delay here -------- // called from timeout in function process() function finishOff() { var obj=saveObj; // from global // fill selectObj options var i, thisItem=0; // build options list switch(selectNo){ case 2 : targArray = A[obj.options[indx].value]; break; } // for(i=0;i<targArray.length;i++) { thisItem=targArray[i]; // syntax is new Option("text", "value", isDefaultSelectedFlag, isSelectedFlag) targetObj.options[i]=new Option(thisItem,thisItem,false,false); } obj.blur(); } // ============ end process() =================== // fires on selecting in third select box function finish() { select("["+selectObj1.value+"] ["+selectObj2.value+"]") } // ------------ // window.onload=init; //--> </script> Hey Guys, I'm working on a Gameserver for a Game, written in JavaScript. I want to save all console.log()'s with Timestamp into a txt-file but I don't know how :/ Could you help me with it and tell me how I can do this? for example, I want to save User-Logins into the logs. This is the code I'm using right now. Code: case "LOGIN": var data = PacketModels.login.parse(datapacket); User.login(data.username, data.password, data.is_banned, data.is_online, function(result, user){ if(result){ if(user.is_banned == 1){ console.log("[WARNING] ".red + data.username + " tried to login. It failed because the User is banned!"); c.socket.write(packet.build(["LOGIN", "ISBANNED"])); }else if(user.is_banned == 0){ if(user.is_online == 1){ console.log("[WARNING] ".red + data.username + " tried to login. It failed because the User is already online!"); c.socket.write(packet.build(["LOGIN", "ALREADYLOGGEDIN"])); }else if(user.is_online == 0){ c.user = user; c.enterroom(c.user.current_room); c.user.is_online = 1; c.user.save(); c.socket.write(packet.build(["LOGIN", "TRUE", c.user.current_room, c.user.pos_x, c.user.pos_y, c.user.username])); console.log("[INFO] ".blue + data.username + " has logged in on Map:[" + (c.user.current_room_name).blue + "] X:[" + String(c.user.pos_x).blue + "] Y:[" + String(c.user.pos_y).blue + "]"); } } ... Reply With Quote 12-22-2014, 02:48 PM #2 sunfighter View Profile View Forum Posts Senior Coder Join Date Jan 2011 Location Missouri Posts 4,830 Thanks 25 Thanked 672 Times in 671 Posts JS will not save a text file. You need to do this with a server side language like PHP and if your going to all of that trouble you might want to study a database at the same time or soon after. This is code use to save XML file using Javascipt but it can't not save full Processing Instruction, example we have PI is <?xml version="1.0" encoding="utf8"> when run the code then PI is saved with <?xml version="1.0"> and sometime it doesn't word. Please help me fix, thanks PHP Code: function SaveXML(xmlDoc,filename) { var outputXML = xmlDoc.xml; var mfObj = new ActiveXObject("Scripting.FileSystemObject"); var absPath = getPath(); var file = mfObj.CreateTextFile(absPath + filename, true); file.Write(outputXML); file.Close(); } function getPath() { var path = document.location; var str = new String(path); var end = str.lastIndexOf("/"); var absolutePath = str.substring(8, end) + "/"; absolutePath = absolutePath.replace(/%20/g, " "); return absolutePath; } Hello all, i am a newbie here. I am starting to programme with javascript. I am designing a website. in This website there is an input with type = text and beside this input, there is another input with type = submit. If i open this website: The default value on the search text is "Enter a text", and if I click submit button, this button can recognize the value of the search text which is "Enter a text". <input id="searchText" type="submit" value="Enter a text"/> <input id="searchSubmit" type="submit" value="Submit"/> And then i modified a little bit. I have this javascript: var searchInput = $('#searchText'); searchInput.focus( function() { searchInput.attr('value', ''); }); The goal is, when I click on the search text, the default text is gone. And it worked. But if i write a new text on the search text, the submit button still recognized the value of search text as empty string. Can anyone please help me?? Thank you I have a long survey form and once its submitted it gets recorded into a database. I would love to be able to save a PDF version of the HTML form with all their radio buttons and textfields filled out at the same time its submitted. It would need a unique name that matches their record in the database (maybe it pulls the data that was entered into one of the form fields for the name). Whether it gets uploaded to an ftp or just emailed to a mailbox doesn't really matter. The purpose of this is to basically have a visual interpretation of the data by a single user. Is something like this even possible? Hi.. I have checkbox and I need to get his value. I create function for checkbox if checkbox is clicked it is true then the checkbox value is H else W. Code: function chk(){ if(document.getElementById('H').checked==true){ var H = document.getElementById('H'). value = H; } else if(document.getElementById('H').checked==false){ var H = document.getElementById('H'). value = W; } } and I have function for save : Code: function ApproveLeaveOP(){ var H = document.getElementById('H').value; document.sampleform.action="AddLeave.php?H="+H; document.sampleform.submit(); } <input type="checkbox" name="H" id="H" value="" onclick="chk()"> I don't know how can I add value to the checkbox if I click the value will be H if not the value is W. I am new in using checkbox. Thank you so much.. I'm trying to find the best approach for saving the checked value of a checkbox in SQL With this script the FieldName "Active" toggles yes/no onClick... That we can post to the database no problem... What I am having trouble with is saving the checked value. I want to make the FieldName Active =hidden, and only display the checkbox with correct value checked yes/no. Code: <script type="text/javascript"> var YesOrNo = (function() { if(document.select.checkbox.checked) { document.select.Active.value = 'yes'; } else { document.select.Active.value = 'no'; } }); </script> <form name="select"> <input type="hidden" name="Active" size="10" /> <input type="checkbox" name="checkbox" onclick="YesOrNo();" value="on" /> </form> I have a ZIP file in the server. I want create a create a save dialog to save the zip file in local machine. The below code works perfectly fine for firefox but not on IE. apparently I want the code to work in IE. this is 4th JS forum I am posting my question......any help is greatly appreciated. <html> <head></head> <script language='javascript'> function JBTRunZip( ){ location.href="IMAN_IMAGE_FILES.zip"; } function download(locate){ window.open(locate) } </script> <body> <button onclick="JBTRunZip()">generateZip</Button> <td><input type ="Button" value ="Scarica" onclick="download('Test.zip');"></td> </body> </html> Hey guys, I've been experimenting around with a way to get a "Save As" dialog to pop up prompting the user to download a certain file from the server. How I've done this so far is open a window in Javascript to a PHP file, server side, passing an argument through _GET. The PHP generates the file and then sends a header request to download. Simple enough. The problem is that using this method opens a blank window in addition to the Save As Dialog. Is there anyway to fool the browser/ hide the window/ etc, so two windows don't pop up at the same time everytime my users press the download button? I am also pretty familiar with AJAX techniques, so if anyone has a solution along that route as well I'd appreciate it. Cheers, Q |