Jack Toffolo Jack Toffolo - 1 year ago 83
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(){

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;

setObject('totCmts', curComment);

function fetchComments(){
var inlist=getObject('totCmts');
if(inlist === null){
//display the comments

My Html file

<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>
<header id="banner">
<button type="button" onclick="clearComment()">Clear
<button type="button" onclick="saveComment()">Save comment</button>
<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 id="cmtlist"></div>


Answer Source

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