How to save drag&drop to localStorage?

I wanted to save my drag to localStorage but when i refresh , dragged place is not where i dropped it. I used jQuery UI |Draggable.

JSFIDDLE.

How can we save it to localStorage ?

HTML

<p id="text">Lorem ipsum dolor sit amet.</p>
<button id="save">Save localStorage</button>
<button id="clear">Clear localStorage</button>

<div id="append-area"></div>

JS

$(function() {

$("#save").click(function() {
var text =$("#text").text();
$("#append-area").append(text+"<br>");

var appended=$("#append-area").html();
localStorage.setItem("appended",appended);
});

if (localStorage.getItem('appended')) {
  $('#append-area').html(localStorage.getItem('appended'));  
}

$("#append-area").draggable();

$("#clear").click(function() {
 window.localStorage.clear();
 window.location.reload();
});

});

Answers 1

  • Try this, Hope this is what you are looking..:)

    fiddle link https://jsfiddle.net/5mwndskb/1/

     $(function() {
      var getPos = JSON.parse(localStorage.getItem("appended"));
      var currentPos = {
        top: 0,
        left: 0
      };
      if (getPos !== null && getPos.top !== null) {
        $('#append-area').css({
          top: getPos.top,
          left: getPos.left
       }).append(getPos.txt);
      };
    
      $('#append-area').draggable({
    
        drag: function(event, ui) {
    
          currentPos = $(this).position();
        }
      });
    
      $("#save").click(function() {
        var text = $("#text").text();
        currentPos.txt = text;
        $("#append-area").append(text + "<br>");
        localStorage.setItem("appended", JSON.stringify(currentPos));
      });
    
      $("#clear").click(function() {
        window.localStorage.clear();
        window.location.reload();
      });
    
    });
    

Related Articles