Truncate String with Show More/Less Anchor using JavaScript Tutorial

In this tutorial, you will learn how to Truncate String or Text Content using jQuery Library with Show More/Less functionality. The tutorial aims to provide IT/CS Students and new programmers with a reference for enhancing their knowledge and skills for developing an application with creative and useful UI/UX. Here, a step-by-step tutorial with snippets is provided. A sample source code zip file for an application that demonstrates the goal of this tutorial.

What is String Truncate?

String Truncate is a way of cutting or slicing the long text content on displaying it on the page. This feature is usually implemented in dynamic content with long text content like in Content Management System. Along with the Show More/Less feature, users will have the privilege to show all the text content or not.

How to Truncate String using JavaScript?

In JavaScript, we can use the substr() (substring) method which allows you to limit the string length. See the following snippet.

  1. var SampleString = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatibus, natus unde. Saepe iste ipsum consectetur dolores, cumque illo vitae repellendus fugiat voluptate nobis eligendi omnis debitis quaerat. Earum, quis. Sequi."
  2.  
  3. var truncated = SampleString.substring(0, 11)
  4. console.log(truncated)
  5. //Outputs: Lorem ipsum

How to create a Show More/Less feature using JavaScript?

Using the same concept on the first snippet that I provided, we can limit the displayed text of the long text content on page load. With some logic and using some JavaScript built-in methods that are usable for creating the show more/less feature. See the following snippet below.

  1. var el = document.getElementById('truncate-text')
  2. var textContent = el.innerText
  3. var textLenght = textContent.length
  4. var originalConent = el.innerHTML
  5.  
  6.  
  7. //Check if Element Text content is over the maximum string length
  8. if(textLenght > maxString){
  9. // Truncated String
  10. var lessContent = textContent.substr(0, maxString)
  11. // Create Show More Ancor
  12. var showMore = document.createElement('a')
  13. showMore.setAttribute('href', '#')
  14. showMore.innerText = `Show More`
  15.  
  16. // Create Show Less Ancor
  17. var showLess = document.createElement('a')
  18. showLess.setAttribute('href', '#')
  19. showLess.innerText = `Show Less`
  20.  
  21. // Add ellipsis
  22. lessContent += `...`;
  23. el.innerHTML = lessContent
  24.  
  25. // Add Show More
  26. el.appendChild(showMore)
  27.  
  28. // Show More Click Event Listener
  29. showMore.addEventListener('click', function(){
  30. // temporarily hide (for animation)
  31. el.style.opacity = '0'
  32. setTimeout(()=>{
  33. // update html content to original content
  34. el.innerHTML = originalConent
  35.  
  36. // add the show less anchor
  37. el.appendChild(showLess)
  38.  
  39. // show html content
  40. el.style.opacity = '1'
  41. }, 300)
  42.  
  43. })
  44.  
  45. showLess.addEventListener('click', function(){
  46. // temporarily hide (for animation)
  47. el.style.opacity = '0'
  48. setTimeout(()=>{
  49. // update html content to truncated content
  50. el.innerHTML = lessContent
  51.  
  52. // add the show more anchor
  53. el.appendChild(showMore)
  54. // show html content
  55. el.style.opacity = '1'
  56. }, 300)
  57.  
  58. })
  59. }

The script below identifies first if the text content is longer than the given maximum text content length. If it is longer than the maximum content length, the script will truncate the string and add the show more anchor. The show more anchor will replace the element text content with the original string or content and replace the anchor with show less. The show-less anchor will convert the text content into a truncated string.

Sample

Here are the scripts of simple web applications that demonstrate the main goal of this tutorial.

