Comments disappear after refreshing site


I’m trying to make a simple comment system. It display comments, but when I refresh the page , all comments disappear, only to re-appear again when I add a new comment. I would like to see the comments even after refreshing the page. And preferably with time stamp and in reverse order: so latest on top.

const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');

// array to store the comments
var comments_arr = [];

if(!localStorage.commentData){localStorage.commentData = [];}
  comments_arr = JSON.parse(localStorage.commentData);

// to generate html list based on comments array
const display_comments = () => {
  let list = '<ul>';
   comments_arr.forEach(comment => {
    list += `<li>${comment}</li>`;
  list += '</ul>';
  comments.innerHTML = list;

submit.onclick = function(event){
    const content = field.value;
    if(content.length > 0){ // if there is content
      // add the comment to the array
      localStorage.commentData = JSON.stringify(comments_arr);
      // re-genrate the comment html list
      // reset the textArea content 
      field.value = '';
html {
    font-size: 14px;
    font-family: "Open Sans", sans-serif;
    background-color: rgb(239, 239, 238);

  /*Comment section*/
textarea {
  margin: 40px 0px 10px 0px;
  background-color: rgb(255, 255, 255);
  width: 800px;
  padding: 10px;
  line-height: 1.5;
  border-radius: 5px;
  border: 1px solid #7097d1;
  box-shadow: 1px 1px 1px #999;

#submit {
  border-radius: 5px;
  border: 1px solid #7097d1;
  background-color: #e2e9ea;

#submit:hover {
    background-color: #7097d1;

li {
    list-style-type: none;
    width: 770px;
    margin: 10px 0px 10px -20px;
    padding: 5px;
    border-radius: 5px;
    border: 1px solid #7097d1;
    box-shadow: 1px 1px 1px #999;
    background-color: #e2e9ea;
<link href="comment.css" rel="stylesheet">

    <textarea id="comment" placeholder="Your response pls." value=""></textarea>
<input id="submit" type="submit" value="add">
       <div id="comment-box"></div>

<script src="comment.js"></script>


Adding window.addEventListener('load', display_comments) will fix
This will run the display_comments function on every refresh

Answered By – CodeBreaker

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published