Drag and Drop: How to get the URL of image being dropped if image is a link (not the url of the link)
For that question: http://stackoverflow.com/questions/21143504/drag-and-drop-how-to-get-the-url-of-image-being-dropped-if-image-is-a-link-not
by Ömür Yanıkoğlu
HTML
<div id="dropbox">Drop an Image....</div>
<img src="http://el.camping.info/style/img/icon-thumb-50.png"/>
<p>IMAGE</p>
<a href="http://stackoverflow.com" target="_blank">
<div id="some_more_elements">
<img src="http://static2.businessinsider.com/image/4cc300a1ccd1d55f7e2b0000-50-sq/image.jpg"/>
</div>
</a>
<p>IMAGE WITH LINK TO SO</p>
CSS
#dropbox {
border: 3px dashed black;
width: 200px;
height: 100px;
}
img{
padding:20px;
display:inline;
}
p{
display:inline;
margin-left:-76px;
}
#some_more_elements{
display:inline;
}
JavaScript
// Thanks to kevinfahy:
// http://stackoverflow.com/a/9496574/1227926
function getAllElementsWith(tag, attribute, value)
{
var matchingElements = [];
var allElements = document.getElementsByTagName(tag);
for (var i = 0; i < allElements.length; i++)
{
if (value.indexOf(allElements[i].getAttribute(attribute)) != -1)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
// onDrop
function onDrop(evt) {
evt.stopPropagation();
evt.preventDefault();
var imageUrl = evt.dataTransfer.getData("URL");
var links = getAllElementsWith("a", "href", imageUrl);
var image;
// console.log(links, evt);
if(links.length){
image = links[0].getElementsByTagName("img");
if(image.length)
imageUrl = image[0].getAttribute("src");
else
imageUrl = "#no-image";
}
alert(imageUrl);
};
// onDragOver
function onDragOver(evt){
evt.preventDefault();
}
var dropbox = document.getElementById('dropbox');
dropbox.addEventListener('drop', onDrop);
dropbox.addEventListener("dragover", onDragOver, false);