Home > Software design >  Comments disappear after refreshing site
Comments disappear after refreshing site

Time:10-10

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 = [];}
else{
  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){
    event.preventDefault();
    const content = field.value;
    if(content.length > 0){ // if there is content
      // add the comment to the array
      comments_arr.push(content);
      localStorage.commentData = JSON.stringify(comments_arr);
      // re-genrate the comment html list
      display_comments();
      // 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">

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

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

CodePudding user response:

You call display_comments after submitting a comment, but you don't call it anywhere else - it needs to be called when the page loads as well.

CodePudding user response:

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

  • Related