Jack Toffolo Jack Toffolo - 21 days ago 10
HTML Question

When I reload the page my previous comments disappear - something to do with local storage

Trying to make it so that when I refresh the page the previous comments remain on the page. Not quite sure how to do it. Also was wondering how you would go about making it so that when you click on the namebox you don't have to highlight "name" and then write your name, you can just click and what you write simply replaces the "name".

//Functions for Homepage
function imgUpdate() {
var img = document.getElementById("navImg").alt;
if (img === "Cat Selfie") {
document.getElementById("navImg").src = "foo.jpg";
document.getElementById("navImg").alt = "foo"
}
else {
document.getElementById("navImg").src = "cat-selfie.jpg";
document.getElementById("navImg").alt = "Cat Selfie"
}
}

//Functions for Comments
function clearComment(){
$('#txt1').val(''); //short for getElement when using j query
};

function clearName(){
$('#namebox').val('');
};

function saveComment() {
var ctext = $('#txt1').val();
var cname = $('#namebox').val();
if (cname === 'Name') {cname = 'Anon';}
alert('saveComment cname=' + cname + ' ctext=' +ctext);
var d = Date();
var prevComments = $('#cmtlist').html();
var curComment='<p><span class="cmtname">'+cname+ ':' + '</span>'
+ctext +d+' </p>'; //span = add things to something inline
curComment += prevComments;
$('#cmtlist').empty();
$('#cmtlist').append(curComment);
clearComment();
clearName();

setObject('totCmts', curComment);
}



function fetchComments(){
var inlist=getObject('totCmts');
if(inlist === null){
inlist='';
}
//display the comments
$('#cmtlist').empty();
$('#cmtlist').append(inlist);
}


My Html file

<html>
<head>
<meta charset="utf-8" />
<title>Dubya comments</title>
<link rel="stylesheet" href="homepage.css" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="homepage.js"></script>
</head>
<body>
<header id="banner">
</header>
<nav>
<button type="button" onclick="clearComment()">Clear
comment</button>
<button type="button" onclick="saveComment()">Save comment</button>
</nav>
<div id="main">
<div id="dtext">
<h4>Your comment</h4>
<input id="namebox" type="text" maxlength="32" size="20"
value="Name" />
<br />
<textarea id="txt1" class="textbox" rows="6"></textarea>
</div>
<h4>Comments</h4>
<div id="cmtlist"></div>
</div>
</body>

</html>

Answer

Jack, you can easily store data in localStorage using global object like this:

// your array with comments
var comments = ["First comment", "Second comment"];

// saving your comments in JSON format
window.localStorage.setItem("comments", JSON.stringify(comments));

// retrieving them
comments = JSON.parse(window.localStorage.getItem("comments"));

You can read more about localStorage on MDN