• We just launched and are currently in beta. Join us as we build and grow the community.

Advertise Here

Advertise Here

Advertise Here

Truncate String with Show More/Less Anchor using JavaScript Tutorial

diya1

Dark Web Explorer
D Rep
0
0
0
Rep
0
D Vouches
0
0
0
Vouches
0
Posts
100
Likes
126
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 100 XP
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. var

    truncated =

    SampleString.substring

    (

    0

    ,

    11

    )
  3. console.log

    (

    truncated)
  4. //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. //Check if Element Text content is over the maximum string length
  6. if

    (

    textLenght >

    maxString)

    {
  7. // Truncated String
  8. var

    lessContent =

    textContent.substr

    (

    0

    ,

    maxString)
  9. // Create Show More Ancor
  10. var

    showMore =

    document.createElement

    (

    'a'

    )
  11. showMore.setAttribute

    (

    'href'

    ,

    '#'

    )
  12. showMore.innerText

    =

    `Show More`

  13. // Create Show Less Ancor
  14. var

    showLess =

    document.createElement

    (

    'a'

    )
  15. showLess.setAttribute

    (

    'href'

    ,

    '#'

    )
  16. showLess.innerText

    =

    `Show Less`

  17. // Add ellipsis
  18. lessContent +=

    `...`;
  19. el.innerHTML

    =

    lessContent

  20. // Add Show More
  21. el.appendChild

    (

    showMore)

  22. // Show More Click Event Listener
  23. showMore.addEventListener

    (

    'click'

    ,

    function

    (

    )

    {
  24. // temporarily hide (for animation)
  25. el.style

    .opacity

    =

    '0'
  26. setTimeout(

    (

    )

    =>

    {
  27. // update html content to original content
  28. el.innerHTML

    =

    originalConent

  29. // add the show less anchor
  30. el.appendChild

    (

    showLess)

  31. // show html content
  32. el.style

    .opacity

    =

    '1'
  33. }

    ,

    300

    )

  34. }

    )

  35. showLess.addEventListener

    (

    'click'

    ,

    function

    (

    )

    {
  36. // temporarily hide (for animation)
  37. el.style

    .opacity

    =

    '0'
  38. setTimeout(

    (

    )

    =>

    {
  39. // update html content to truncated content
  40. el.innerHTML

    =

    lessContent

  41. // add the show more anchor
  42. el.appendChild

    (

    showMore)
  43. // show html content
  44. el.style

    .opacity

    =

    '1'
  45. }

    ,

    300

    )

  46. }

    )
  47. }

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. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    JS - More Less</

    title

    >
  8. <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"

    /

    >
  9. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    integrity=

    "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"

    crossorigin=

    "anonymous"

    >
  10. <link

    rel

    =

    "stylesheet"

    href

    =

    "assets/css/styles.css"

    >
  11. <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

    >
  12. <script

    src

    =

    "https://code.jquery.com/jquery-3.6.1.js"

    integrity=

    "sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="

    crossorigin=

    "anonymous"

    ></

    script

    >
  13. <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

    >

  14. <script

    src

    =

    "assets/js/script.js"

    ></

    script

    >
  15. <style

    >

  16. </

    style

    >
  17. </

    head

    >
  18. <body

    >
  19. <main>
  20. <nav

    class

    =

    "navbar navbar-expand-lg navbar-dark bg-gradient"

    >
  21. <div

    class

    =

    "container"

    >
  22. <a

    class

    =

    "navbar-brand"

    href

    =

    "./"

    >

    JS - More Less</

    a

    >

  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. <script

    >
  31. start_loader()
  32. </

    script

    >
  33. <div

    class

    =

    "mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12"

    >
  34. <div

    class

    =

    "card rounded-0 mb-3 shadow"

    >
  35. <div

    class

    =

    "card-header rounded-0"

    >
  36. <div

    class

    =

    "card-title"

    ><b

    >

    Content 101</

    b

    ></

    div

    >
  37. </

    div

    >
  38. <div

    class

    =

    "card-body rounded-0"

    >
  39. <div

    class

    =

    "container-fluid"

    >
  40. <div

    class

    =

    "truncate-el"

    >
  41. <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

    >
  42. <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

    >
  43. <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

    >
  44. </

    div

    >
  45. </

    div

    >
  46. </

    div

    >
  47. </

    div

    >
  48. </

    div

    >
  49. <div

    class

    =

    "mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12"

    >
  50. <div

    class

    =

    "card rounded-0 mb-3 shadow"

    >
  51. <div

    class

    =

    "card-header rounded-0"

    >
  52. <div

    class

    =

    "card-title"

    ><b

    >

    Content 102</

    b

    ></

    div

    >
  53. </

    div

    >
  54. <div

    class

    =

    "card-body rounded-0"

    >
  55. <div

    class

    =

    "container-fluid"

    >
  56. <div

    class

    =

    "truncate-el"

    >
  57. <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

    >
  58. <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

    >
  59. </

    div

    >
  60. </

    div

    >
  61. </

    div

    >
  62. </

    div

    >
  63. </

    div

    >
  64. <div

    class

    =

    "mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12"

    >
  65. <div

    class

    =

    "card rounded-0 mb-3 shadow"

    >
  66. <div

    class

    =

    "card-header rounded-0"

    >
  67. <div

    class

    =

    "card-title"

    ><b

    >

    Content 103</

    b

    ></

    div

    >
  68. </

    div

    >
  69. <div

    class

    =

    "card-body rounded-0"

    >
  70. <div

    class

    =

    "container-fluid"

    >
  71. <div

    class

    =

    "truncate-el"

    >
  72. <p

    >

    Pellentesque et maximus ipsum. Integer a efficitur sapien. Fusce rutrum bibendum blandit. Donec sit amet blandit metus.</

    p

    >
  73. </

    div

    >
  74. </

    div

    >
  75. </

    div

    >
  76. </

    div

    >
  77. </

    div

    >
  78. </

    div

    >
  79. </

    div

    >
  80. <footer

    class

    =

    "bg-gradient bg-light shadow-top py-4 col-auto"

    >
  81. <div

    class

    =

    ""

    >
  82. <div

    class

    =

    "text-center"

    >
  83. All Rights Reserved &copy;

    <span

    id

    =

    "dt-year"

    ></

    span

    >

    | <span

    class

    =

    "text-muted"

    >

    JS - More Less</

    span

    >
  84. </

    div

    >
  85. <div

    class

    =

    "text-center"

    >
  86. <a

    href

    =

    "mailto:[email protected]"

    class

    =

    "text-decoration-none text-success"

    >

    [email protected]</

    a

    >
  87. </

    div

    >
  88. </

    div

    >
  89. </

    footer

    >
  90. </

    main>
  91. <script

    src

    =

    "assets/js/truncate-moreless.js"

    ></

    script

    >

  92. </

    body

    >
  93. </

    html

    >

