How to Truncate in Prototype
This is to truncate multiple items in the javascript library Prototype. If it has the class="truncate" it will be truncated!
Simple way:
var toTruncate = $$(".truncate");
var len = 190;
for(i=0;i
Class Based:
var TruncateIt = Class.create({
initialize: function(sTruncate) {
var toTruncate = (typeof sTruncate != 'undefined') ? $$(sTruncate) : $$('.truncate');
var len = 100;
for (var i = 0; i < toTruncate.length; i++) {
toTruncate[i].innerHTML=toTruncate[i].innerHTML.truncate(len);
}
}
});
document.observe('dom:loaded', function(){
var truncate = new TruncateIt('.truncate');
});
Thanks to Kris for helping me write this in a class as I'm totally new to prototype. See his hip new site at komputerart.com.
This is to truncate multiple items in the javascript library Prototype. If it has the class="truncate" it will be truncated!
Simple way:
var toTruncate = $$(".truncate"); var len = 190; for(i=0;iClass Based: var TruncateIt = Class.create({ initialize: function(sTruncate) { var toTruncate = (typeof sTruncate != 'undefined') ? $$(sTruncate) : $$('.truncate'); var len = 100; for (var i = 0; i < toTruncate.length; i++) { toTruncate[i].innerHTML=toTruncate[i].innerHTML.truncate(len); } } }); document.observe('dom:loaded', function(){ var truncate = new TruncateIt('.truncate'); });Thanks to Kris for helping me write this in a class as I'm totally new to prototype. See his hip new site at komputerart.com.
2 Comments:
Nice work! Just a couple comments to help explain the code:
var toTruncate = (typeof sTruncate != 'undefined') ? $$(sTruncate) : $$('.truncate');
This line uses a ternary operator to check whether the parameter 'sTruncate' is defined and if not, falls back to the default class 'truncate'.
var len = 100;
This line sets the max characters to 100. So, it will cut off any text from the 101st character on.
You could also add some logic to only truncate on spaces, since truncating in the middle of some words could produce surprising and potentially offensive results. And, depending on the application, it may be desirable to append ellipses at the end.
To check for spaces, you'd need to add some logic that checks the position of the string at len - 1, and keep decrementing and checking if the character is a space until you find one. Once you find a space, you lop it off there.
Something like:
for (var i = 0; i < toTruncate.length; i++) {
var len = 100;
for (var charIndex = len - 1;
toTruncate[i].innerHTML.
charAt(charIndex) == " ";
charIndex--) {
len--;
}
toTruncate[i].replace(
toTruncate[i].innerHTML.truncate(len)
);
}
I haven't tested this, but it should work. As for adding ellipses, something like this should work:
toTruncate[i].replace(
toTruncate[i].innerHTML.truncate(len)
+ "..."
);
I found out that Prototype automatically adds the ellipsis for you. Sweet!
Post a Comment
Subscribe to Post Comments [Atom]
<< Home