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> <img src="Desert.jpg"></img> </div>
</body>and this code is working..
<body onload="init();"> <div> <div></div> </div>
</body> 7 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.
1<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">XHTML (note the / at the end of the tag)
<img src="Desert.jpg" /> 1