Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect browser support File API drag n drop

I like to add a background on a div only for browsers which support drag & drop for files

I don't like to use modernizr though, just a one line script

like image 867
Xaver Avatar asked Feb 23 '23 18:02

Xaver


1 Answers

Why not just copy required parts from Modernizr?

var isEventSupported = (function() {

      var TAGNAMES = {
        'select': 'input', 'change': 'input',
        'submit': 'form', 'reset': 'form',
        'error': 'img', 'load': 'img', 'abort': 'img'
      };

      function isEventSupported( eventName, element ) {

        element = element || document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;

        // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
        var isSupported = eventName in element;

        if ( !isSupported ) {
          // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
          if ( !element.setAttribute ) {
            element = document.createElement('div');
          }
          if ( element.setAttribute && element.removeAttribute ) {
            element.setAttribute(eventName, '');
            isSupported = typeof element[eventName] == 'function';

            // If property was created, "remove it" (by setting value to `undefined`)
            if ( typeof element[eventName] != 'undefined' ) {
              element[eventName] = undefined;
            }
            element.removeAttribute(eventName);
          }
        }

        element = null;
        return isSupported;
      }
      return isEventSupported;
    })();

Usage:

if (isEventSupported('dragstart') && isEventSupported('drop')) {
  ...
}

And for File API:

var isFileAPIEnabled = function() {
  return !!window.FileReader;
};
like image 144
anton_byrna Avatar answered Feb 26 '23 08:02

anton_byrna