Created
December 27, 2013 06:28
-
-
Save raiden-dev/8143369 to your computer and use it in GitHub Desktop.
Cut the filenames pretty way
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
<!doctype html> | |
<html> | |
<head> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> | |
<style> | |
.filename { width: 150px; margin: 5px 10px; padding: 5px 10px; border:1px solid #000; overflow: hidden; } | |
</style> | |
</head> | |
<body> | |
<div class="filename" title="NewOfficeDocument_26.12.2013.docx">NewOfficeDocument_26.12.2013.docx</div> | |
<script> | |
/** | |
* Cut the filenames pretty way | |
* | |
* @param {String} options.delimiter Delimiter between filename and extension | |
* @param {Boolean} options.split Pick out filename, delimiter and extension to separate tags | |
* @param {String} options.filenameClass Class for filename tag | |
* @param {String} options.delimiterClass Class for delimiter tag | |
* @param {String} options.extensionClass Class for extension tag | |
*/ | |
$.fn.filename = function(options) { | |
var options = options || {}; | |
return this.each(function() { | |
var $el = $(this); | |
setTimeout(function() { | |
var $wrapper = $('<span style="white-space:nowrap"/>') | |
, $filename = $('<span/>').addClass(options.filenameClass) | |
, $delimiter = $('<span/>').addClass(options.delimiterClass) | |
, $extension = $('<span/>').addClass(options.extensionClass) | |
, containerWidth = $el.width() | |
, filename = $el.text() | |
, extension = filename.match(/\.[0-9a-z]+$/i)[0] | |
, delimiter = options.delimiter || '\u2026 '; | |
filename = filename.replace(extension, ''); | |
$wrapper | |
.append( $filename.text(filename) ) | |
.append( $delimiter.text(delimiter).hide() ) | |
.append( $extension.text(extension) ) | |
$el.html($wrapper); | |
if ($wrapper.outerWidth() > containerWidth) { | |
$delimiter.show(); | |
while ($wrapper.outerWidth() > containerWidth) { | |
filename = filename.substr(0, filename.length-1); | |
$filename.text(filename); | |
} | |
} | |
if (options.split) { | |
$wrapper.children().unwrap(); | |
} | |
else { | |
$el.text($wrapper.children().filter(':visible').text()); | |
} | |
}, 0); | |
}); | |
}; | |
$(function() { | |
$('.filename').filename({ | |
split: true, | |
filenameClass: 'filename__file', | |
delimiterClass: 'delimiter__file', | |
extensionClass: 'extension__file' | |
}); | |
$('.filename').filename(); // will just unwrap, nothing more to do | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment