If I understood your question, you have a div
that moves over the page and you want the last position occupied by it to always be saved when loading the page again, correct? Well, if this is it, I have developed a script
and using localStorage
save the last position, left
and top
, div
. You will not be able to implement the code in the StackOverflow snippet by that it does not allow the use of localStorage
for security reasons.
You can see the implementation working perfectly in the jsfiddle . .
Script:
window.addEventListener('DOMContentLoaded', function() {
var box = document.getElementById('box');
var draggable = false;
var bLeft = localStorage.getItem('bLeft') || '';
var bTop = localStorage.getItem('bTop') || '';
box.style.left = bLeft;
box.style.top = bTop;
box.addEventListener('mousedown', function() {
draggable = true;
});
window.addEventListener('mouseup', function() {
draggable = false;
});
window.addEventListener('mousemove', function(e) {
if(draggable) {
box.style.left = (e.clientX - 50) + 'px';
box.style.top = (e.clientY - 50) + 'px';
localStorage.setItem('bLeft', box.style.left);
localStorage.setItem('bTop', box.style.top);
}
});
});
See working at jsfiddle
Reference: MDN - localStorage