SVG drag-and-drop: more features, organized, and up on GitHub

Today I did some organizing and refactoring on my SVG drag-and-drop framework. It now supports picking up any of multiple children, and is sorted nicely into class files that it ‘imports’ right before use. As far as I can tell my solution differs a little bit from others around the web in that it represents the children and parents as Javascript objects, encapsulating the movement logic inside. I believe it would be more reusable since there’s very little code in the top-level Javascript that actually knows about the SVG document.

Here’s the script that’s specific to this example:

//Import the classes we need
importClass("scripts/svg_lib.js");
importClass("scripts/svg_movable_parent.js");
importClass("scripts/svg_movable_child.js");
//Instantiate and link all the objects
window.onload = function () {
 //define the object that can be dragged
 var myTriangle = document.getElementById("myTriangle");
 //secondary element that can be dragged
 var myTriangle2 = document.getElementById("myTriangle2");
 //specify the region in which dragging should work well
 var myParent = document.getElementById("svgHost");

 var movableParent = new com.SVG.MovableParent;
 var movableTriangle = new com.SVG.MovableChild;
 var movableTriangle2 = new com.SVG.MovableChild;

 movableParent.Initalize(myParent);
 movableTriangle.Initialize(myTriangle, movableParent);
 movableTriangle2.Initialize(myTriangle2, movableParent);

 movableParent.AddChild(movableTriangle);
 movableParent.AddChild(movableTriangle2);
};

Everything else is hidden away inside the svg framework classes. All of the code is up on GitHub, and you can play with the demo itself here.

Leave a Reply