Created
July 5, 2012 03:57
-
-
Save elclanrs/3051209 to your computer and use it in GitHub Desktop.
toCustomFile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.toCustomFile = function () { | |
return this.each(function () { | |
var | |
$file = $(this), // The file input | |
// Necessary markup | |
$wrap = $('<div class="wrap">'), | |
$input = $('<input type="text" class="filename" />'), | |
$button = $('<button type="button" class="upload">Open</button>') | |
// Hide by shifting to the left, that way can | |
// still use events that are otherwise problematic | |
// if the field is hidden as in "display: none" | |
$file.css({ | |
position: 'absolute', | |
left: '-9999px' | |
}) | |
// Events | |
$button | |
.attr('tabIndex', -1) // disable focus on button for better usability | |
.click(function () { | |
$file.trigger('click') // Yes, `click`, not `change`. Crossbrowser compat. | |
}) | |
$file | |
.attr('tabIndex', -1) | |
.on({ | |
change: function () { | |
// Detect if browser supports HTML5 "file multiple" | |
var multipleSupport = typeof $('input')[0].multiple !== 'undefined', | |
files = [], | |
fileArr, | |
filename | |
if (multipleSupport) { | |
fileArr = $file[0].files | |
for (var i = 0, len = fileArr.length; i < len; i++) | |
files.push(fileArr[i].name) | |
filename = files.join(', ') | |
} else { | |
filename = $file.val().split('\\').pop() // Remove fakepath | |
} | |
$input.val(filename) | |
// Set filename as title tooltip on | |
// input field for better usability | |
$input.attr('title', filename) | |
}, | |
focus: function () { | |
$input.trigger('focus') | |
} | |
}) | |
$input | |
.on({ | |
keyup: function () { $file.trigger('change') }, | |
focus: function () { $file.trigger('change') }, | |
blur: function () { $file.trigger('blur') }, | |
// Open files when pressing [ENTER] | |
// on the input field | |
keydown: function (e) { if (e.which === 13) $file.trigger('click') } | |
}) | |
// Append to DOM | |
$wrap.append($button, $input).insertAfter($file) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment