4

In below code I'm attempting to truncate the <a> tag text :

<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 invoked from within <a> tag ?

Downgoat
  • 11,422
  • 5
  • 37
  • 64
blue-sky
  • 45,835
  • 124
  • 360
  • 647

6 Answers6

3

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>

Fiddle


JSFiddle Fix

Remember to keep the function outside of a window.onload. You can change this in JSFiddle by setting it no no-wrap

Choose 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>
Downgoat
  • 11,422
  • 5
  • 37
  • 64
0

You don't invoke javascript code like this. Although you could use document.write to print result of javascript function into HTML element, it is stongly advised to avoid this, as it makes code really confusing.

Instead try something like this: select HTML element in question with CSS selector, select corresponding HTML element, and finally modify its inner content.

function truncate(selector) {
    
    var obj = document.querySelector(selector),
        string = obj.innerHTML;
    
    if (string.length > 5) string = string.substring(0, 5) + '...';
    
    obj.innerHTML = string;
};

truncate('#link');
<a href="test" id="link">truncate this text</a>
dfsq
  • 182,609
  • 24
  • 222
  • 242
0

You have to address the element with an ID, like this:

<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/

Reeno
  • 5,524
  • 10
  • 35
  • 48
0

All javascript, including the function definition, should happen within a <script> ... </script> block. And that script block should stay in the end of the page, where the function "selects" the a tag with an id or class.

However I think that you might want to achieve the same results using pure CSS.

<a class="trim-text">This text should be trimmed!</a>

// add this to your css file / block
.trim-text {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

h1 {
  max-width: 100px;
}
ddinchev
  • 29,115
  • 26
  • 82
  • 124
0

Simply define the function before its call in the code, then use document.write to receive the output of the function

<!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>

Checkout this DEMO

SaidbakR
  • 11,955
  • 16
  • 89
  • 173
  • 1
    `document.write` shouldn't really *ever* be used. It promotes bad practice – Downgoat Apr 25 '15 at 21:14
  • As the the code of OP he could not printout his function output without `document.write`. Secondly, what's the bad practice in `document.write` I think it is one of the first things one may know about DOM. – SaidbakR Apr 25 '15 at 21:17
  • 1
    I was tempted to downvote solely because you suggested using `document.write`. There are [many reasons](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) it shouldn't be used. [Douglas Crockford on `document.write`](https://www.youtube.com/watch?feature=player_detailpage&v=Y2Y0U-2qJMs#t=1082s). It is never a good idea to teach beginners bad habits, they might take them up without realizing they are bad habits. – Useless Code Apr 25 '15 at 21:22
  • 1
    Also, his problem originated because of `window.onload` and `document.write` will only *really* work before – Downgoat Apr 25 '15 at 21:24
  • The demo that I have offer, does not show any of points regarded in the signed answer of http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice. Simply it works and it is the more near solution from the OP code. – SaidbakR Apr 25 '15 at 21:32
  • Also you may checkout the second answer of that question too, http://stackoverflow.com/a/802894/1592845 – SaidbakR Apr 25 '15 at 21:36
0

If you're open to a css only method there's a way to do that. It's based on width and not character count so more precise for styling.

fiddle

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;
}

A more thorough explanation

http://makandracards.com/makandra/5883-use-css-text-overflow-to-truncate-long-texts

And there are options to not use ellipsis and just end it immediately.

Hastig Zusammenstellen
  • 3,744
  • 2
  • 29
  • 42