When drag starts (onDown
or
onClick
), you should actually
dynamically attach onUp
and onMove
events to document
instead of
handle. Just don't forget to clear
them onUp
.
However, there should be no difference
between <img>
and <div>
in this
case.
-- EDIT --
I stand corrected. Seems, there is slight difference in img and div handling in FF since FF3. It enables you to drag images to your computer, but we can get around it :).
Anyway, I have made some slight modifications to your script, cleaned it up a bit, and it should work now in all browsers. I have tested it on my computer with Firefox 3.5.5, Safari 4.0.3, Google Chrome, and Opera 10.1.
However, I don't have a way to test it on IE, so please report results.
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Page Title</title>
<script>
window.onload = function() { //After page is loaded this script will start automaticly
var divEl = document.getElementById("myDiv"); // Locate element with id "myDiv"
var imgEl = document.getElementById("myImg"); // Locate element with id "myImg"
divEl.onmousedown = onDown; // Assign funnction to event mousedown on "myDiv"
imgEl.onmousedown = onDown; // Assign funnction to event mousedown on "myImg"
function onDown(e) { // Mouse is down, long live the mouse :)
$el = this;
if (e.preventDefault) { e.preventDefault(e); } // This prevents default "drag image" behaivour
window.onmousemove = function(e) { // Assign function onmousemove to window
this.onmouseup = function(e) { // When we do a mouseup anywhere on window
window.onmousemove = undefined; // We clear onmouse from window
window.onmouseup = undefined; // We clear onmouseup from window
}
/* Part borowed from http://www.quirksmode.org/js/events_properties.html */
if (e.pageX) { posx = e.pageX; } // In case it is a normal browser
else if (e.clientX) { // In case it is IE
posx = e.clientX + document.body.scrollLeft+document.documentElement.scrollLeft;
}
/* End of borowed part */
$el.style.left = posx-parseInt($el.offsetWidth)/2+"px"; // Move this element to where mouse is
}
}
}
</script>
<style>
#myImg, #myDiv { display: block; position: relative; left: 0; width: 100px; height: 50px; }
#myImg { border: 1px solid red; }
#myDiv { border: 1px solid blue; background-color: lime;}
</style>
</head>
<body>
<img src="some_image.png" alt="my img" id="myImg">
<div id="myDiv">My div</div>
</body>
</html>
Ah, yes. CSS & JS in this example are in HTML only for testing purposes. In real code it is suggested you separate them to their own files.
Good luck :)