chickentulip
01-23-2012, 09:30 PM
I wrote a script that should loop through the list of countries, and if the entry's width exceeds 70px, it should cut the extra letters and insert "..." at the end of the entry;
My codes produces unexpected results. The script only modifies the entry"United States", by replacing it with "Cook Isla...".
I suspect I don't use the while loop properly. Plus the script does not work at all in IE.
Could someone have a look and give me a hint what went wrong.
Thank you very much!!!
<html>
<head>
<title> Ellipse Practice </title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<style type="text/css">
ul {
width: 200px;
margin-left: 100px;
}
span {
white-space: nowrap;
}
</style>
<script type="text/javascript">
function trancateAll() {
var list=document.getElementsByTagName("li");
count=0;
while (count<list.length) {
var text=String(list[count].innerHTML);
list[count].innerHTML='<span id="mySpan">'+text+'</span>';
mySpan=document.getElementById("mySpan");
mySpan.innerHTML='';
var charac=1;
while( (mySpan.offsetWidth<70) && (charac<text.length)) {
mySpan.innerHTML=text.substr(0,charac)+"...";
charac++;
}
count++;
}
}
</script>
</head>
<body >
<ul>
<li> United States</li>
<li> Australia</li>
<li> New Zealand</li>
<li> Democratic Republic of Congo</li>
<li> Russian Federation</li>
<li> Cook Islands</li>
</ul>
<input type="button" value="Truncate" onclick="trancateAll()"/>
</body>
</html>
My codes produces unexpected results. The script only modifies the entry"United States", by replacing it with "Cook Isla...".
I suspect I don't use the while loop properly. Plus the script does not work at all in IE.
Could someone have a look and give me a hint what went wrong.
Thank you very much!!!
<html>
<head>
<title> Ellipse Practice </title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<style type="text/css">
ul {
width: 200px;
margin-left: 100px;
}
span {
white-space: nowrap;
}
</style>
<script type="text/javascript">
function trancateAll() {
var list=document.getElementsByTagName("li");
count=0;
while (count<list.length) {
var text=String(list[count].innerHTML);
list[count].innerHTML='<span id="mySpan">'+text+'</span>';
mySpan=document.getElementById("mySpan");
mySpan.innerHTML='';
var charac=1;
while( (mySpan.offsetWidth<70) && (charac<text.length)) {
mySpan.innerHTML=text.substr(0,charac)+"...";
charac++;
}
count++;
}
}
</script>
</head>
<body >
<ul>
<li> United States</li>
<li> Australia</li>
<li> New Zealand</li>
<li> Democratic Republic of Congo</li>
<li> Russian Federation</li>
<li> Cook Islands</li>
</ul>
<input type="button" value="Truncate" onclick="trancateAll()"/>
</body>
</html>