idealfile.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * Ideal File
  3. */
  4. (function($, win, doc, undefined) {
  5. // Browser supports HTML5 multiple file?
  6. var multipleSupport = typeof $('<input/>')[0].multiple !== 'undefined'
  7. , isIE = /msie/i.test(navigator.userAgent)
  8. , plugin = {};
  9. plugin.name = 'idealfile';
  10. plugin.methods = {
  11. _init: function() {
  12. var $file = $(this.el).addClass('ideal-file') // the original file input
  13. , $wrap = $('<div class="ideal-file-wrap">')
  14. , $input = $('<input type="text" class="ideal-file-filename" />')
  15. // Button that will be used in non-IE browsers
  16. , $button = $('<button type="button" class="ideal-file-upload">Open</button>')
  17. // Hack for IE
  18. , $label = $('<label class="ideal-file-upload" for="' + $file[0].id + '">Open</label>');
  19. // Hide by shifting to the left so we
  20. // can still trigger events
  21. $file.css({
  22. position: 'absolute',
  23. left: '-9999px'
  24. });
  25. $wrap.append($input, (isIE ? $label : $button)).insertAfter($file);
  26. // Prevent focus
  27. $file.attr('tabIndex', -1);
  28. $button.attr('tabIndex', -1);
  29. $button.click(function () {
  30. $file.focus().click(); // Open dialog
  31. });
  32. $file.change(function () {
  33. var files = []
  34. , fileArr, filename;
  35. // If multiple is supported then extract
  36. // all filenames from the file array
  37. if (multipleSupport) {
  38. fileArr = $file[0].files;
  39. for (var i = 0, len = fileArr.length; i < len; i++) {
  40. files.push(fileArr[i].name);
  41. }
  42. filename = files.join(', ');
  43. // If not supported then just take the value
  44. // and remove the path to just show the filename
  45. } else {
  46. filename = $file.val().split('\\').pop();
  47. }
  48. $input .val(filename).attr('title', filename);
  49. });
  50. $input.on({
  51. blur: function () {
  52. $file.trigger('blur');
  53. },
  54. keydown: function (e) {
  55. if (e.which === 13) { // Enter
  56. if (!isIE) $file.trigger('click');
  57. $(this).closest('form').one('keydown', function(e) {
  58. if (e.which === 13) e.preventDefault();
  59. });
  60. } else if (e.which === 8 || e.which === 46) { // Backspace & Del
  61. // In IE the value is read-only
  62. // with this trick we remove the old input and add
  63. // a clean clone with all the original events attached
  64. if (isIE) $file.replaceWith($file = $file.clone(true));
  65. $file.val('').trigger('change');
  66. $input.val('');
  67. } else if (e.which === 9) { // TAB
  68. return;
  69. } else { // All other keys
  70. return false;
  71. }
  72. }
  73. });
  74. }
  75. };
  76. require('../../plugin')(plugin);
  77. }(jQuery, window, document));