Topic: Drag and drop API Dynamic

Timo Werkhoven free asked 2 years ago


Expected behavior I create a few li elements from received data from a JSON file. I want these list items to be draggable inside the ul.

Actual behavior I've got a JSON file that contains data, later this should fetch data from an external json file. This data gets return to the variable data in my Javascript file. When the page gets loaded the function that can be found at the bottom of this message gets called. I've got a sortable-list and the created li elements from the received data should be added to this list. This all works perfectly, however because the li elements dont get a unique data-mdb-id for the drag & drop api, the dragging and dropping part doesn't work. Is there anyway i can give these elements the data-mdb-id after creating the elements?

Resources shots, code snippets etc.)

let formFieldArea = document.querySelector('#formFieldArea');

window.addEventListener('load', async () => {
await fetchData();
let fetchedData = await data.value[0];
let formFields = await fetchedData.formFields;
for(i = 0; i < formFields.length; i++){
    latestItemData = await formFields[i].type;
    let inputfield = formFieldArea;
    let li = document.createElement('li');
    li.dataset.type =  formFields[i].type;
    li.className = `p-3 border border-dark sortable-item formField ${li.dataset.type}`;
    li.style = "transition: none 0s ease 0s; transform: translate3d(0px, 0px, 0px);"
    inputfield.insertAdjacentElement('beforeend', li);
    }
});

async function fetchData() {
    let res = await fetch('/static/json/test.json');
    data = await res.json();
    return data;
}

Kamila Pieńkowska staff answered 2 years ago


There are to ways to initiate components. With html of with js. In your example you should initiate sortable with js after you add all your elements from JSON file. I've created simplified example how to add DOM elements with js and then initiate Drag and drop. https://mdbootstrap.com/snippets/standard/kpienkowska/4047458



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 4.1.0
  • Device: Laptop (Razer blade 15)
  • Browser: Firefox
  • OS: Windows
  • Provided sample code: No
  • Provided link: No