idealfile.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. if (isIE) $label.add($button).addClass('ie');
  20. // Hide by shifting to the left so we
  21. // can still trigger events
  22. $file.css({
  23. position: 'absolute',
  24. left: '-9999px'
  25. });
  26. $wrap.append($input, (isIE ? $label : $button)).insertAfter($file);
  27. // Prevent focus
  28. $file.attr('tabIndex', -1);
  29. $button.attr('tabIndex', -1);
  30. $button.click(function () {
  31. $file.focus().click(); // Open dialog
  32. });
  33. $file.change(function () {
  34. var files = []
  35. , fileArr, filename;
  36. // If multiple is supported then extract
  37. // all filenames from the file array
  38. if (multipleSupport) {
  39. fileArr = $file[0].files;
  40. for (var i = 0, len = fileArr.length; i < len; i++) {
  41. files.push(fileArr[i].name);
  42. }
  43. filename = files.join(', ');
  44. // If not supported then just take the value
  45. // and remove the path to just show the filename
  46. } else {
  47. filename = $file.val().split('\\').pop();
  48. }
  49. $input .val(filename).attr('title', filename);
  50. });
  51. $input.on({
  52. blur: function () {
  53. $file.trigger('blur');
  54. },
  55. keydown: function (e) {
  56. if (e.which === 13) { // Enter
  57. if (!isIE) $file.trigger('click');
  58. $(this).closest('form').one('keydown', function(e) {
  59. if (e.which === 13) e.preventDefault();
  60. });
  61. } else if (e.which === 8 || e.which === 46) { // Backspace & Del
  62. // In IE the value is read-only
  63. // with this trick we remove the old input and add
  64. // a clean clone with all the original events attached
  65. if (isIE) $file.replaceWith($file = $file.clone(true));
  66. $file.val('').trigger('change');
  67. $input.val('');
  68. } else if (e.which === 9) { // TAB
  69. return;
  70. } else { // All other keys
  71. return false;
  72. }
  73. }
  74. });
  75. }
  76. };
  77. require('../../plugin')(plugin);
  78. }(jQuery, window, document));