tags:

views:

508

answers:

5

Hello

I have many fields in an html page such as this

<div class="note" id="notexyz23">
    very long content
</div>

I'm looking for a script that can do the following:

  • check if the content length is larger than some quantity (like 300 characters)
  • if this is the case, compact it so that its length is 300 characters and display an "expand" button, otherwise leave it as it is

Obviously it should maintain intact the inner html structure of the content.

I'm sure something like this has been done already, I'd like to get some reference.

Thanks a lot

Nicola Montecchio

A: 
 if(document.getElementById('notexyz23').innerHTML.length > 300)
{
    document.getElementById('notexyz23').innerHTML = document.getElementById('notexyz23').innerHTML.substring(0, 300);
    //Add expand button outside of DIV
}
George
A: 

you might want to use a framework that supports css selectors something like dojo or jquery

so think:

dojo.query(".note").foreach(
     function(zeDiv){
       if(zeDiv.innerHTML.length > 300){
          var content = zeDiv.innerHTML;
          var summary = content.subtring(0,300);
          zeDiv.innerHTML = summary;
          var hiddenContent = document.createElement("input");
          hiddenContent.type = "hidden";
          hiddenContent.value = content;
          zeDiv.appendChild(hiddenContent);
          var expandButton = document.createElement("input");
          expandButton.type = "button";
          expandButton.onClick = function(){
             this.innerHTML = dojo.query("[type=hidden]")[0].value;
          }
          zeDiv.appendChild(expandButton);
       }
     }
);

The code isn't tested but its something in this general direction.

MahdeTo
A: 

There's a jQuery plugin located here that, when called, automatically cuts off the text that doesn't fits and adds the ellipsis. It also recalculates if the container is resized.

Stephen
A: 

Not an answer to your question, but here's a nice little function I have to truncate text only at the end of a word instead of just blindly after x chars.

function truncate(text, length) {
    if (text.length > length) {
        var re = new RegExp('^(.{1,' +length+ '})(\\s.*|$)');
        text = text.replace(re, '$1...');
    }
    return text;
}
tj111
+1  A: 

THIS is what I was looking for: http://www.reindel.com/truncate/#examples Anyway, thanks to all of you for your kind answers. have a nice day Nicola

Nicola Montecchio