Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feature detection for ability to drop file over HTML file input

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
});
like image 888
Danyal Aytekin Avatar asked Oct 26 '12 11:10

Danyal Aytekin


People also ask

What is the proper way to conduct feature detection?

Another good approach is to encapsulate feature detection into a set of functions that can then be used throughout the code. Here's a best practice for detecting whether the browser supports the HTML5 <canvas> element and if so, makes sure that the canvas. getContext('2d') method is working as well.

Which method checks whether the specific features get supported by the browser?

Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers.


1 Answers

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!
}
like image 176
joequincy Avatar answered Oct 25 '22 00:10

joequincy