Feature detection for ability to drop file over HTML file input
Asked Answered
S

1

8

Can we detect whether a browser supports dropping a file over an <input type="file" />?

For example, this is possible in Chrome but not in IE8.

Modernizr.draganddrop is a possibility but is it the right choice? I'm not adding any custom drag/drop event handlers.

Update

To verify Joe's answer here's a jQuery example that should stop the file drop. Verified in Chrome and Firefox.

$yourFileInput.on('drop', function() {
    return false; // if Joe's explanation was right, file will not be dropped
});
Sanctimony answered 26/10, 2012 at 11:50 Comment(6)
Why do you want to know?Supreme
I'm enhancing an area of the page to accept a file, which will then be uploaded (using iframe strategy by necessity). Transparent input receives file and then gets moved to a form and posted. I don't want to add the input for browsers which don't support the functionality.Sanctimony
Personally, I would add the input for every browser.Supreme
so you are trying to create an IE8-only fix for something that cannot be fixed in the other browsers? :-)Supreme
You could set the title to something that doesn't seem out-of-place.Supreme
Thanks for the suggestion. I may take that route if I can't feature detect, but I'm still interested in knowing if its possible.Sanctimony
F
2

I think the answer to Detecting support for a given JavaScript event? may help you. Adjusting the code to test against Input instead of Div, and testing for the "Drop" event seems to work fine for me.

Reproduced here so you don't have to click through (and adjusted slightly, since it seems you only need to detect this one feature):

function isEventSupported(eventName) {
  var el = document.createElement('input');
  eventName = 'on' + eventName;
  var isSupported = (eventName in el);
  if (!isSupported) {
    el.setAttribute(eventName, 'return;');
    isSupported = typeof el[eventName] == 'function';
  }
  el = null;
  return isSupported;
}
if(isEventSupported('drop')){
  //Browser supports dropping a file onto Input
} else {
  //Fall back, men!
}
Fowle answered 27/10, 2012 at 21:22 Comment(3)
This is a nice approach. Are you convinced that these browsers actually use the standard 'drop' event for files being dropped over the input, rather than something home-baked?Sanctimony
Great, I've confirmed that you're right, by returning 'false' from the drop event and observing that the drop doesn't work. Thanks Joe.Sanctimony
Always welcome! Also suggest upvoting the answer on the other page, because the approach belongs to @kangax and I only found it because of that post :)Fowle

© 2022 - 2024 — McMap. All rights reserved.