JavaScript

truncate-moreless.js

  1. const

    truncateEL =

    document.querySelectorAll

    (

    '.truncate-el'

    )
  2. const

    maxString =

    300

    ;

  3. truncateEL.forEach

    (

    el =>

    {
  4. var

    textContent =

    el.innerText
  5. var

    textLenght =

    textContent.length
  6. var

    originalConent =

    el.innerHTML


  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. // Create Show Less Ancor
  16. var

    showLess =

    document.createElement

    (

    'a'

    )
  17. showLess.setAttribute

    (

    'href'

    ,

    '#'

    )
  18. showLess.innerText

    =

    `Show Less`

  19. // Add ellipsis
  20. lessContent +=

    `...`;
  21. el.innerHTML

    =

    lessContent

  22. // Add Show More
  23. el.appendChild

    (

    showMore)

  24. // Show More Click Event Listener
  25. showMore.addEventListener

    (

    'click'

    ,

    function

    (

    )

    {
  26. // temporarily hide (for animation)
  27. el.style

    .opacity

    =

    '0'
  28. setTimeout(

    (

    )

    =>

    {
  29. // update html content to original content
  30. el.innerHTML

    =

    originalConent

  31. // add the show less anchor
  32. el.appendChild

    (

    showLess)

  33. // show html content
  34. el.style

    .opacity

    =

    '1'
  35. }

    ,

    300

    )

  36. }

    )

  37. showLess.addEventListener

    (

    'click'

    ,

    function

    (

    )

    {
  38. // temporarily hide (for animation)
  39. el.style

    .opacity

    =

    '0'
  40. setTimeout(

    (

    )

    =>

    {
  41. // update html content to truncated content
  42. el.innerHTML

    =

    lessContent

  43. // add the show more anchor
  44. el.appendChild

    (

    showMore)
  45. // show html content
  46. el.style

    .opacity

    =

    '1'
  47. }

    ,

    300

    )

  48. }

    )
  49. }


  50. }

    )

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 =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

452,496

342,574

342,582

Top