I have this code:
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var imageUrl = evt.dataTransfer.getData('URL');
alert(imageUrl);
}
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 http://i.stack.imgur.com/juvdV.jpg?s=32&g=1
to be alerted.
I want the solution to work on latest version of Chrome and Firefox.
Create drag-drop.js file and add following code.
Here you go: working example
It works on Chrome and Firefox, but note that if you drag an image from Chrome to Firefox it doesn't work.
I think that's working:
http://fiddle.jshell.net/4E92W/3/
Using jQuery. (I'm just using it to get the "src" attribute so i think you can do without it)
I replaced:
With:
Oh, and I replace the alert with a console.log so you'll need to open it.
Edit: It's not working with Firefox.
Edit2 : This one seems to work with both browser : http://fiddle.jshell.net/4E92W/5/
This problem can be solved using only Javascript.
Piece of Code:
JSFiddle Here: http://jsfiddle.net/hayatbiralem/7pr7N/5/
Thanks to kevinfahy for getAllElementsWithAttribute function.
Add an event listener to the window for the "drag" event. Set a global variable to the event source (I.E. The element in the page being dragged.) Then on "drop" you grab that the information you require from the element.
http://fiddle.jshell.net/exx4e/
Here's how I'd do it (only tested in Firefox):
.find()
.attr()
Here's the important part from my new drop(event) function:
Here's the working JSFiddle: http://fiddle.jshell.net/4r7dT/1/
And yes: You can drag-drop your user-icon into that box and will get the img url. ;)