PDA

View Full Version : Truncating long words with javascript - need help adjusting code



plastikaa
November 4th, 2004, 12:24 PM
At the moment I'm using the following code to truncate words that are over 15 characters long, and add '...' onto the end to show the word has been truncated - im using this on part of a forum where users post the words so I have no control over the length of the word but need to make sure the layout of the page doesnt mess up.


Placed inbetween head tags



<script language="javascript" type="text/javascript">
<!--
var mxw_max = 5;
function mxw(id)
{
if (!document.getElementById) return;
var n = document.getElementById(id);
if (!n || !n.nodeType) return;
mxw2(n);
}
function mxw2(n)
{
if (n.nodeType == 3 /*Node.TEXT_NODE*/)
{
var flag = 0;
var words = n.data.split(" ");
for (var i = 0; i < words.length; i++)
{
if (words[i].length > mxw_max)
{
flag++;
words[i] = words[i].substr(0, mxw_max-2) + "... ";
}
}
if (flag > 0) n.data = words.join(" ");
}
var children = n.childNodes;
for (var i = 0; i < children.length; i++) mxw2(children[i]);
}
//-->
</script>


Then on the page I use the following around the user posted text to truncate the word.



<div id="shorten">Userpostedtextishere</div><script language="javascript" type="text/javascript">mxw("shorten");</script>


So 'Userpostedtextishere' would become 'Userpostedtex...'

The problem is that I can only use this on one part of the page - unless i give different ID's to all the divs on every part of the page where I need to use it.

How can I get this to work so I can use the same div and script around the words on every part of the page?

(BTW: Im know nothing much about javascript as I'm just a html person - so please dont just tell me the changes to the header code I must make as I probably wont understand)

All help will be appreciated a lot!

Thanks,