Why
The reason you get the error is because your computer hasn't run the code that defined truncate
yet. That function is running before the page finishes loading, that includes the JavaScript. Put the code in a window.onload
with a setTimeout
to be safe.
window.onload = function(){setTimeout(function () {
truncate("truncate this text");
},1);};
How
Also, unlike languages such as PHP. return
won't place any text. Do something like:
<a id="result-location" href='test'>
<script>
window.onload = function(){setTimeout(function () {
document.getElementById('result-location').innerHTML = truncate("truncate this text");
},1);};
</script>
</a>
JSFiddle Fix
Remember to keep the function outside of a window.onload
. You can change this in JSFiddle by setting it no no-wrap

CSS
You can use CSS to truncate text
.truncate {
width: 50px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
This will cause the text to truncate, after 50px;
.truncate {
width: 50px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
<a class="truncate">This text is truncated</a>