javascript - Truncate <a> tag text -
in below code i'm attempting truncate <a>
tag text :
<a href='test'> <script> truncate("truncate 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 not defined
how can function invoked within <a>
tag ?
why
the reason error because computer hasn't run code defined truncate
yet. function running before page finishes loading, includes javascript. put code in window.onload
settimeout
safe.
window.onload = function(){settimeout(function () { truncate("truncate text"); },1);};
how
also, unlike languages such php. return
won't place text. like:
<a id="result-location" href='test'> <script> window.onload = function(){settimeout(function () { document.getelementbyid('result-location').innerhtml = truncate("truncate text"); },1);}; </script> </a>
fiddle
jsfiddle fix
remember keep function outside of window.onload
. can change in jsfiddle setting no no-wrap
css
you can use css truncate text
.truncate { width: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block; }
this cause text truncate, after 50px;
.truncate { width: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block; }
<a class="truncate">this text truncated</a>
Comments
Post a Comment