Reputation: 73
I found a post from awhile back that was very useful for something I'm working on. I need the functionality of dragging and dropping an object (an image in my case) wherever I want, and then dropping it wherever I want without changing the content around it.
However, I can't seem to get it to work with a simple image rather than a code block. I'm sure it's an easy fix and I'm just overlooking something, but I'd appreciate the help.
This example is perfect from the aforementioned SO post: http://jsfiddle.net/robertc/kKuqH/ (this is with a code block, but I want an image instead)
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('dragme');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
var dm = document.getElementById('dragme');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
Upvotes: 3
Views: 1283
Reputation: 149
Make the image the background image of the div. Change your CSS to something like this:
aside {
position: absolute;
left: 0;
top: 0; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
width: 200px;
height: 200px;
background: rgba(255,255,255,0.66);
border: 2px solid rgba(0,0,0,0.5);
border-radius: 4px; padding: 8px;
background-image: url('http://lorempixel.com/200/200/');
background-repeat: no-repeat;
background-position: center;
}
Upvotes: 1