0

I am trying to create a platform where multiple people can interact with each other by writing what they want to say, however, I can't figure out how to save the words said for when the page refreshes or is opened by someone else, can someone help? Btw here is the code for that section (I know it's sloppy but I hate having different files for different codes:

<!DOCTYPE html>
<html>
<head>
<title>Creatia</title>
</head>
<body>
<style>
button {
  margin-top: 20px;
  line-height: 60px;
  font-weight: bold;
  padding: 0 40px;
  background: blue;
  border: none;
}
</style>
<script>
var username = prompt('What should we call you?');
var button = document.createElement("button");
button.innerHTML = "Post";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
input = prompt("What do you want to say to the world?");
p = document.createElement("p");
p.innerHTML = "@" + username + " says: " + input; 
document.body.appendChild(p);
});
</script>
</body>
</html>   

I tried using local storage to save it, but either that doesn't work for prompts or there would need to be a new variable for every post or I need to use non local storage

1 Answers1

0

Know that what you're implementing and what I believe you want to have implemented are different.

Using localstorage will only work for a single browser session-to-session, and be completely seperate from any other computer. This would make sense on something like a library computer with multiple people accessing it, but if you're trying to make a website where multiple users across different computers can add messages, you need a CRUD app

That being said, i think the best way forward to do this locally would indeed be Window.localStorage, but I would save a JSON object with a list of comments, as follows

localStorage.setItem("comments", JSON.stringify(
    [
        "comment one",
        "comment two"
    ]
);

and you can retrieve it via

let comments = JSON.parse(localStorage.getItem("comments"))
Jam
  • 476
  • 3
  • 9