How do you position a moving div to be automatically saved?

2

I've developed a widget for my project and now I need it to be saved when I move it.

Example: Initial position of widget 80px x 120px , after move it, initial position of widget 210px x 300px .

I hope my doubt is clear.

    
asked by anonymous 04.12.2015 / 21:16

1 answer

4

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

    
04.12.2015 / 23:30