Search code examples
javascripthtmlpositiondraggable

How can I save draggable div positions in html


I'm a newbie in html and javascripts, and trying to save my draggable div positions after clicking save button in my web application. my question is little bit different with others that I'm using Websocket for getting data

Here is my draggable divs which is creating from websocket in javascript code

function WebSocket(){
  if ("WebSocket" in window){
    var channel = "hello";
    var socket = io.connect("my socket address here");

    socket.on(channel, function (d) {
      var data = JSON.parse(d);
      console.log(channel + " : " + d);
      var theDiv = document.getElementById(data.node_info[1].info.mac);
      if(theDiv == null) {
        var divTag = document.createElement("div");
        divTag.id = data.node_info[1].info.mac;   //"drag1"
        divTag.className = "draggable js-drag";
        divTag.innerHTML = data.node_info[1].info.mac;
        document.getElementsByTagName('body')[0].appendChild(divTag);
        //document.getElementsByName('scroll_div')[0].appendChild(divTag);
        //$('#'+data.node_info[1].info.mac).load('#'+data.node_info[1].info.mac);
      }
    });
    socket.on('crc_err', function(packet){
      console.log("crc_err : " + packet);
    });
    socket.on('type_err', function(packet){
      console.log("type_err : " + packet);
    });
  } else{
    // The browser doesn't support WebSocket
    // alert("WebSocket NOT supported by your Browser!");
  }
}

I created divTags with id, className, innerHTML and each of them shows mac addresses and put them in the body of html.

Also, I want those draggable divs is positioned in same places as last time when users revisit my web app.

How should I do and any suggestions here??

Thanks in advance.

p.s If you need my css code or more code of html I can EDIT


Solution

  • Use localStorage

    To save

    localStorage.setItem(divTag.id + '-X', leftPosition);
    localStorage.setItem(divTag.id + '-Y', topPosition);
    

    To load back

    divTag.style.left = localStorage.getItem(divTag.id + '-X') + 'px';
    divTag.style.top = localStorage.getItem(divTag.id + '-Y') + 'px';