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 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.
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.
Here's how I'd do it (only tested in Firefox):
.find()
.attr()
Here's the important part from my new drop(event) function:
// Get text/html instead of text/uri-list!
// So you get raw html that is passed even between different websites
var droppedHTML = evt.dataTransfer.getData("text/html");
// add this html to some container.
// if you skip this, the following code won't work if a single img element is dropped
var dropContext = $('<div>').append(droppedHTML);
// now you can read the img-url (not link-url!!) like this:
var imgURL = $(dropContext).find("img").attr('src');
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var imageUrl = evt.dataTransfer.getData('text/html');
var rex = /src="?([^"\s]+)"?\s*/;
var url, res;
url = rex.exec(imageUrl);
alert(url[1]);
}
It works on Chrome and Firefox, but note that if you drag an image from Chrome to Firefox it doesn't work.
Here is my fiddle: http://fiddle.jshell.net/ep2z5/
This works in chrome on my Mac. Basically you take the html returned, and then convert into jquery object, and since the return string is a meta tag, and an img tag, you have to take the 2nd element (number 1 in the array returned by jquery parsing) and jquery-ify that item, and then grab the src attribute.
Update: checked firefox and it isn't working there, researching now.
Update: Okay here is the newest fiddle tested in both chrome and firefox. http://fiddle.jshell.net/ep2z5/6/
It uses recursion, which can be dangerous, but i think will work okay, as long as there isn't to many nested elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With