Search code examples
javascriptjqueryimageurldrag-and-drop

Drag and Drop: How to get the URL of image being dropped if image is a link (not the url of the link)


I have this code:

function drop(evt) {
    evt.stopPropagation();
    evt.preventDefault(); 
    var imageUrl = evt.dataTransfer.getData('URL');
    alert(imageUrl);
}

FIDDLE

If you drop the <img> element it alerts the url of the image. So far so good.

My problem is that if you drop the <a> element it alerts the url of the href of <a> element. I want to alert the url of the <img> element inside the <a> like if you droped the image in the above example.

Is that possible?

I dont mind using Jquery or any other library. I just want to take the url of the image inside a <a> element.

The whole point is to drag images-links from other websites to mine and get the url of images.

To be more clear what i am trying to achieve try to drag my profile image just under this post and drop it to fiddle. It alerts http://stackoverflow.com/users/3074592/laaposto. I want https://i.sstatic.net/juvdV.jpg?s=32&g=1 to be alerted.

I want the solution to work on latest version of Chrome and Firefox.


Solution

  • Using jQuery. (I'm just using it to get the "src" attribute so i think you can do without it)

    I replaced:

    var imageUrl = evt.dataTransfer.getData('URL');
    

    with:

    var imageUrl = evt.dataTransfer.getData('text/html');
    

    Oh, and I replace the alert with a console.log so you'll need to open it.