How to make the position of a moving div be saved automatically?

Asked

Viewed 179 times

2

I developed a widget for my project and now I need that, when moving it, your position is saved.

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

I hope my doubt becomes clear.

  • Understand I think it does, but in what part of the procedure are you having difficulty?

  • Like the part where he takes the position I left and saves in css

  • @Daniel changing the CSS file will take a lot of work, I believe localStorage be a good option.

1 answer

4


If I understand your question, you have a div that scrolls over the page and you want always the last position occupied by it to be saved by loading the page again, correct? Well, if that’s what it is, I developed a script and using the localStorage except the last position, left and top, of div.
It will not be possible to implement the code in the Stackoverflow snippet because it does not allow the use of the localStorage for security reasons.
You can see the implementation working perfectly on 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 on jsfiddle

Reference: MDN - localStorage

  • 1

    Bro all right it’s a little problem, it gets selected no matter what I do.

  • 1

    Good. Daniel: this will save the position on the computer and browser you are using. If you want it to persist between different computers or browsers, you will need to save the position in a database, or in a file on the server.

  • @Daniel perhaps why the mouseup were in the box, I switched to the object window, test to see if to.

  • @devgaspa changed it right, only the problem is that it ends up opening a margin of some '50 px' of the mouse cursor

  • @Daniel if you look at the code, that part (e.clientX - 50), both left and top are subtracted half the width and height of the box so that the mouse is centered on it. Anyway, you have to change the value 50 for half of your box

Browser other questions tagged

You are not signed in. Login or sign up in order to post.