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 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>
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.

Check it out here!

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" id="ele" style="position:absolute;">

XHTML (note the / at the end of the tag)

<img src="Desert.jpg" id="ele" style="position:absolute;" />
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest