SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard Wolf_22's Avatar
    Join Date
    Jul 2005
    Posts
    1,714
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Truncation based on element width...?

    I'm using the following function to truncate by character count:

    Code:
                function truncate(str, limit) {
                    var chars;
                    var i;
    
                    if ( typeof(str) != 'string') {
                        return '';
                    }
                    
                    chars = str.split('');
                    
                    if (chars.length > limit) {
                        for (i = chars.length - 1; i > -1; --i) {
                            if (i > limit) {
                                chars.length = i;
                            }else if (' ' === chars[i]) {
                                chars.length = i;
                                break;
                            }
                        }
                        chars.push('...');
                    }
                    return chars.join('');
                }
    I found this function in one of the Stack threads and was wondering if it might be possible to retrofit this to do the following:

    1.) Check if the second parm is a string. If it is, it's an element.
    2.) Check the width of the element and somehow calculate the amount of truncation being done based on it's width.

    I think it would boil down to performing a check to verify that it's a string first, but then after that, I'm not sure how character size plays a part nor am I sure how that should be manipulated in regards to the size of the element it's contained in. I'm thinking that you would take the width of the element and then the width of the text and I guess if the text either breaks or is bigger than the allotted width of the container, truncate the text?

    If someone could steer me in the right direction, it would be very appreciated.

  2. #2
    SitePoint Mentor silver trophy
    Rubble's Avatar
    Join Date
    Dec 2005
    Location
    Cambridge, England
    Posts
    2,435
    Mentioned
    82 Post(s)
    Tagged
    3 Thread(s)
    It is a bit longwinded but you could create an image from the text and get the size of that. The problem then becomes how much to shorten the text by but should work with all fonts.

    You could use a fixed pitch font which would make the calculations easier but you are then restricted by what fonts you could use.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •