Topic: Saving the order of cards after dragging

cloudbyte free asked 4 weeks ago


Users can reorder dashboard cards, but refreshing restores their original positions. I need to persist the new sequence by card ID.

Which event indicates sorting has finished?


Igor Przybysz staff answered 3 weeks ago


The visual rearrangement needs application-level persistence. Give each real card a stable ID, read those IDs in their final DOM order, save the sequence for that workspace, and render the next page in that sequence. Avoid storing screen coordinates or temporary drag placeholders as card positions.

Please share the plugin initialization and whether cards can move between containers. With that example, we can identify a suitable completion signal before adding persistence. A custom drag-completion handler can compare the previous and final ID arrays and save only when their order differs.

https://mdbootstrap.com/docs/standard/plugins/drag-and-drop/


cloudbyte free commented 3 weeks ago

For now I added a Save layout button that users click after dropping a card, so I can isolate persistence from drag events. There is only one grid. The cards move correctly, but the stored array always returns to the original ID order. This is the handler.

function saveLayout() {
  const ids = Array.from(grid.children, card => card.dataset.cardId);
  const order = ids.sort();
  localStorage.setItem('dashboardOrder', JSON.stringify(order));
}
saveButton.addEventListener('click', saveLayout);

Igor Przybysz staff commented 3 weeks ago

The sort() call replaces the visual order with ID order before you save it. For your save-button approach, read the settled card elements and store that sequence directly. JSON preserves array order. When restoring the layout, iterate the saved IDs in the same sequence rather than sorting them again.

function saveLayout() {
  const order = Array.from(grid.children)
    .filter(card => card.matches('[data-card-id]'))
    .map(card => card.dataset.cardId);
  localStorage.setItem('dashboardOrder', JSON.stringify(order));
}


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB Standard
  • MDB Version: MDB5 7.1.0
  • Device: Desktop
  • Browser: Firefox
  • OS: Windows 11
  • Provided sample code: No
  • Provided link: No