What's the best way to keep track of the most recent location to which an element was moved

Presently, I'm utilizing this script:


let mousePosition;
let offset = [0,0];
let div;

let isDown = false;

div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";  
div.style.top = "0px";
div.style.width = "237px";
div.style.height = "50px";
div.style.background = "red";
div.style.padding = "15px 0px 0px 0px";
div.style.color = "blue";
div.id = "clock";

document.body.appendChild(div);

div.addEventListener('mousedown', function(e) {
isDown = true;
offset = [
    div.offsetLeft - e.clientX,
    div.offsetTop - e.clientY
];
}, true);

document.addEventListener('mouseup', function() {
isDown = false;
}, true);

document.addEventListener('mousemove', function(event) {
event.preventDefault();
if (isDown) {
    mousePosition = {
        x : event.clientX,
        y : event.clientY
    };
    div.style.left = (mousePosition.x + offset[0]) + 'px';
    div.style.top  = (mousePosition.y + offset[1]) + 'px';
    }
}, true);

This script enables me to drag a div element using my mouse. As a JavaScript novice, I am still learning.

I am looking for a simple way to save the final position of the Div so that when I reopen the HTML file, the Div will appear in its last saved location.

Thank you.

Answer №1

To store the location information in your browser, you can utilize the power of localStorage.

window.localStorage.setItem('divPosition', JSON.stringify({
  left: div.style.left, 
  top: div.style.top
}));

console.log(JSON.parse(window.localStorage.getItem('divPosition')));

Keep in mind that localStorage is limited to storing string values only, so for more complex data, make sure to stringify and parse it accordingly.

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

The class [AdminController] being targeted does not exist

https://i.sstatic.net/r6c7q.pngI encountered an issue where a user is redirected from login to the admin page (e.g. ), and a 403 error should be triggered if the user is not logged in as an admin. Interestingly, even the admin experiences the same error. ...

Can the lib property in tsconfig.json override the target property?

Just starting out with Typescript, I have a query regarding the lib and target properties. Below is my tsconfig.json file: { "compilerOptions": { "target": "es5", "outDir": "./dist", "rootDir": "./src", "noEmitOnError": true, } } //index.ts consol ...

Position the container flush with the left edge and expand it to occupy the entire right side

Can someone help me figure out how to align a carousel with the left side of a container and make the right side stretch to fill the remaining space? Check out the image in the link below for reference. Much appreciated. https://i.sstatic.net/SMlkd.png ...

Navigating into uncharted territories with each touch movement

Is there a way to change the background of an element as you drag your finger over it? It seems like using the touchmove event might work for this, but I'm having trouble getting the target element to change as I drag. While clientX and clientY value ...

What is the best way to align text in "reverse order" to the center?

While utilizing text-align: center, I noticed that the remainder remains at the end. Here is how it currently looks: https://i.sstatic.net/DjQU4.png However, I am seeking to achieve this effect where the remainder remains at the start: https://i.sstatic ...

Display complex 3D models using three.js

This question is widely known, but unfortunately, I have been unable to find a satisfactory answer. My Approach I utilize three.js for showcasing 3D models generated from drone images (example here). The Issue I face difficulty rendering large models ( ...

Firefox is having trouble defining the HTML form attribute "name"

Here is some code that I have in my JSP page: <form name = loginform method = post action=""> <table class=registerTable> <tr> <td>Username:</td></tr> <tr><td> <input name=user type=t ...

Choose the element excluding a particular child

My issue is: I have a div with multiple children and I am trying to figure out how to exclude a specific element that is a child of the previously selected element. I attempted using the :not(selectedElement) selector as well as the .not(selectedElement) ...

Issue with sending form data to MySQL database

I have a couple of forms that need to be submitted to my database. I created a general function to update a specified table, but the problem is that the code doesn't modify the database; it only changes the column (fullname) to zero. Below is my code, ...

What is the process by which Next.js uses useRouter() to interpret the mapping variable?

const router = useRouter(); return ( <> {Usercategory.map((user,index)=>{ return <div className='user-li' key={index} onClick={()=>{router.push(user.link)}}> <li> {use ...

What sets bootstrap.css apart from bootstrap-responsive.css?

Can you explain the difference between bootstrap.css and bootstrap-responsive.css? I'm unsure which one is best for creating responsive websites. ...

Looking for assistance with eliminating the excess white space that's appearing between two div elements

Seeking assistance to remove the unwanted whitespace in my code. I have attempted to set *{margin:0} as well as for p and pre tags, but it hasn't been effective. The issue persists even though I am using BS4. Here is the snippet of the troublesome cod ...

Send a personalized array from Javascript to a Spring Rest Service using Ajax

I am faced with the task of creating a POST request using AJAX in jQuery. This involves passing an array of objects, which I can achieve with the following code: var actor = new Array(); for(var i = 1; i <= incr; i++) { actor.push({ "name": ...

Extend JavaScript capabilities for window.print() function to automatically include backgrounds

I am looking to add a special magical property to my Print this Page button. This property will automatically enable the default unset option (shown in the picture) which is to print the backgrounds of div colors and background images. <a href="#" oncl ...

"Centering an Image in ASP.NET HyperLink Control: A Step-by-Step

Here is the setup for my control: <asp:HyperLink CssClass="link-image" ID="Link1" runat="server"/> Code-behind in C#: Link1.ImageUrl = "imagePath"; Resulting HTML code: <a class="link-image" id="MainContent_Link1"> <img alt="" src=" ...

Looking to halt navigation in a Chrome browser immediately after performing a click action with Selenium?

Is there a way to prevent the browser from loading immediately after a click event? Are there any workarounds or JavaScript implementations for achieving this? ...

Changing the value in a multi-dimensional array using a specific path represented in array or any other format

In my project, I am dealing with a multidimensional array that represents a deep category tree menu. The structure of the array looks like this: this.tree = [{ "title": "1. dragon-breath", "items": [] }, { "title": "2. moiré-vision", "ite ...

cancel button in confirmation dialog is malfunctioning

Having an issue with a button that triggers a confirmation dialog: <asp:Button ID="btnSignOff" runat="server" CssClass="button" Text="Sign OFF" OnClick="btnSignOff_Click" OnClientClick="return confirm('Are you sure you want to Sign OF ...

Building a website on Prestashop without disrupting the functionality of the online store

Is it possible for me to make updates to my website without affecting the live Prestashop store? I am looking to modify the template store including ".tpl" files, css, and javascript, but I want to ensure that these changes do not impact the online store ...

Is it Possible to Craft a Dropdown Navigation Menu with the Nav Element?

Currently, I am in the process of developing a website for a stock plan home designer. I need to design a navigation bar using the nav tag, but unfortunately, I have been unable to find any resources online that provide guidance on how to achieve this. I ...