Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question How can I truncate all words greater than 30 characters when page loads?

    How can I truncate all words greater than 30 characters using a class name when the page loads?

    Been trying to do this for about 5 hours. Trying to conside the following:

    * Truncate long words and churn anything above the minimum length with an ellipse.
    * Only truncate words and not the whole sentence or paragraph.
    * Should truncate text that are inside HTML tags and not truncate the tags themselves.
    * When you hover over the ellipse, it will show you the complete word.
    * The long words are already truncated when the page load (SEO friendly).
    * Block of text are included in a max of 25 <div> elements and a minimum of 1. That's why I'm not using ID.

    So far I have this lines of code:

    Code:
    <script charset="utf-8" language="javascript" type="text/javascript">
    function test(gaz) {
    		var sbText = gaz.innerHTML;
    		var sbTextArr = sbText.split(' ');
    		var tempText = "";
    		for (var s=0; s<sbTextArr.length; s++) {
    			if (sbTextArr[s].length > 30) { sbTextArr[s] = "marco"; }
    			gaz.innerHTML = "";
    			tempText = tempText + " " + sbTextArr[s];
    			gaz.innerHTML = tempText;
    			}
    	}</script>
    
    <div class="myClass" onmouseover="test(this);"><p>This is a <strong>looooooooooooooo</strong><em>ooooooooooooooooooooooooooooooong</em> word.</p></div>
    <div class="myClass" onmouseover="test(this);">A text without long word.</div>
    <div class="anotherClass"><p>Another set</p><p>But should not affect if there's a loooooooooooooooooong word.</p></div>
    I got this from the web and modified it but not working as I intended it to be.

    Useful for posts in forums, blog comments, and guestbooks

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    I do not see the point of trying to truncate words of more than 30 characters. The longest English word is supposed to be antidisestablishmentarianism - 26 letters. It would be very difficult to truncate any text with mark-up in it as you have. Why not simply truncate the whole text at a certain number of characters?


    Example:-

    Code:
    <body onload = "showstart()"> 
    <div id = "mydiv"></div>
    
    <script type = "text/javascript">
    
    var txt = "";
    var shorttxt = "";
    function showstart() {
    txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor. "
    shorttxt = txt.substring(0,100);
    document.getElementById("mydiv").innerHTML = shorttxt + "<font color = '#0000FF' size = '1'><a = '#' onclick='showmore();return false'>.....read more</a>";
    }
    
    function showmore() {
    document.getElementById("mydiv").innerHTML = document.getElementById("mydiv").innerHTML = txt + "<font color = '#0000FF' size = '1'><a = '#' onclick='showless();return false'>.....read less</a>";txt;
    }
    
    function showless() {
    document.getElementById("mydiv").innerHTML = shorttxt + "<font color = '#0000FF' size = '1'><a = '#' onclick='showmore();return false'>.....read more</a>";
    }
    
    </script>
    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
    Last edited by Philip M; 12-23-2010 at 08:29 PM.

  • #3
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Hey Philip just an Idea, would this work?

    Strip all the html tags and double spaces so something like this.
    Code:
    <span class="demo">hello    world</span>
    Would turn into this.
    Code:
    hello world
    And then set that string as a variable for usage in the function and then split it up by the spaces and then check the length of each array item, once it finds a word longer than 30 chars it will shorten it and replace the old long word with the new shorten word.

    May not work but worth thinking of as it might work. Also do agree with you with shortening the full string with the html tags in it but what if the string gets shorten down and a string like this hello <sup>world</sup> get shorten down and then returns hello <sup>world</s the </s would also be displayed so wouldn't it be best to try and stop this happening.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    I think it would be very difficult indeed to deal with HTML tags as you suggest. In any case, it see it as another fundamentally flawed idea.

    If there are mark-up tags e.g.
    txt = "Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit. Etiam </strong>ipsum leo, scelerisque
    then either you count the tags as part of the string length, or you remove them with a regex. I don't see how it is possible to do both.

    You could count the characters between HTML tags and add that number to the truncated text - but as I see it it is impossible to detect whether the tags are before or after the revised length (and the truncate cut-off might fall within a tag).

    Code:
    var txt = "";
    var shorttxt = "";
    function showstart() {
    txt = "Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit. Etiam ipsum leo</strong>, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor. "
    
    var len = txt.length;
    alert (len);  // 869
    var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;  
    var trunclen = txt.replace(regexp,"").length; 
    alert (trunclen);  // 852
    
    var x = 100 + (len-trunclen);
    shorttxt = txt.substring(0, x);

  • #5
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Good idea Philip I always find it best to have no tags on a shorten string so like you did was you took them out and when you click read more the full text would be styled then with the strong tag etc.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #6
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    A thought just came to me, WHY use javascript for this????

    Why not just use css? so much more simple and also keeps the html styles on the text.

    EXAMPLE:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
      <title>Untitled Document</title>
      <style type="text/css">
      .demo {
        width: 130px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      </style>
    </head>
    <body>
      <div class="demo">Hello World</div>
      <div class="demo">Lorem ipsum dolor sit amet, <strong>consectetur adipiscing elit. Etiam ipsum leo</strong>, scelerisque at dapibus ac, consectetur vel ipsum. Morbi et metus ut diam molestie ullamcorper. Suspendisse rutrum semper semper. Donec volutpat neque in lorem tempus scelerisque. Curabitur dignissim rhoncus quam ac suscipit. Donec viverra quam lobortis neque porta a sagittis urna tristique. Suspendisse nec lacus nisi. Pellentesque fermentum massa sit amet magna hendrerit vestibulum. Sed elit libero, scelerisque eu eleifend ut, interdum gravida nunc. Etiam ut nisi sapien, et tempus sem. Nam vel mi est. Mauris congue felis ut ante bibendum vehicula. Nullam nec sapien arcu, eget cursus lorem. Donec blandit, dolor tristique ornare dictum, arcu sapien vulputate dolor, et placerat risus odio ut magna. Ut magna mauris, pellentesque at ultricies vitae, fermentum vitae dolor.</div>
      <div class="demo">Hello World Again!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</div>
    </body>
    </html>
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by DJCMBear View Post
    All codes written by me have been 100% tested.
    Not this one!

  • #8
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Quote Originally Posted by Philip M View Post
    Not this one!

    Well it works on my website so it must be your server/computer.

    Also try adding white-space: no-wrap; to the demo class CSS this will stop the text from wrapping to a new line.
    Last edited by DJCMBear; 12-24-2010 at 02:09 PM.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,918
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Well, what I get in IE8 is

    Hello World
    Lorem ipsum dolor
    sit amet,
    consectetur
    adipiscing elit.
    Etiam ipsum leo,
    scelerisque at
    dapibus ac,
    consectetur vel
    ipsum. Morbi et
    metus ut diam
    molestie
    //.......
    Hello World
    Again!!!!!!!!!!!!!!!...

  • #10
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    C'mon IE messes up on everything lol!!
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #11
    New to the CF scene
    Join Date
    Dec 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Arrow

    Quote Originally Posted by Philip M View Post
    I do not see the point of trying to truncate words of more than 30 characters. The longest English word is supposed to be antidisestablishmentarianism - 26 letters. It would be very difficult to truncate any text with mark-up in it as you have. Why not simply truncate the whole text at a certain number of characters?
    Okay, then maybe 25. I want to truncate words because some people add lengthy characters creating horizontal scrollbar to appear and messing up the pages. Such are these examples:

    I loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooveeeeeeeeeeeeeeeeeeeeeeeeeeeeeee eeee Emma Watson!
    Shut Up!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!
    Or sometimes forgot to addspacestowordsandcopyandpastedthemwrongcreatinglongcharacters.
    Or when a period comesafteralong.wordsuchasthiscreatinghorizontalbarstoappear.
    Or when they post long URLs such as http://www.codingforums.com/newreply...eply&p=1031430 (but they can be remedied easily so the lengthy words are more of my concern).


    EDIT: I'm new here so I'm not sure why. Tried clicking "Thank user for this post" but it says I do not have permission to do that. So I just want to add thank you guys for the replies. I think I'm going to like this message board.
    Last edited by Terran; 12-26-2010 at 06:30 PM.

  • #12
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,296
    Thanks
    10
    Thanked 584 Times in 565 Posts
    here's a slightly more educated way of doing a truncation, keeping in mind that 30 "I"s don't take up as much room as 30 "W"s:

    feel free to integrate it into your own scripts.

    Code:
    
    function slicePix(s,w){ //slices text by visual width in pixels instead of by character counts.
    var charWidths={a:10,b:11,c:10,d:11,e:11,f:6,g:11,h:10,i:4,j:4,k:9,l:4,m:16,n:10,o:11,p:11,q:11,r:6,s:10,t:5,
    u:10,v:9,w:13,x:9,y:9,z:9,A:13,B:13,C:14,D:14,E:13,F:12,G:15,H:13,I:6,J:10,K:13,L:11,M:15,N:13,O:15,P:13,
    Q:15,R:14,S:13,T:12,U:13,V:13,W:19,X:13,Y:12,Z:12,0:11,1:11,2:11,3:11,4:11,5:11,6:11,7:11,8:11,9:11};
    
     var tot=0, buff = s.split("").filter(function(a,b){
        tot+=(charWidths[a]||8);
        if(tot<w){return a;}
      }).join("");
     return buff==s ? s : buff+"...";
    }
    feed it the string and the approx #of relative pixels. you may have to adjust the pixel allowance for certain fonts, but this function should result in much more consistent visual blocking...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #13
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by DJCMBear View Post
    C'mon IE messes up on everything lol!!

    That's why most web developers call it "IFE" (and you know what the "F" is for)...

  • #14
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by Terran View Post
    How can I truncate all words greater than 30 characters using a class name when the page loads?
    Could this be what you need?

    Code:
    <html>
    <head>
    
    <script type="text/javascript">
    function truncate(text)
    {
        if (text.length > 30)
        {
            var head = text.substring(0, 10);
            var tail = text.substring(text.length-10);
            text = head + '...' + tail;
        }
        return text;
    }
    </script>
    </head>
    <body>
    
    <script type="text/javascript">
        alert(truncate('Hello'));
        alert(truncate('Mary had a little lamb, it\'s fleece was white as snow.'));
    </script>
    
    </body>
    </html>
    Output of first "alert": 'Hello'
    Output of second "alert": 'Mary had a...e as snow.'

    Hope this helps...

    -- Roger

    (edit to add): To truncate long words in a certain class, maybe you could use "getElementsByClassName" then get their innerHTML, truncate each word then write it back with innerHTML=text?

    Note Internet @!^%$# Explorer doesn't support "getElementsByClassName", but there is a nice function that provides it: LINK

    Instead of doing something like var e = document.getElementsByClassName('class') you simply do var e = getElementsByClassName('class'). Works like a charm.
    Last edited by Krupski; 12-27-2010 at 01:46 AM.

  • #15
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Quote Originally Posted by Krupski View Post
    That's why most web developers call it "IFE" (and you know what the "F" is for)...
    That made me laugh, I have no idea why Microsoft is still creating new IE's as even the latest versions (IE8 and IE9) are both really bad I do have to give credit to them though as even though IE7 is still bad it is the best IE browser they have ever made it went from IE6() lol IE7() IE8+(WTF).
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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