Text trimming <a> tag
In the code below, I am trying to truncate the tag text <a>:
<a href='test'>
<script>
truncate("truncate this text");
</script>
</a>
function truncate(string){
if (string.length > 5)
return string.substring(0,5)+'...';
else
return string;
};
https://jsfiddle.net/fcq6o4Lz/6/
But returns error Uncaught ReferenceError: truncate is not defined
How can this function be called from a tag <a>?
Why
The reason you get the error message is because your computer has not yet run the code that it detected truncate. This function is executed until the page has finished loading, including JavaScript. Put the code in window.onloadwith setTimeoutto be safe.
window.onload = function(){setTimeout(function () {
truncate("truncate this text");
},1);};
how
Also, unlike languages like PHP. returnwill not put 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>
Fiddle
<h / ">
JSFiddle
window.onload. JSFiddle, no no wrap

CSS
CSS
.truncate {
width: 50px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
50px;
, :
<a href='test' id="test-id">truncate this text</a>
<script>
function truncate(id){
var string = document.getElementById(id).innerHTML;
if (string.length > 5) {
document.getElementById(id).innerHTML = string.substring(0,5)+'...';
}
};
truncate("test-id");
</script>
JSFiddle-Demo: http://jsfiddle.net/c8s3dc6q/1/
, document.write
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script>
function truncate(string){
if (string.length > 5)
return string.substring(0,5)+'...';
else
return string;
};
</script>
</head>
<body>
hhhhhhh<br />
<a href='test'>
<script>
document.write(truncate("truncate this text"));
</script>
</a>
</body>
</html>
css, . , , .
http://jsfiddle.net/Hastig/ufe1t66v/3/
HTML
<a class="truncated-anchors">This be way too long</a>
<a class="truncated-anchors">This too is too long</a>
<a class="truncated-anchors">This as well, far too long</a>
<a class="truncated-anchors">This one is even longer if I add some more words</a>
CSS
.truncated-anchors {
display: inline-block;
width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
http://makandracards.com/makandra/5883-use-css-text-overflow-to-truncate-long-texts
And there are options to not use the ellipsis and just finish it immediately.