Set <div> position from data stored in localStorage

I am trying to learn how to use localStorage.

Partially imitating, I wrote html, which generates a page with several fragments that can be dragged around the page.

for example

<script type="text/javascript"> function drag_start(event){ var style = window.getComputedStyle(event.target, null); var str = (parseInt(style.getPropertyValue("left")) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top")) - event.clientY)+ ',' + event.target.id; event.dataTransfer.setData("Text",str); event.stopPropagation(); } function drop(event){ var offset = event.dataTransfer.getData("Text").split(','); var dm = document.getElementById(offset[2]); dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px'; dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px'; localStorage.setItem(dm.id,dm.style.left); event.preventDefault(); return false; } function drag_over(event){ event.preventDefault(); return false; } </script> 

I think that with a line like the first starting with "localStorage", I can keep the position in localStorage after the fall. [The current line is just an example. Later, when I understand these things, I will really maintain a position or bias.]

The part I'm confused with is how to get the position from localStorage when the page loads.

Let's say that I will have one of the tiles

 <div id="tile3" draggable="true" ondragstart="drag_start(event)"> <a href="http://www.link.somewhere"> Link </a> </div> 

I can say that the tile has style="position:absolute" , and then I will need to get the offset from localStorage and set it as a div property.

But how to make this last part?

+7
javascript html css html5
source share
1 answer

to save you use this javascript command:

(assuming thePosition is an array with two values ​​(position x and y))

 localStorage.setItem("position", JSON.Stringify(thePosition)); 

in pageload you can do something like this (assuming you are using jquery):

 $(document).ready(function(){ var position = JSON.parse(localStorage.getItem("position")); $('#the-divs-id').css({'left': position[0], 'top': position[1]}); }); 

edit: added JSON stringify / parse for array

If you do not want to use jquery:

 window.onload = setDiv(); function setDiv(){ var position = JSON.parse(localStorage.getItem("position")); document.getElementById(the-divs-id).style.left = position[0]; document.getElementById(the-divs-id).style.top = position[1]; } 

edit: loop question:

 $(document).ready(function(){ // loops trough all divs with the-class $('.the-class').each(function(){ // get the id from the current div // and get the corresponding position from local storage var id = $(this).attr('id'), position = JSON.parse(localStorage.getItem(id)); // sets the css values for the current div $(this).css({'left': position[0], 'top': position[1]}); }); }); 
+3
source share

All Articles