HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Rewriting file names according to the available screen space

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filetheavailablespacenamesrewritingscreenaccording

Problem

I created a function that rewrites file names according to the available space on screen:

@{
  var index = 0;
  foreach (var item in Model)
  {
  
              
        var id = "filename_" + ++index;
        @Html.SpanFor(i => item.FileName, new { id = id, title = item.FileName, style = "white-space: nowrap;" })          
    
  
  }
}

@section Scripts
{
  
    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) });
    });
  
}


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.

Solution

In general case I would to get text_width and container_width, then calculate new_string_length=container_width/text_width*length, than setup increase or decrease text, depending on result_text_width > container_width and do the loop like yours.

This is really needed only if strings have a very big size.

Context

StackExchange Code Review Q#19913, answer score: 4

Revisions (0)

No revisions yet.