Drag and drop

With Fit.UI we can make Apps that support drag and drop using our mouse. In the follow examples we imagine an application that lets us move pictures from a folder to a picture box.
We start by making it possible for the user to move all pictures around using the mouse.

// Make all pictures within <div id="PictureFolder"> draggable

Fit.Array.ForEach(document.querySelectorAll("div#PictureFolder img"), function(picElm)
{
    var drg = new Fit.DragDrop.Draggable(picElm);

    drg.OnDragStart(function(elm)
    {
        console.log("Started dragging (mouse down)");
        elm.style.opacity = "0.5";
    });
    drg.OnDragging(function(elm)
    {
        console.log("Element being dragging around (mouse move)");
    });
    drg.OnDragStop(function(elm)
    {
        console.log("Element stopped being dragging (mouse up)");
        elm.style.opacity = "";
    });
});

The Fit.DragDrop.Draggable constructor takes a second handle argument (optional), if an element needs to be draggable only when a particular part of the element is being dragged (e.g. the title bar in a window/dialog).
To complete our drag and drop App, we turn our picture box into a DropZone.

// Turn <div id="#PictureBox"> into a dropzone (picture box) to which the user can move pictures.

var dz = new Fit.DragDrop.DropZone(document.querySelector("#PictureBox"));

dz.OnEnter(function(dropZone)
{
    console.log("User is holding picture above picture box");
    dropZone.GetDomElement().style.border = "2px solid red";
});
dz.OnDrop(function(dropZone, draggable)
{
    console.log("User dropped picture in picture box");
    dropZone.GetDomElement().style.border = "";

    // Move picture to picture box
    Fit.Dom.Add(dropZone.GetDomElement(), draggable.GetDomElement());
});
dz.OnLeave(function(dropZone)
{
    console.log("User moved picture away from picture box");
    dropZone.GetDomElement().style.border = "";
});
Fit.UI is open source (LGPL) - download or fork it on GitHub - website powered by Sitemagic CMS