javascript - Truncate <a> tag text - Stack Overflow

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

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

/

But returns error Uncaught ReferenceError: truncate is not defined

How can this function be invoked from within <a> tag ?

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

But returns error Uncaught ReferenceError: truncate is not defined

How can this function be invoked from within <a> tag ?

Share Improve this question edited Apr 25, 2015 at 21:46 Downgoat 14.4k7 gold badges47 silver badges72 bronze badges asked Apr 25, 2015 at 20:54 blue-skyblue-sky 54k161 gold badges466 silver badges780 bronze badges 1
  • You have to receive the output in document.write check the answer. – SaidbakR Commented Apr 25, 2015 at 21:13
Add a ment  | 

6 Answers 6

Reset to default 3

Why

The reason you get the error is because your puter 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


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>

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>

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

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

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/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./makandra/5883-use-css-text-overflow-to-truncate-long-texts

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745532990a4631779.html

相关推荐

  • javascript - Truncate &lt;a&gt; tag text - Stack Overflow

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

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信