JavaScript - Q: Proper Way To Test For Local Storage
Hi all,
I have some code that attempts to save a user's preference settings. It first tries to use "localStorage", and if that fails (only old versions of MSIE), then a cookie is used instead. I tried several different tests, such as: Code: if (localStorage) { alert('True'); } else { alert('False'); } and....... if (typeof localStorage).... and....... if (typeof localStorage == 'object').... but none of these are reliable. For example, if I intentionally misspell "localStorage" by instead using "localStor" (simulating a browser that doesn't understand the object name), the code simply does not run. What I ultimately want is this: Code: if (user_wants_to_save_settings && localStorage) { save_to_local_storage; } else if (user_wants_to_save_settings) { save_to_cookie; } ...unfortunately, that doesn't work. Anyone have ideas? I've been staring at this too long and am probably missing the obvious.... Thanks! -- Roger Similar TutorialsI run Windows 7 and IE9, and I believe IE9 supports HTML5 Local Storage. But when I run this offline (locally) in IE9 Code: <script type="text/javascript"> function testSupport() { if (localStorage) {return "Local Storage: Supported"} else { return "Local Storage: NOT supported"; } } alert ( testSupport() ); </script> I get "LocalStorage: NOT supported". Chrome returns "Local Storage: Supported" My DOCTYPE is <!DOCTYPE html> Other tests also fail in IE. Example: Code: localStorage.setItem("name", "Hello World!"); alert(localStorage.getItem("name")); Above works in Chrome. Any advice, please? Have I not configured IE9 properly? I am working on a web app for the iPad and I am storing all my content in cookies. I am wondering how easy it is to transfer it to Local Storage. I'll post all the scripts that set cookies below: Code: jQuery.cookie = function (a, b, c) { if (typeof b !== "undefined") { c = c || {}; if (b === null) { b = ""; c.expires = -1; } var d = ""; if (c.expires && (typeof c.expires === "number" || c.expires.toGMTString)) { var e; if (typeof c.expires === "number") { e = new Date(); e.setTime(e.getTime() + c.expires * 24 * 60 * 60 * 100000); } else { e = c.expires; } d = "; expires=" + e.toUTCString(); } var f = c.path ? "; path=" + c.path : ""; var g = c.domain ? "; domain=" + c.domain : ""; var h = c.secure ? "; secure" : ""; document.cookie = [a, "=", encodeURIComponent(b), d, f, g, h].join(""); } else { var i = null; if (document.cookie && document.cookie !== "") { var j = document.cookie.split(";"); for (var k = 0; k < j.length; k++) { var l = jQuery.trim(j[k]); if (l.substring(0, a.length + 1) === a + "=") { i = decodeURIComponent(l.substring(a.length + 1)); break; } } } return i; } }; $(window).unload(function () { $(".remember").each(function () { $.cookie(this.id, this.value, { expires: 365 }); }); $(".draggable").each(function () { var a = $(this); $.cookie(this.id, a.css("top") + "_" + a.css("left"), { expires: 365 }); $.cookie("disp" + this.id, a.css("display"), { expires: 365 }); }); }); $(function () { var a, b, c; setInterval(checkOrientAndLocation, 1000); $(".remember").each(function () { var a = $.cookie(this.id); if (a) { this.value = a; } }); $(".draggable").each(function () { var a = $.cookie(this.id); if (a) { a = a.split("_"); $(this).css({ position: "absolute", top: a[0], left: a[1] }); } var b = $.cookie("disp" + this.id); if (b) { this.style.display = b; } }).touch({ animate: false, sticky: false, dragx: true, dragy: true, rotate: false, resort: false, scale: false }); }); function toggle_visibility(a) { var item = $("#" + a); item.fadeToggle(); $.cookie("disp" + a, item.css("display")); } var _target = null, _dragx = null, _dragy = null, _rotate = null, _resort = null; var _dragging = false, _sizing = false, _animate = false; var _rotating = 0, _width = 0, _height = 0, _left = 0, _top = 0, _xspeed = 0, _yspeed = 0; var _zindex = 1000; jQuery.fn.touch = function (a) { a = jQuery.extend({ animate: false, sticky: false, dragx: true, dragy: true, rotate: false, resort: false, scale: false }, a); var b = []; b = $.extend({}, $.fn.touch.defaults, a); this.each(function () { this.opts = b; this.ontouchstart = touchstart; this.ontouchend = touchend; this.ontouchmove = touchmove; this.ongesturestart = gesturestart; this.ongesturechange = gesturechange; this.ongestureend = gestureend; }); }; var currentRotation = null; 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); } function checkOrientAndLocation() { if (currentRotation !== window.orientation) { setOrientation(); } } function gestureend(a) { _sizing = false; _rotating = (_rotating + a.rotation) % 360; } function gesturechange(a) { if (_sizing) { _width = this.opts.scale ? Math.min(parseInt(_sizing[0], 8) * a.scale, 300) : _sizing[0]; _height = this.opts.scale ? Math.min(parseInt(_sizing[1], 10) * a.scale, 300) : _sizing[1]; _rotate = this.opts.rotate ? "rotate(" + (_rotating + a.rotation) % 360 + "deg)" : "0deg"; $("#" + this.id).css({ width: _width + "px", height: _height + "px", webkitTransform: _rotate }); $("#" + this.id + " b").text(""); $("#" + this.id).css({ backgroundColor: "" }); } } function gesturestart(a) { _sizing = [$("#" + this.id).css("width"), $("#" + this.id).css("height")]; } function touchend(a) { $(a.changedTouches).each(function () { if (!a.targetTouches.length) { _dragging = false; if (_animate) { _left = $("#" + _target).css("left") === "auto" ? this.pageX : parseInt($("#" + _target).css("left"), 10); _top = $("#" + _target).css("top") === "auto" ? this.pageY : parseInt($("#" + _target).css("top"), 10); var b = _dragx ? _left + _xspeed + "px" : _left + "px"; var c = _dragy ? _top + _yspeed + "px" : _top + "px"; if (_dragx || _dragy) { $("#" + _target).animate({ left: b, top: c }, "fast"); } } } }); $("#" + _target + " b").text(""); $("#" + _target).css({ backgroundColor: "" }); } function touchmove(a) { if (_dragging && !_sizing && _animate) { var b = isNaN(parseInt($("#" + _target).css("left"), 10)) ? 0 : parseInt($("#" + _target).css("left"), 10); var c = isNaN(parseInt($("#" + _target).css("top"), 10)) ? 0 : parseInt($("#" + _target).css("top"), 10); } $(a.changedTouches).each(function () { a.preventDefault(); _left = this.pageX - parseInt($("#" + _target).css("width"), 10) / 2; _top = this.pageY - parseInt($("#" + _target).css("height"), 10) / 2; if (_dragging && !_sizing) { if (_animate) { _xspeed = Math.round((_xspeed + Math.round(_left - b)) / 1.5); _yspeed = Math.round((_yspeed + Math.round(_top - c)) / 1.5); } if (_dragx || _dragy) { $("#" + _target).css({ position: "absolute" }); } if (_dragx) { $("#" + _target).css({ left: _left + "px" }); } if (_dragy) { $("#" + _target).css({ top: _top + "px" }); } if (_dragx || _dragy) { $.cookie(_target, ($("#" + _target).css("top") || "") + "_" + ($("#" + _target).css("left") || "")); } $("#" + _target).css({ backgroundColor: "" }); $("#" + _target + " b").text(""); } }); } function touchstart(a) { _target = this.id; _dragx = this.opts.dragx; _dragy = this.opts.dragy; _resort = this.opts.resort; _animate = this.opts.animate; _xspeed = 0; _yspeed = 0; $(a.changedTouches).each(function () { var b = $("#" + _target).css("left") === "auto" ? this.pageX : parseInt($("#" + _target).css("left"), 10); var c = $("#" + _target).css("top") === "auto" ? this.pageY : parseInt($("#" + _target).css("top"), 10); if (!_dragging && !_sizing) { _left = a.pageX - b; _top = a.pageY - c; _dragging = [_left, _top]; if (_resort) { _zindex = $("#" + _target).css("z-index") === _zindex ? _zindex : _zindex + 1; $("#" + _target).css({ zIndex: _zindex }); } } }); } function killAllCookies() { $(window).unbind("unload"); var a = document.cookie.split(";"), b = a.length - 1; for (b; b > -1; --b) { $.cookie(a[b].split("=")[0], "", { expires: -1 }); setTimeout("location.reload(true);", 1); } } I realize this is a big thing to ask, so if anyone has some free time and possibly wants to help me, I would be extremely thankful. Please help with some javascript for client side storage in html5 mobile safari. Here we wish to use local storage [persistent]. The page index.html has a list of links to question pages e.g. question1.html. When question1.html is answered correctly the page goes to answer1.html. From here, the page moves back to index.html by pressing a button. The button has 2 actions: goto index.html place a key/value pair in local storage - e.g. localStorage.setItem("name", "answer1"); On reloading, the index.html page then asks the local storage if the key/value pair ("name" "answer1") is stored. If yes, a new graphic appears next to the link. If no, the old graphic remains. Thank you for any help. I have set's of radio buttons that have on click functions, and when i restore the form data i would like the onclick functions to re-calculate. Is there a simply way such as if this.checked = true run onclick function that i can apply to every radio with onload???
Reply With Quote 01-10-2015, 01:51 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts You cannot auto-click for security reasons. But you can use local storage to keep the status of the radio buttonds and reinstate them on page reload. You can then run a script to do whatever is required. is "localStorage" a native variable to javascript? On lin 36 & 37 is there anything else involved in getting that local storage to store? Those lines are local storage right? Is it really that easy? I was just reading this HUGE post and immediately stressed me out. I'm used to working off small examples and diving in bit by bit. It was the first article on google so I trusted it to be the most appropriate for introductions. (which means not reading more than 500 words before I get some sample code) In addition, can Google Chrome & FireFox extensions change page elements? The reason I think it can do this is because google chrome says this Which (to me) implies that the extension has access to page data. If that is the case. How are localStorage variables not mixing? How can I access that page data? I don't care about browser history, I just want to change page elements. Is this possible? If this is the case. Is there a way I can have the extension close itself or not open at all? Sometimes I just want the "extension" to provide a simple function. That's all. Thanks! I had Silverbird and the tutorialzine example extension. They were both different size. Odd thing is that I never saw a size specification in the style.css in the tutorialzine example. How can I specify the size of the popup extension? I want to have an example on web storage. I have an index.html page. On this page, there is a button which will go to another page, that is page1.html. On this page now, there is another button which will go to page2.html if clicked. Index.html > page1.html > page2.html Suppose if a user has already visited page2.html on the first time, how to make him/her goes directly on page2.html after clicking the button on index.html? The user must not again go to page1.html to get page2.html because he/she has already done that. I want to know how to store page sessions with HTML5 so that the user gets on his/her last visited page when he/she clicks the button. Thank. Hi, Not sure how difficult this will be but im working on a javascript/HTML5 game, and thought it would be interesting to allow for people to add their score to a google map at their location. I can get the google map and allow people to add their own markers but i dont no how i would store them, and then reload them when someone plays the game. any ideas? Thanks, Luke I've been avoiding php and asp trying to do as much client-side as possible, as lightweight as possible, but don't know enough to know if I should go that route. I want to have several js/jquery games, really simple stuff like flash cards, memory games, matching, etc Currently when you do something correctly it adds 5 points like: points+=5; and if you get it wrong lose 3 points: points-=3; At the end of the game it flashes a play again button which resets points and all the cards, and that's it. So I was trying to think of ways to add a global variable that adds the latest score to it, and maybe gives you a random "prize" which would be another variable randomly selected from an array of "prizes", or better yet, "achievements"....between games....on the same domain. I'd like to eventually make something similar to a "crafting" system, where if you have 3 particular achievements you can convert them into some new achievement...I imagine just a function that checks if you have the 3 objects, then if so it adds some 4th object and removes the first 3. I was avoiding server side databases because I was avoiding authentication/user accounts for the time being...I would probably eventually like to let people play games, and if they want to save their scores long term, register an account....but if they don't want to register an account, I'd like them to have the same functionality for that session, where they can play a few games from around the site while accumulating a global score and list of achievement variables. I was messing around with jstorage, but am not sure if it will work for what I'm thinking....it only accepts strings, and I couldn't figure out how to write the variableName.toString() into the jstorage "value" of the key:value pair...it gives me the impression it's more for storing form data as a convenience to the user. So is there a client side variable storage that's simple, lightweight, and works with mobile? Or a way to write .toString() value of objects into jstorage? Or should I just break down and start investigating my server side options? Is there some middle ground where stuff can be done client side, then give the option to register to save that information long term? edit::I'm thinking of my 3 year old nieces ipad games, they're simple drag drop, highlight shapes, pattern association, etc but I want it so each time you play it remembers where you left off...basically a cookie would have been cool if it were bigger and not sent every packet....so kinda a "save-state" and "load-state" functionality.. edit2::sqlite seems like a legitimate option but then reading through it, it gets convoluted how to implement on my bluehost account... question is Code: href="javascript:void(null);" the same as Code: href="javascript:void(0);" if not whats the preferred or standardized use to avoid conflict.. OK, I'm filling in for a coworker on a radio stations website. The station currently streams live online. I want to add an event tracking so I can track how many people are streaming. I'm really new to js, but I think I figured it out (keyword is "think"). However, there was already an onclick event within the anchor tag. Can I have two in the same tag? Is there a better way to do this? Code: <a href="/fmstream/listen.asx" onclick="window.open(this.href,'Listen','resizable=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,fullscreen=no,dependent=no,width=400,height=400,status'); return false" onClick="pageTracker._trackEvent('Stream','Listen_Button','Stream_Live');"> <img src="/images/filecabinet/folder1/listen1.png" alt="listen1"></a> Hi, So firstly this is likely not in the right place at all, as it's a bit OT but I figured it's the best place to ask.. I have to document 4 different tests to my code; what structure should I take when doing this? I was thinking: * State the aim of the test * State the inputs, and what I believe the output should be. * State the actual output, and whether this positively or negatively affect my code. Is it just considered proper format to always have comment tags in javascript code such as */ and /* and // etc? thanks hello guys, I'm new here .. I am developing a fw js, now I have to test the selector $.. operation is similar to jquery $('#Id') $('table td .class) If there are several factors you should: $('table td .class).each(function () { this .. }); or $('table td .class).item(number) ... http://debbe.altervista.org/d&d.html can be used to test the methods set / get the attributes or setCSS or getCSS for styles .. Thanks to all Hi All, I am looking to make a "enemy" dissapear when "character" hits it? I don't really know what I'm doing. All help is appreciated! PHP Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style> body { padding:0; margin:0; background:#000; } canvas { display:block; margin:30px auto 0; border:1px solid #ccc; background:#999; } </style> <script> var canvas, ctx, width = 320, height = 480, rightKey = false, leftKey = false, enemyTotal = 4, enemies = [], enemy_x = 50, enemy_y = 1, enemy_w = 32, enemy_h = 32, speed = 1, character_x = (width / 2) - 15, character_y = height - 65, character_w = 32, character_h = 32, level_1, level_1_bgX = 0, level_1_bgY = -1312; var enemy, character; for (var i = 0; i < enemyTotal; i++) { enemies.push([enemy_x, enemy_y, enemy_w, enemy_h, speed]); enemy_x += enemy_w + 30; } function drawEnemies() { for (var i = 0; i < enemies.length; i++) { ctx.drawImage(enemy, enemies[i][0], enemies[i][1]); } } function moveEnemies() { for (var i = 0; i < enemies.length; i++) { if (enemies[i][1] < height) { enemies[i][1] += enemies[i][4]; } else if (enemies[i][1] > height - 1) { enemies[i][1] = -45; } } } function clearCanvas() { ctx.clearRect(0,0,width,height); } function drawCharacter() { ctx.drawImage(character, character_x, character_y); if (rightKey) character_x += 5; else if (leftKey) character_x -= 5; if (character_x <= 0) character_x = 0; if ((character_x + character_w) >= width) character_x = width - character_w; } function drawlevel_1() { ctx.drawImage(level_1,level_1_bgX,level_1_bgY); if (level_1_bgY > 1792) { level_1_bgY = -1791; } level_1_bgY += 1.5; } function init() { canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); enemy = new Image(); enemy.src = 'character_1.gif'; character = new Image(); character.src = 'character_1.gif'; level_1 = new Image(); level_1.src = 'level_1.jpg'; setInterval(gameLoop, 25); document.addEventListener('keydown', keyDown, false); document.addEventListener('keyup', keyUp, false); } function gameLoop() { clearCanvas(); drawlevel_1(); moveEnemies(); drawEnemies(); drawCharacter(); } function keyDown(e) { if (e.keyCode == 39) rightKey = true; else if (e.keyCode == 37) leftKey = true; } function keyUp(e) { if (e.keyCode == 39) rightKey = false; else if (e.keyCode == 37) leftKey = false; } window.onload = init; </script> </head> <body> <canvas id="canvas" width="320" height="480"></canvas> </body> </html> Thanks I've gone far enough with my website and thanks to you guys i completed a lot of issues i had. I just included a browser detect snippet which is supposed to show the pages correctly on IE, Firefox, Safari, Opera and Chrome. I understand that watching a greek site won't make much sense for you, but i'm hoping you will at least understand how the thing goes. The first yellow box on your left is the menu. Clicking there will take you to the menu's categories. You will find a few categories in english there, at least Now, in each category, clicking the button below the product should put it in the cart, part of it appears on every page in a floating layer to the top-right. There is also a link in there to "checkout" (ΟΛΟΚΛΗΡΩΣΗ ΠΑΡΑΓΓΕΛΙΑΣ). This is where the problem comes: In every browser except Chrome, the list of items of the cart will appear. I don't know why but in Chrome, not only i see nothing in there, but it also deletes everything in the cart! If any of you, specially the ones who have many browsers installed, could spend a little time testing my site, i would really appreciate it. Old Pedant and Phillip should be more aware since you guys have already helped me out and you kinda know the functionality of the site. The address is: lukulos.gr (works directly now, no need to type specific files) please help me~~Hi I have to create a table using javascript. Firefox displays the expected result but for IE, the column width is screwed >"< I have to use the col tag to set width because sometimes the first row maybe merged. All I need is to create a table that strictly displays according to the inputted column widths from my program. In below I have setup very short example that construct table in a similar way to my original javascript function. I also draw a ruler to help showing the proper width of 400px on the screen. column 1 should be 100px width and column 2 should be 300px. Please help me~~T_T Code: <?xml version='1.0' encoding='UTF-8'?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <body onload="init()"> Hard Coded: <DIV style="WIDTH: 400px; HEIGHT: 25px;overflow:hidden;"> <TABLE style="border:none; BORDER-SPACING: 0px; WIDTH: 400px; TABLE-LAYOUT: fixed" cellSpacing="0" cellpadding="0"> <col width="100px"> <col width="300px"> <TBODY> <TR> <TD style="background-color:blue"> a </TD> <TD style="background-color:green"> b </TD> </TR> </TBODY> </TABLE> </DIV> Ruler: <div id='ruler' style="background-color:yellow;width:400px;height:28px;"></div> Javascript inserted: <div id="hi"> </div> </body> <script language="javascript"> function init() { var w = [100, 300] // test table create var testDiv, testTBody, testTable, testTr, testTd, testCol; document.getElementById("hi").appendChild(testDiv = document.createElement("div")); with (testDiv.style) { width="400px"; height="25px"; } testDiv.appendChild(testTable = document.createElement("table")); with (testTable) { style.tableLayout="fixed"; style.borderSpacing="0px"; style.width = "400px"; appendChild(testCol = document.createElement("col")); testCol.style.width = 100 + 'px'; appendChild(testCol = document.createElement("col")); //testCol.style.width = 300 + 'px'; appendChild(testTBody = document.createElement("tbody")); cellSpacing= 0 } testTBody.appendChild(testTr = document.createElement("tr")); with (testTr){ } for (var i= 0; i < 2; i++) { testTr.appendChild(testTd = document.createElement("td")); testTd.innerHTML = "Testing"; with (testTd) { style.borderTop = "1px solid lightgray"; style.borderLeft="1px solid lightgray"; style.borderRight="1px solid black"; style.borderBottom="1px solid black"; } } } </script> </html> Code: <html> <head> <script> function testemail(){ var fld= document.getElementById("input1").value; var reg = /^[\w+]@[\w+].com$/i; if(reg.test(fld)) { alert("email is ok"); } else { alert("email is not correct"); } } </script> </head> <body> <p> <form name="form1" onsubmit="testemail()"> enter email : <input id="input1" type="text" /> <input id="input2" type="submit" value="Submit" /> </form> </p> </body> </html> I am trying to test an email ID with above RegExp. I enter a correct email or not, I am always getting message "email is not correct" So RegExp is not working. How can I find out whats wrong with this RegExp ? Is there any tool to figure that out ? I tried with FireBug, but it does not point to whats wrong with RegExp Thanks Can someone advise me how I could get this websocket to work. I'm working off a tutorial which gives this example. Code: var connection = new WebSocket('ws://html5rocks.websocket.org/echo', ['soap', 'xmpp']); // When the connection is open, send some data to the server connection.onopen = function () { connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; // Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); }; This does work and I can write something similar can get the correct results as long as I am connecting to that address. I am not able to get the same results from my server and I cannot even get the sockets onopen function to run. Here is my JS Code- Code: socket = new WebSocket("ws://micahwilliamson.com:80/socket.php", ['soap', 'xmpp']); socket.onmessage = function(e) { alert(e.data); } socket.onopen = function() { alert("Success"); socket.send("test"); } socket.onerror = function(err) { alert(err); } Here is my php socket code. Code: <?php ini_set("display_errors", 1); $host = "localhost"; $port = 80; $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket"); $bind = socket_bind($socket, $host, $port) or ("Could not bind to socket"); $listen = socket_listen($socket, 3) or die("Could not listen to socket"); $spawn = socket_accept($socket) or die("Could not accept incoming connection"); $input = socket_read($spawn, 1024) or die("Could not read input"); $input = trim($input); $output = strrev($input); socket_write($spawn, $output, strlen($output)) or die("Could not write to socket"); socket_close($spawn); socket_close($socket); ?> It seems the socket cannot make a connection so it could be my php code or the file hosting server just wont allow it. I got a VPS- maybe that would work better? Code: //Script to Rotate Images and Transition Effects var slidespeed=2000 var slideimages=new Array("1.jpg","2.jpg","3.jpg") var whichimage=0 var imgobj, filtersupport, blenddelay var imageholder=new Array() for (i=0;i<slideimages.length;i++){ //preload images imageholder[i]=new Image() imageholder[i].src=slideimages[i] } function slideit(){ if (filtersupport) imgobj.filters[0].apply() imgobj.src=imageholder[whichimage].src if (filtersupport) imgobj.filters[0].play() whichimage=(whichimage<slideimages.length-1)? whichimage+1 : 0 setTimeout("slideit()", slidespeed+blenddelay) } //End Image Rotation/Transistion What object can I test for instead of "filtersupport" so that I can have an else {} for non-ie browsers? I have Javascript on my site and will not work at all if JS is disabled. How do I notify my users that the pull down menus use javascript and will not work unless they turn it on? |