function newXmlHttp() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Msxml2.XMLHttp");
}
return null;
}
Friday, December 02, 2005
JavaScript XmlHttp
javascript Drag
It turns out not that difficult to implement your own drag and drop. Below is a very lightweight and customizable web Drag&Drop support using javascript and dhtml. Supports both IE and Firefox.
<script type="text/javascript">
function getEvent(e) {
return e ? e : window.event;
}
function moveElem(elem, left, top) {
var style = elem.style;
style.left = left;
style.top = top;
}
function Drag(elem) {
var self = this;
this.elem = elem;
elem.onmousedown = function(e) {
e = getEvent(e);
self.onBeginDrag(e.clientX, e.clientY);
saveLast(e.clientX, e.clientY);
document.onmousemove = onmousemove;
document.onmouseup = onmouseup;
return false;
}
function onmousemove(e) {
e = getEvent(e);
self.onDrag(e.clientX, e.clientY);
saveLast(e.clientX, e.clientY);
return false;
}
function onmouseup(e) {
e = getEvent(e);
document.onmousemove = null;
document.onmouseup = null;
self.onEndDrag(e.clientX, e.clientY);
return false;
}
function saveLast(x, y) {
self.x0 = x;
self.y0 = y;
}
}
Drag.prototype.move = function(dx, dy) {
var style = this.elem.style;
var x = parseInt(style.left);
var y = parseInt(style.top);
style.left = x + dx;
style.top = y + dy;
}
Drag.prototype.moveTo = function(x, y) {
moveElem(this.elem, x, y);
}
Drag.prototype.drag = function(x, y) {
this.move(x - this.x0, y - this.y0);
}
Drag.prototype.onDrag = function(x, y) {
this.drag(x, y);
}
Drag.prototype.onBeginDrag = function(x, y) {}
Drag.prototype.onEndDrag = function(x, y) {}
</script>
To make an element draggable, simply call "new Drag(elem)" for the element, e.g.,
<img id="dragimg" src="...">
<script type="text/javascript">
new Drag(document.getElementById("dragimg"));
</script>