user43052
user43052

Reputation: 37

Local Storage - Jquery

The thing is when i click on a button, it creates a clone of the div which is draggable and i want to save the position of the cloned moved divs after refresh using local storage .Right now with my code I can save the original div but the cloned divs are removed after refresh.Please offer solution to get the required functionality.For JS:

var sPositions = localStorage.positions || "{}",
    positions = JSON.parse(sPositions);
$.each(positions, function (id, pos) {
    $("#" + id).css(pos)
})
$("#divd").draggable({
    containment: "#containment-wrapper",
    scroll: false,
    stop: function (event, ui) {
        positions[this.id] = ui.position;
        localStorage.positions = JSON.stringify(positions);
    }
});


$("#button").click(function () {
    $("#divd").clone().insertAfter("#body").draggable();
});

Here is the original div code -

<div id="divd" class="draggable ui-widget-content"></div>
<button id="button">Button</button>

Upvotes: 1

Views: 335

Answers (1)

Kishore Sahasranaman
Kishore Sahasranaman

Reputation: 4230

recreate all the div when load, and bind them with draggable.

see the below example :

var globalCount = 1;
var sPositions = localStorage.positions || "{}",
    positions = JSON.parse(sPositions);
$.each(positions, function (id, pos) {
    if(id != "divd"){
     	var cloned = $("#divd").clone();
        cloned[0].id = id;
        cloned.insertAfter("#divd")
         globalCount++;
    }
    $("#" + id).css(pos)
});
$(".common-drag").draggable({
    containment: "#containment-wrapper",
    scroll: false,
    stop: function (event, ui) {
        positions[this.id] = ui.position
        localStorage.positions = JSON.stringify(positions)
    }
});

$("#button").click(function () {
    var cloned = $("#divd").clone();
    cloned[0].id = "divd" + globalCount++;
    cloned.insertAfter("#divd").draggable({
        containment: "#containment-wrapper",
        scroll: false,
        stop: function (event, ui) {
            positions[this.id] = ui.position
            localStorage.positions = JSON.stringify(positions)
        }
    });
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css">

<div id="divd" class="draggable ui-widget-content common-drag">Test</div>
<button id="button">Button</button>

Demo : http://jsfiddle.net/kishoresahas/sh72djwz/

With Multiple Type of Divs :

Demo : http://jsfiddle.net/kishoresahas/sh72djwz/2/

Upvotes: 1

Related Questions