So I'm making a web page where users can press buttons to add elements using appendChild
but when they refresh the page it all goes away. Is there something I can do to save what the users add to the page so that when they refresh it it stays the same?
HTML:
<input type="text" id="input" placeholder="write anything here...">
<button id="submit" onclick="createEl()">Submit</button>
<div class="text-div" id="text-div"></div>
CSS:
#input {
width: 500px;
height: 50px;
padding-left: 5px;
}
#submit {
height: 55px;
}
JAVASCRIPT:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
function createEl() {
if (inputField.value !== "") {
var p = document.createElement("p")
var pNode = document.createTextNode(inputField.value)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
}
Well, as people said earlier, if you want to load your data in all browsers regardless of where those data came from, you should set up a database based on your needs and specifications. Otherwise, you can get used to existing stuff in browsers such as localStorage. So you need to create a property in it, and then, on each page reload, check whether there is data saved there or not with the onload
event.
So your final code should be something like this:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
var items = [];
function createItem(item) {
var p = document.createElement("p")
var pNode = document.createTextNode(item)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
window.onload = function() {
if (window.localStorage.getItem("items") !== null) {
items = JSON.parse(window.localStorage.getItem("items"))
var itemsLength = items.length
for (var i = 0; i < itemsLength; i++) {
createItem(items[i])
}
}
}
function createEl() {
if (inputField.value !== "") {
createItem(inputField.value)
items.push(inputField.value)
window.localStorage.setItem("items", JSON.stringify(items))
}
}