I created a function that rewrites file names according to the available space on screen:
@{
var index = 0;
foreach (var item in Model)
{
<div class="gallery-item">
<a href="@item.Uri" title="Click to open file" target="_blank" style="display:block; width: 100%;">
var id = "filename_" + ++index;
@Html.SpanFor(i => item.FileName, new { id = id, title = item.FileName, style = "white-space: nowrap;" })
</a>
</div>
}
}
@section Scripts
{
<script type="text/javascript">
function adaptWidth(span) {
var span = $(span);
var origfilename = span.text();
var ext = origfilename.split('.').pop();
var filename = origfilename.substr(0, origfilename.length - ext.length - 1);
var text = origfilename;
while (span.outerWidth() > span.parent().innerWidth()) {
span.text(text = (filename = filename.substr(0, filename.length - 4) + '...') + ext);
}
}
$(document).ready(function () {
$('span[id^=filename_]').each(function (i) { adaptWidth(this) });
});
</script>
}
Here are the results before and after running script:
Before:
After:
The function runs quite fast for now, but should I be worried from future impact? Any other suggestion or alternatives? Optimization?
I thought about splitting it to 3 spans, 1 for filename, second for ...
, and 3rd for the extension, but I don't really know how to make the overflow of the first be hidden under the other two. Besides, if a truncation isn't required, it's gonna look weird.