Interface

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JS - More Less</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="assets/css/styles.css">
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11. <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13.  
  14. <script src="assets/js/script.js"></script>
  15.  
  16. </style>
  17. </head>
  18. <main>
  19. <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  20. <div class="container">
  21. <a class="navbar-brand" href="./">JS - More Less</a>
  22.  
  23. <div>
  24. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  25. </div>
  26. </div>
  27. </nav>
  28. <div id="main-wrapper">
  29. <div class="container px-5 my-3" >
  30. start_loader()
  31. </script>
  32. <div class="mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12">
  33. <div class="card rounded-0 mb-3 shadow">
  34. <div class="card-header rounded-0">
  35. <div class="card-title"><b>Content 101</b></div>
  36. </div>
  37. <div class="card-body rounded-0">
  38. <div class="container-fluid">
  39. <div class="truncate-el">
  40. <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer imperdiet vitae mi eu feugiat. Etiam et fringilla orci, quis euismod nunc. Phasellus eleifend est dolor, sit amet aliquet eros scelerisque at. Fusce varius sapien non dignissim bibendum. Pellentesque convallis faucibus luctus. Nullam euismod sem blandit lorem lacinia sollicitudin pretium vitae urna. Mauris venenatis pharetra erat at tincidunt. Donec id dui a augue lacinia lobortis. Nullam sit amet mollis massa, eget gravida felis. Maecenas porttitor ac augue eu maximus. Curabitur nec quam quis lacus tincidunt luctus vitae sit amet eros. Etiam leo nisl, varius eu mi ac, feugiat imperdiet nibh. Nunc libero sapien, mattis a rhoncus et, condimentum nec purus.</p>
  41. <p>Cras facilisis, nulla eu sollicitudin pretium, eros risus accumsan quam, vel pulvinar ligula orci a mauris. Donec ac felis non sem luctus dictum vitae in erat. Pellentesque ut aliquet quam. Cras suscipit dapibus efficitur. Donec convallis mi et venenatis laoreet. In hac habitasse platea dictumst. Praesent dictum sed mauris eu suscipit. Maecenas justo mi, fermentum eget faucibus eget, vulputate eleifend lorem. Phasellus odio nibh, tempus eu enim ac, congue dignissim turpis.</p>
  42. <p>Nam eros sem, dictum ac dapibus a, iaculis sed tellus. Sed pharetra turpis at lorem tincidunt, at malesuada lectus rhoncus. Fusce leo turpis, dictum ultricies nisl a, tempus sodales sem. Quisque pulvinar risus id consequat consectetur. Nulla dignissim iaculis condimentum. Fusce mollis risus luctus diam auctor, ac pulvinar urna pulvinar. Pellentesque at gravida elit. Mauris ac risus dui. Nam nisi arcu, imperdiet at ipsum ac, commodo sodales elit. Sed imperdiet nisi magna, sit amet placerat purus condimentum et. Vestibulum vel lectus porta, finibus risus consequat, lacinia metus. Donec ac nibh facilisis, aliquet neque id, molestie justo. Vivamus tincidunt lorem ac leo cursus iaculis. Aliquam rutrum fringilla nunc, sit amet tempus ex vestibulum et.</p>
  43. </div>
  44. </div>
  45. </div>
  46. </div>
  47. </div>
  48. <div class="mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12">
  49. <div class="card rounded-0 mb-3 shadow">
  50. <div class="card-header rounded-0">
  51. <div class="card-title"><b>Content 102</b></div>
  52. </div>
  53. <div class="card-body rounded-0">
  54. <div class="container-fluid">
  55. <div class="truncate-el">
  56. <p>Pellentesque et maximus ipsum. Integer a efficitur sapien. Fusce rutrum bibendum blandit. Donec sit amet blandit metus. Praesent vel vestibulum lorem, ut sollicitudin eros. Pellentesque eget tempor odio. Donec auctor gravida magna gravida interdum.</p>
  57. <p>Nullam nec ligula urna. Donec diam nunc, rutrum a venenatis id, bibendum vel leo. Aenean a rhoncus diam, et ultrices lacus. Sed rutrum justo eget dolor ultrices blandit.</p>
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62. </div>
  63. <div class="mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12">
  64. <div class="card rounded-0 mb-3 shadow">
  65. <div class="card-header rounded-0">
  66. <div class="card-title"><b>Content 103</b></div>
  67. </div>
  68. <div class="card-body rounded-0">
  69. <div class="container-fluid">
  70. <div class="truncate-el">
  71. <p>Pellentesque et maximus ipsum. Integer a efficitur sapien. Fusce rutrum bibendum blandit. Donec sit amet blandit metus.</p>
  72. </div>
  73. </div>
  74. </div>
  75. </div>
  76. </div>
  77. </div>
  78. </div>
  79. <footer class="bg-gradient bg-light shadow-top py-4 col-auto">
  80. <div class="">
  81. <div class="text-center">
  82. All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">JS - More Less</span>
  83. </div>
  84. <div class="text-center">
  85. <a href="mailto:[email protected]" class="text-decoration-none text-success">[email protected]</a>
  86. </div>
  87. </div>
  88. </footer>
  89. </main>
  90. <script src="assets/js/truncate-moreless.js"></script>
  91.  
  92. </body>
  93. </html>

JavaScript

truncate-moreless.js

  1. const truncateEL = document.querySelectorAll('.truncate-el')
  2. const maxString = 300;
  3.  
  4. truncateEL.forEach(el =>{
  5. var textContent = el.innerText
  6. var textLenght = textContent.length
  7. var originalConent = el.innerHTML
  8.  
  9.  
  10. //Check if Element Text content is over the maximum string length
  11. if(textLenght > maxString){
  12. // Truncated String
  13. var lessContent = textContent.substr(0, maxString)
  14. // Create Show More Ancor
  15. var showMore = document.createElement('a')
  16. showMore.setAttribute('href', '#')
  17. showMore.innerText = `Show More`
  18.  
  19. // Create Show Less Ancor
  20. var showLess = document.createElement('a')
  21. showLess.setAttribute('href', '#')
  22. showLess.innerText = `Show Less`
  23.  
  24. // Add ellipsis
  25. lessContent += `...`;
  26. el.innerHTML = lessContent
  27.  
  28. // Add Show More
  29. el.appendChild(showMore)
  30.  
  31. // Show More Click Event Listener
  32. showMore.addEventListener('click', function(){
  33. // temporarily hide (for animation)
  34. el.style.opacity = '0'
  35. setTimeout(()=>{
  36. // update html content to original content
  37. el.innerHTML = originalConent
  38.  
  39. // add the show less anchor
  40. el.appendChild(showLess)
  41.  
  42. // show html content
  43. el.style.opacity = '1'
  44. }, 300)
  45.  
  46. })
  47.  
  48. showLess.addEventListener('click', function(){
  49. // temporarily hide (for animation)
  50. el.style.opacity = '0'
  51. setTimeout(()=>{
  52. // update html content to truncated content
  53. el.innerHTML = lessContent
  54.  
  55. // add the show more anchor
  56. el.appendChild(showMore)
  57. // show html content
  58. el.style.opacity = '1'
  59. }, 300)
  60.  
  61. })
  62. }
  63.  
  64.  
  65. })

Snapshots

Here are the snapshots of the application interface

Interface

Shown More

Shown Less

The source code zip file of the application that I created for this tutorial is also provided on this website and is free to download. Feel free to download it by clicking the download button below this article.

That's it! You can now test the sample application on your end and see if it works properly. I hope this Truncate String with Show More/Less Anchor using JavaScript Tutorial will help you with what you are looking for and will be useful for current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Enjoy =)

Add new comment