Can someone please help me!
I am working on assignment with drag & drop and localstorage. This is my first time writing a code involving localstorage. I'm creating someting like kanban board.
The problem I am having right now is, I have no idea how am i going to make all cards in the board stay at where i drop it after page refresh.
Here is what i've tried so far
const todos = document.querySelectorAll(".todo"); const all_status = document.querySelectorAll(".box") todos.forEach((todo) => { todo.addEventListener("dragstart", dragStart); todo.addEventListener("dragend", dragEnd); }); function dragStart() { draggableTodo = this; setTimeout(() => { this.style.display = "none"; }, 0); console.log("dragStart"); } function dragEnd() { draggableTodo = null; setTimeout(() => { this.style.display = "block"; }, 0); console.log("dragEnd"); } all_status.forEach((box) => { box.addEventListener("dragover", dragOver); box.addEventListener("dragenter", dragEnter); box.addEventListener("draleave", dragLeave); box.addEventListener("drop", dragDrop); }); function dragOver(e) { e.preventDefault(); //console.log("dragOver"); } function dragEnter() { console.log("dragEnter"); } function dragLeave() { console.log("dragLeave"); } function dragDrop() { this.appendChild(draggableTodo); var left = this.offsetLeft; var top = this.offsetTop; localStorage.setItem("left", left); localStorage.setItem("top", top); console.log("dropped"); }
Can check on my JSFiddle too
If there is only one element which you want to keep it's state, "left" and "top" is fine, but you would try to generate a key which defines the element.
localStorage.setItem("elementAPosition", {left: '10px', top: '5px'})
And when your scripts run at the first place, you can check element positions and set their place.
let elementAPos = localStorage.getItem("elementAPosition") //this returns an object with left and top keys.
elementA.style.left = elementAPos.left
elementA.style.top = elementAPos.top
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.