views:

377

answers:

3

Hei,

i want to allow a user to drag an image from a web page into my web app and then store and use the image url elsewhere in the application. So i'm creating an input field as the drag target.

But since that allows to drop any draggable web object (like links), i need to do some error checking. I could put a button there, but it would be nicer if the drop is auto-detected.

So the question is...are there any event handlers - primarily supported in IE7 and FF3 - that get triggered when the image is dropped? Does it simply trigger a change event on the field?

Thanks, Andre.

A: 

You won't get an standard event directly after drag-and-drop (only after clicking outside the textfield), but perhaps you can use some kind of DragListener...

To check if the URL is a valid image, it will be best to check the extension (JPG, PNG, GIF...) and to check if the URL begins with "file:" - if it does, it links to a local image file and you should ignore it.

schnaader
+1  A: 

No, to my knowledge, there are no events that'll fire as soon as you make the drop.

Here's a possible solution:

var input = document.getElementById("input");
var lastVal = input.value;

setInterval(function() {
  if (input.value !== lastVal) {
    if (input.value) {
      if ( /\.(jpe?g|gif|bmp|png)(\?.*)?$/.test(input.value) ){
        alert('It\'s an image URL!!!');
      } else {
        alert('Not an image URL...');
      }
    }
    lastVal = input.value;
  }
}, 100);

Demo here: http://jsbin.com/izake

Note: It appears that some browsers (IE) don't let you drop items into fields like other browsers. It may be worth creating one from scratch - where everything on the page is draggable...

J-P
Up-voted because that's pretty awesome =)
David Thomas
A: 

Hei guys,

thanks for those very helpful replies. Yes, i was inteding to check for the file: prefix as well.

J-P: Just awesome.

The whole point is really about dragging images from external sites into the field...my application already has a great dnd framework for internal stuff and an upload capacity for local images and all that, i just would like to make it easier for the users to use online images than by looking up and copy-pasting image urls.

If IE doesn't use fields as drag targets, i think i can still catch them in IE via it's proprietary onDrop event.

Andre.

PS: I'll come back and rate your answers as soon as my openid povider likes me again.