3

I'm trying to retrieve a url of an image dropped into a div. This is the code I use:

$('#dropzone')
    .bind('dragenter dragover', false)
    .bind('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
        alert(e.dataTransfer.getData('text'));
    });

Thing is, while it works great when dragging and dropping unlinked images (I get the src attribute of the img element), when I try to do this with images that they are links( <a href="..."><img src="..."></a>), I get the href attribute of the a element instead of the src attribute of the img element.

Any ideas?

I don't care about browser compatibility, I want to make it work in Firefox (or Chrome) only.

Edit: Here's how it looks like: http://jsfiddle.net/SPdHR/2/

(seems to be working only in Firefox by the way)

laaposto
  • 11,835
  • 15
  • 54
  • 71
Mike
  • 505
  • 5
  • 13

4 Answers4

1

You can try this:

$('#target')
    .bind( 'dragenter dragover', false)
    .bind( 'drop', function( e ) {
        e.stopPropagation();
        e.preventDefault();
        var imageUrl = e.dataTransfer.getData('text/html');
    if($(imageUrl).children().length > 0 ){
        var url = $(imageUrl).find('img').attr('src');
    }else{        
        var url = $(imageUrl).attr('src');
    }
        $('#result').html(url);
    });

It works both on Firefox and Chrome(latest versions)
See updated FIDDLE

laaposto
  • 11,835
  • 15
  • 54
  • 71
0

You should use after above code

 $('#dropzone')
.bind('dragenter dragover', false)
.bind('drop', function(e) {
    e.stopPropagation();
    e.preventDefault();

    var data = $(e.dataTransfer.getData('text/html'));
    var src = e.dataTransfer.getData("Text");
    var img = data.attr('src');   
    if (!img) {   
      var img = data.find("img").attr('src');

      alert(img);
});
0

My preferred method is to use a regular expression search of the dataTransfer text to find a string beginning with http:// and ending in " (but do not include the " in the result).

$('#dropzone')
.bind('dragenter dragover', false)
.bind('drop', function(e) {
    e.stopPropagation();
    e.preventDefault();
    if(e.dataTransfer.files.length>0){
        //Handle the local file
    }
    else{
       //Find the url embedded in the dataTransfer data
        var data = e.dataTransfer.getData("text/html");
        var matches = data.match(/http:\/\/.*(?=")/gi);
        var url = (matches || [false])[0]; //returns the url or false if no match found

        //Do whatever with the url
        console.log(url);
    }
});
Brooks
  • 2,082
  • 2
  • 18
  • 26
0

You should try:

$(e.target).find("img")
bluish
  • 26,356
  • 27
  • 122
  • 180
elrado
  • 4,960
  • 1
  • 17
  • 15