Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Maison012's avatar

How to drag and drop div and save on localStorage

I have done this example https://codesandbox.io/s/practical-artem-v9xqk3?file=/src/components/draggable/Border.vue . It is working now just for drag and drop between divs. What i want next is to save the new position of div after dragging on localstorage, so after page reload divs can keep they new position. How can i do this on my example?

0 likes
8 replies
Maison012's avatar

@vincent15000 i have tryed to create something like this

drop: e => {
                const card_id = e.dataTransfer.getData('card_id');
                const card = document.getElementById(card_id);
                
                let op1 = card.offsetTop;
                let op2 = card.offsetLeft;
                let cardPosition = op1 + op2; 
                // card.style.display = "block";
                card.style.opacity = "1";
                e.target.appendChild(card);
                // console.log(JSON.parse(e.target.appendChild(card)));
                localStorage.setItem('reorder-stat', cardPosition);
            }

and save on loacal storage a value key: reorder-stat; value: 555; if is the right way. I know maybe is a basically question but i does not know where to put my localStorage.getTiem('reorder-stat')

note but i also can get x and y position like this drop: e => { console.log(e.x);

1 like
vincent15000's avatar

@Leon012 You are adding op1 and op2, that has no sense, you need to save both values separately.

You could for example create a JSON object to store both values of the position and then stringify the JSON object so that you can store it in the localStorage.

Maison012's avatar

@vincent15000 hello again anth thank you for responding, i have tryed a lot but nothing works on this. Logicaly i know where is the problem bur i cant do it on the code. Maybe it is really simple just it is my first time i do this. Plase can you do an example with my code?

1 like
vincent15000's avatar

@Leon012 You need to save both values separately, so don't add them. I assume you rarely coded before, you should have a look at some tutorials. You have great Laracast series on JavaScript and VueJS. And you could probably find some advise about algorithms.

vincent15000's avatar

@Leon012 You should try AlpineJS, it's a very interesting library. But it doesn't replace any knowledge about algorithms, JS and VueJS.

Please or to participate in this conversation.