The page im experimenting with is like a simple notes page where you click a button to create divs that are movable on the page. So i want these divs to stay on the page when i reload it. How would i go about solving this issue in the best way? Ive experimented alot with localStorage but without success.
Here is simplified version of how i create and move them:
window.onload = function() {
var iscklick = 0;
function trigger(id){
let tempid = "#div_" + id;
$(document).on('mousemove', function(event){
if(isclick){
$(tempid).css({'top':event.pageY - $('#div_' + id).outerHeight() /2, 'left':event.pageX - $(tempid).outerHeight() /2});
}
//mouseup makes it unstick and cleans tempid
}).on('mouseup',function(){
isclick = 0;
tempid = ""
})
}
$(document).ready(function(){
$(".container").on('mouseover', '.element', function(){
var id = this.id;
var split_id = id.split("_");
var finalid = split_id[1];
//mousedown triggers func
$("#div_" + finalid).on('mousedown', function(){
isclick = 1;
trigger(finalid);
})
})
$(".add").click(function(){
var lastid = $(".element:last").attr("id");
var split_id = lastid.split("_");
var nextindex = Number(split_id[1]) + 1;
$(".element:last").after("<div class='element' id='div_"+ nextindex +"'></div>");
$("#div_" + nextindex).append("");
});
});
};
html, body{
background-color:lightgray;
margin:0;
height:100%;
width:100%;
}
.add {
position: relative;
float:left;
background-color: rgb(105, 230, 188);
color: white;
border: none;
height: 50px;
width: 50px;
font-size: 43px;
font-weight: bolder;
box-shadow: 0 2px 4px darkslategray;
cursor: pointer;
border-radius: 70%;
transition: all 0.2s ease;
top:45%;
margin: 2%;
}
.add:active{
background-color: rgb(45, 138, 107);
box-shadow: 0 0 2px darkslategray;
transform: translateY(2px);
}
.element{
position:absolute;
padding: 5px;
height: 100px;
width: 200px;
background-color: yellow;
box-shadow: 0 2px 4px rgb(172, 172, 106);
margin: 1%;
border-radius: 10px;
float:left;
}
.element:hover{
z-index: 1;
}
#div_1{
display: none;
}
<!doctype html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="main.js"></script>
<html >
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<button class='add'>+</button>
<div class="container" >
<div class='element' id='div_1'></div>
</div>
</body>
</html>
Thanks in advance, im just trying to learn how to save states in jquery.
Ive tried alot of localStorage and looked into cookies but i dont really understand what the best way is to tackle this issue when there are so many things that need to be saved. I also plan on adding loads more and basically everything that the user does needs to stick after you reload the page.
2
Answers
You have to use
localStorage
, but the catch is that you have to save yourcontainer
HTML to it.You need to do it on the add button click as well as on the
trigger()
function called (to save HTML with positions)Here is the working snippet:
Result: https://jsfiddle.net/5ep9v3kr/
You can consider using
localStorage
which will work for the user, without losing its saved state when the user’s session is destroyed. Or you can usesessionStorage
which stores data for the current session.To be agnostic, I will use the term
myStorage
and you replace it withlocalStorage
orsessionStorage
, depending on your preference.Things to know:
myStorage.setItem(key, value)
sets the value to be stored as key, for examplemyStorage.setItem('name', 'John Doe')
, you will need to pass a string to this one, so you might need to doJSON.stringify(thestuff)
myStorage.getItem(key)
returns the string that was stored at the key, defaulting tonull
. If you want to work with something else than a string, then you will need to parse this back, viaJSON.parse(thestuff)
or your parsing functionalitiesThe other answer suggests storing the HTML inside your storage, but that’s wasting memory and it’s a rather volatile approach, because if you change your HTML, then all the already stored HTMLs will be invalid when they are loaded back.
Instead, I strongly suggest to:
function
togetDataFromHTML(thehtml)
function
togetHTMLFromData(thedata)
myStorage.setItem(JSON.stringify(thekey, getDataFromHTML(thehtml)))
myStorage.getItem(JSON.parse(thekey))
Of course, it’s your responsibility to get the HTML, find the data from an HTML and specify your key.