I'm wondering if/how I can store the position I moved the draggable div to on the table, so when the page reloads it will go back to where it left off (from the MySQL database).
I've read some related articles, but they were all about using jquery (events, ui) with AJAX.
This is my code:
var p = document.getElementsByTagName('p'); var choice = document.getElementsByClassName('choice'); var dragItem = null; for(var i of p){ i.addEventListener('dragstart', dragStart); i.addEventListener('dragend', dragEnd); } function dragStart(){ dragItem = this; setTimeout(()=>this.style.display = "none", 0); } function dragEnd(){ setTimeout(()=>this.style.display = "block", 0); dragItem = null; } for(j of choice){ j.addEventListener('dragover', dragOver); j.addEventListener('dragenter', dragEnter); j.addEventListener('dragleave', dragLeave); j.addEventListener('drop', Drop); } function Drop(){ this.append(dragItem); } function dragOver(e){ e.preventDefault(); this.style.border = "2px dotted cyan"; } function dragEnter(e){ e.preventDefault(); } function dragLeave(e){ this.style.border = "none"; }
section{ width: 1000px; height: 360px; margin: 100px auto; display: flex; justify-content: space-around; } h1{ text-align: center; } div{ width: 200px; height: 90%; padding: 20px; margin: 10px; background: #fafafa; box-sizing: border-box; } p{ font-weight: bold; border-radius: 5px; padding: 5px; color: white; background: red; } table, th, td { border:1px solid black; } button{ width: 100px; height: 15px; padding: 15px; margin: 10px; background: gray; box-sizing: border-box; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>test drag & drop </title> </head> <body> <h1> it's just a test for js </h1> <section> <div2> <table style="width:100%"> <tr> <th>time</th> <th>DIM</th> <th>LUN</th> </tr> <tr> <td>8:00 - 9:00</td> <td><div class="choice"></div> S1-1</td> <td><div class="choice"></div>S1-2</td> </tr> <tr> <td>9:00 - 10:00</td> <td><div class="choice"></div>S2-1</td> <td><div class="choice"></div>S2-2</td> </tr> </table> <button>save</button> </div2> <div class="choice"> <p draggable="true">MODULE 1</p> <p draggable="true">MODULE 2</p> <p draggable="true">MODULE 3</p> <p draggable="true">MODULE 4</p> <p draggable="true">MODULE 5</p> </div> </section> </body> </html>
This may be an overly complicated answer. But I think the best way is to store an array of
module
objects in JavaScript. Eachmodule
has aposition
property that needs to be updated every time the module is moved. You can also use thedata
html attribute to store the position of the element itself on the element (https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). This is my code:Javascript:
HTML:
To update the database, you can make a
write
database call every time you move a module. Then every time the page loads, just sort the array based on theposition
value. Hope this helps!