...

View Full Version : My code is not working. Please help



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>

Old Pedant
01-23-2012, 11:24 PM
When you reach this line of code:

mySpan=document.getElementById("mySpan");

You don't have anything on that page with an id of "mySpan", so you get an error and the code stops right there. So of course only the first one gets changed.

chickentulip
01-24-2012, 02:24 PM
Thank you. I understand now where I made an error



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum