Determine the placement of a <div> based on information stored in localStorage

I'm diving into the world of localStorage and trying to figure out how it works.

To get a better understanding, I decided to create an HTML page that allows users to drag and drop tiles around the screen.

Here's a snippet of the code I came up with:

<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();
    }

    // More functions for handling drag and drop

</script>

I believe that by incorporating a line similar to the one above starting with "localStorage," I can store the position after each drop action. Of course, this is just a simplified example for now.

My current challenge lies in retrieving the saved positions from localStorage when the page loads again.

Take, for instance, one of the draggable tiles like this:

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

The tile has a CSS property of style="position:absolute", so I need to fetch the offset data from localStorage and apply it as a property of the div.

But how exactly do I go about doing this last step?

Answer №1

To save your position, use the following JavaScript command:

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

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

When the page loads, you can implement 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]});
});

Note: Added JSON stringify/parse for the array

If you prefer not 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];
}

Regarding the looping question:

$(document).ready(function(){
  // loops through all divs with the-class
  $('.the-class').each(function(){
    // get the id from the current div
    // and retrieve 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]});
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Returning to the previous page

Having some trouble navigating back to the previous page. When I click the cancel button, it runs a function that uses history.back();, which works correctly. However, there is a validation on the page, so it checks all fields before navigating back. I&ap ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at The benefit of rendering JSON in string format within the page response is that it allows for the efficient loading of da ...

Arranging h1 tags within a container id

Seeking assistance with aligning specific classes in a certain way: "left" should align to the left part of #header, "links" should be centered, and "right" should align to the right of #header. Additionally, I want the icons to align vertically with the t ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

Fluidly move through spaces where subsequent elements align to the top level

In the black container, there is an {overflow:hidden;} CSS property applied The yellow blocks are ordered in code according to the numbers and have {float:left;} I am aiming for the 5th element to align with the element above it: However, currently this ...

Combining the inline JavaScript linting tool ESLint with the popular Airbnb configuration and Facebook

In my current project, I am utilizing ESLint and looking to incorporate Facebook flow. However, I am encountering warnings from ESLint regarding flow type annotations. Within the project root directory, I have both .flowconfig and .eslintrc files present. ...

Ways to convert field data to lowercase in MongoDB query result

I have two Objects in my database collection. [ {"_id" : 1, name: "notLowercased"}, {"_id" : 2, name: "lowercased"}, ] Using find and $regex to search for names that include a specific string. data = await Catal ...

Angular - Ensuring service completion before proceeding with navigation

I'm currently facing an issue where I need to populate data in a service before navigating, but the navigation is happening before the data is ready. Here's the code in my service: addToken(token) { this.cookieService.set( 'token', ...

Navigating a loop in javascript: tips and techniques

I have a challenge with three boxes that are supposed to fade in, shake, and then fade out. The IDs of each box are stored in an array and a loop is used to traverse them. However, the loop only displays the first item. I have tried various methods in Jav ...

Node.js, PHP, and the Express framework

I have a project where I need to develop a to-do list and a form that allows users to upload png files using Node.js. Currently, I am using the following packages: { "name": "todo", "version": "0.0.1", "private": true, "dependencies": { "ejs": ...

The grpc client is not able to receive the data being streamed from the

I've been attempting to stream the output of a nodejs child process through grpc, but I consistently receive an empty result. Here is my proto file: syntax = "proto3"; package servicePackage; service Mobile { rpc sign(Empty) returns ( ...

Attempting to transmit unique symbols using JQuery Ajax to a PHP script

I am using JQuery Ajax to send special characters to a PHP file. sending_special_characters.js var special_chars = '!@#$%^&*()_+-='; var dataToSend = 'data=' + special_chars; $.ajax({ type: "POST", ...

The issue of Datatables child row not refreshing when using AJAX

I'm attempting to retrieve child row data in Datatables using AJAX: $('#myTable tbody').on('click', 'td', function () { var tr = $(this).closest('tr'); var row = myTable.row( tr ); if ( row.child.isS ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

Ways to ensure a ul li element perfectly fits inside a div element without any spaces

As a newcomer to CSS and HTML, I'm facing an issue with my ul li dropdown menu and login boxes. The background colors are red and blue, but there are gaps within the div that I want to fill with the height of the div. Below is the code snippet: @key ...

Trigger an event when hovering over a disabled item in React using material-ui's tooltip feature

I've been trying to figure out how to hover over a disabled item with a tooltip, but it seems that disabled items don't trigger any events. I attempted wrapping my elements in another div as a workaround, but unfortunately, it didn't work. I ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...