Here is example code for drag and drop
<html>
<head>
<title>Drag and Drop Example </title>
<script type="text/javascript" src="EventUtil.js"> </script>
</head>
<body>
<div id="myDiv1" class="draggable" style="background:red;width:100px;height:100px;position:absolute"></div>
<div id="myDiv2" class="draggable" style="background:blue;width:100px;height:100px;position:absolute;left:100px"> </div> <div id="myDiv3" class="draggable" style="background:green;width:100px;height:100px;position:absolute;left:200px"> </div>
<div id="myDiv4" class="draggable" style="background:yellow;width:100px;height:100px;position:absolute;left:300px"></div>
<script type="text/javascript">
var DragDrop = function(){
var dragging = null;
function handleEvent(event){
//get event and target
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
//alert(" target "+ target);
//determine the type of event
switch(event.type){
case "mousedown":
if (target.className.indexOf("draggable") > -1){
dragging = target;
}
break;
case "mousemove":
if (dragging !== null){
//get event
event = EventUtil.getEvent(event);
//assign location
dragging.style.left = event.clientX + "px";
dragging.style.top = event.clientY + "px";
}
break;
case "mouseup":
dragging = null;
break;
}
};
//public interface
return {
enable: function(){
EventUtil.addHandler(document, "mousedown", handleEvent);
EventUtil.addHandler(document, "mousemove", handleEvent);
EventUtil.addHandler(document, "mouseup", handleEvent);
},
disable: function(){
EventUtil.removeHandler(document, "mousedown", handleEvent);
EventUtil.removeHandler(document, "mousemove", handleEvent);
EventUtil.removeHandler(document, "mouseup", handleEvent);
}
}
}();
DragDrop.enable();
</script>
</body>
</html>
Here at two methods DragDrop:enable() and disable(), is used which provides additional attach and detach all events , and provide addtional measure of control over the dragdrop functionality
here to start DragDrop for an object enable function has to be called , which in turn call EventUtil.addHandler , after which if any move event occurs [mouseup, mousedown,mousemove] in that page means it is captured in handleEvent
In handle event if mousedown is clicked over an div with the class draggable and moved means , X
In this example, an element ’ s left and top coordinates are set equal to the event object ’ s clientX and clientY proper ties, which places the element at the cursor ’ s position in the viewport. The effect is an element that follows the cursor around the page whenever it ’ s moved. that is how DragDrop works
when mouse is released dragging variable is cleared, for implementing DragDrop functionality the object should be in the absolute position
ps: source: Wrox Professional JavaScriptTM for Web Developers
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment