Web-Components


Posts

blog Drag and Drop and Django

I wanted to have some drag and drop web components that I could use with my django apps. I am planning on using them in another of my many todo/scheduling prototypes. Basing heavily on the api docs for drag and drop, I start with some basic components.

I start with my <drag-source> component that I will use to wrap anything I want draggable.

class DragSource extends HTMLElement {
  constructor() {
    super();
    // I use a random ID here to make something quick/simple but in a real version
    // I should probably only set this if not already set.
    this.id = Math.random();
  }

  dragStart(e) {
    e.dataTransfer.setData("text/plain", e.target.id);
    e.dataTransfer.dropEffect = "move";
    setTimeout(() => {
      e.target.classList.add("hide");
    }, 0);
  }

  dragEnd(e) {
    e.target.classList.remove("hide");
  }

  connectedCallback() {
    this.addEventListener("dragstart", this.dragStart);
    this.addEventListener("dragend", this.dragEnd);
  }
}
customElements.define("drag-source", DragSource);

Next, I create a container that I will use to drop onto.

Read More →