How to Make a Draggable Image in Div?
I Am Trying to Move a Image in a Div Like a Facebook Cover Page, but It Is Not Moving Smoothly with Image Tag. When I Put This Image in a Div Like a Background...
I am trying to move a image in a div like a facebook cover page, but it is not moving smoothly with image tag . when I put this image in a div like a background image it is working my js code is ..
var draggable = function(element) {
element.addEventListener('mousedown', function(e) {
e.stopPropagation();
if (e.target != element)
return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
function move(e) {
var ele = document.getElementById('ele');
var width = 400-ele.clientWidth;
var height = 400-ele.clientHeight;
element.style.left = (e.pageX - offsetX) + 'px';
element.style.top = (e.pageY - offsetY) + 'px';
}
function stop(e) {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', stop);
});
}
function init() {
var ele = document.getElementById('ele');
draggable(ele);
}
and my html code which is not working is..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<img src="Desert.jpg" id="ele" style="position:absolute;"></img>
</div>
</body>
and this code is working..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<div id="ele" style="width:100%; height:100%; background-color: gray; position:absolute; background-image:url( 'Desert.jpg' );"></div>
</div>
</body>
2 Answers
You could refer to this question, which handles the same idea of dragging images, althought the question is slightly different. Check out his/her JSFiddle from question.
<img> is a self-closing tag. You don't need the </img> as it's not valid. Remove that and it should work fine. Depending on your doctype you should use:
HTML5
<img src="Desert.jpg" id="ele" style="position:absolute;">
XHTML (note the / at the end of the tag)
<img src="Desert.jpg" id="ele" style="position:absolute;" />