javascript - On first time visit- popup a div asking user name, then store it and the date on local storage -
the problem here never goes else statement; tried creating flag check when goes if , changing didn't work
var ouser = {}; // add name js if (!ouser.name) { ouser.name = prompt("enter name: ") // add name js localstorage.name = ouser.name // time ouser.date = new date().toutcstring(); localstorage.date = ouser.date; } else { var msgdis = document.getelementbyid('msgdisplay'); msgdis.innerhtml = "hi " + localstorage.name + " welcome back!" + " -->date: " + localstorage.date; }
ouser.name
undefined, !ouser.name
pass. you're creating ouser empty object (var ouser = {};
), checking data member never defined.
you should checking if localstorage set:
// declare ouser in global scope, empty object var ouser = {}; // check browser support of localstorage if(typeof(localstorage) == 'undefined') { // check failed, alert user alert('your browser not support localstorage method!'); } else { // wrapping in try...catch block, incase cookies disabled try { // attempt pull ouser (by key) localstorage, failure results // in ouser being empty object. ouser = json.parse(localstorage.getitem('ouser'))||{}; // check if ouser.name not set if(!ouser.name) { // prompt user name ouser.name = prompt("enter name: "); // insert current date ouser.date = (new date()).toutcstring(); // save ouser in localstorage, stringified localstorage.setitem('ouser',json.stringify(ouser)); } else { // ouser.name set, welcome them var msgdis = document.getelementbyid("msgdisplay"); msgdisplay.innerhtml = "hi " + ouser.name + " welcome back! -->date: " + ouser.date; } } catch(e) { // cookies disabled, threw error, alert user alert('to use localstorage, need enable cookies.'); } }
Comments
Post a Comment