Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Pass class through drag and drop data transfer

I have an application that has multiple "widgets" that can be dragged and dropped onto the widget preview. Each widget has its own class and I am looking for a way to pass these classes into the drag and drop events.

Currently on the dragstart event I am passing the typeof the widget class and converting it to a string:

const addWidget = (widgetType) => {
    // widgetBox is the box dragged onto the widget preview to specify the user wants to create this widget
    const widgetBox = document.createElement("div");
    // style widgetBox
    
    widgetBox.addEventListener("dragstart", (e) => {
        e.dataTransfer.setData("widget-type", String(widgetType));
    })
}

addWidget(TextboxWidget); // TextboxWidget is a class

On the drop event in the widget preview I then get the widget type string and am forced to manually check for each widget, which is not ideal:

element.addEventListener("drop", () => {
    e.preventDefault();
    const widgetType = e.dataTransfer.getData("widget-type");

    switch(widgetType) {
        case String(TextboxWidget):
            widget = new TextboxWidget();
            break;
        // etc for each widget
        default:
            return;
    }
})

Ideally I would like to be able to pass the widget class to the drop event, and then be able to create an instance of it like so:

// dragover

const addWidget = (widget) => {
    const widgetBox = document.createElement("div");

    widgetBox.addEventListener("dragstart", (e) => {
        e.dataTransfer.setData("widget", widget);
    })
}

addWidget(TextboxWidget);

// drop
element.addEventListener("drop", () => {
    e.preventDefault();
    const WidgetClass = e.dataTransfer.getData("widget");
    const widgetInstance = new WidgetClass();
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!