Wednesday, December 23, 2009

Javascript API - Creating draggable components

This API helps you perform Simple Drag and Drop using plain javascript.

The implementation of this API is quite easy though.

1. Make a js file containing the following javascript class
2. Include that to your HTML Page
3. In the onload event of the page put the following code,

var dragObj=new DraggableObject();

You can also put the above mentioned code in some button and perform the test.

parameter - id of the element you want to make draggable
- or name of the element you want to make draggable
- or the object reference of the element you want to make draggable

@Type : Class/Function
@Name : DraggableObject
@getter : getDebugFlag - To get the debugFlag value
@Setter : setDebugFlag(isDebugFlag)- To set the debugFlag value
@Property : makeDraggable(objectItem) - Property to make an object draggable
@Property : getMouseCoords(event) - To get the coordinates of mouse on screen
@Created : 23rd, Dec'09
@Author : Karthikeyan A

function DraggableObject() {
//private variables
var dragObject=null;
var mouseOffset = null;
var classRef=this;
var debugFlag=false;

//defining getters
this.getDebugFlag=function() {
return debugFlag;

//defining setters
this.setDebugFlag=function(isDebugFlag) {

//defining properties
this.makeDraggable = function(objectItem){
//if the objectItem subjected for drag is not an object,
//then check whether it is a name or an id and get the
// associated object. If every thing fails return an error
if (typeof objectItem!='object') {
if (typeof objectItem!='object') {
if (typeof objectItem!='object') {
throw new Error(objectItem + 'does not refer to a valid HTML Element');

objectItem.onmousedown = function(){
dragObject = this;

if (document.all) { //code fragment to go work in IE
var tmpX = event.clientX;
var tmpY = event.clientY;
} else { //code fragment to work in firefox, opera and safari
var tmpX = m.pageX;
var tmpY = m.pageY;

if (!document.body.scrollTop) { //code fragment to go work in IE
var iL = document.documentElement.scrollLeft;
var iV = document.documentElement.scrollTop;
} else { //code fragment to work in firefox, opera and safari
var iL = document.body.scrollLeft;
var iV = document.body.scrollTop;
return {x: tmpX + iL, y: tmpY + iV};

// methods for internal usage
function init(){
document.onmousemove = mousemove;
document.onmouseup = mouseUp;

function mouseUp(ev){
dragObject = null;

function mousemove(event) {
if (dragObject==null) return;
var xy=classRef.getMouseCoords(event); = 'absolute'; = xy.y; = xy.x;

No comments:

Post a Comment