diya1
Dark Web Explorer
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.
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.
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
JavaScript
truncate-moreless.js
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
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.
- 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."
- var
truncated =
SampleString.substring
(
0
,
11
)
- console.log
(
truncated)
- //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.
- var
el =
document.getElementById
(
'truncate-text'
)
- var
textContent =
el.innerText
- var
textLenght =
textContent.length
- var
originalConent =
el.innerHTML
- //Check if Element Text content is over the maximum string length
- if
(
textLenght >
maxString)
{
- // Truncated String
- var
lessContent =
textContent.substr
(
0
,
maxString)
- // Create Show More Ancor
- var
showMore =
document.createElement
(
'a'
)
- showMore.setAttribute
(
'href'
,
'#'
)
- showMore.innerText
=
`Show More`
- // Create Show Less Ancor
- var
showLess =
document.createElement
(
'a'
)
- showLess.setAttribute
(
'href'
,
'#'
)
- showLess.innerText
=
`Show Less`
- // Add ellipsis
- lessContent +=
`...`;
- el.innerHTML
=
lessContent
- // Add Show More
- el.appendChild
(
showMore)
- // Show More Click Event Listener
- showMore.addEventListener
(
'click'
,
function
(
)
{
- // temporarily hide (for animation)
- el.style
.opacity
=
'0'
- setTimeout(
(
)
=>
{
- // update html content to original content
- el.innerHTML
=
originalConent
- // add the show less anchor
- el.appendChild
(
showLess)
- // show html content
- el.style
.opacity
=
'1'
- }
,
300
)
- }
)
- showLess.addEventListener
(
'click'
,
function
(
)
{
- // temporarily hide (for animation)
- el.style
.opacity
=
'0'
- setTimeout(
(
)
=>
{
- // update html content to truncated content
- el.innerHTML
=
lessContent
- // add the show more anchor
- el.appendChild
(
showMore)
- // show html content
- el.style
.opacity
=
'1'
- }
,
300
)
- }
)
- }
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
- <!DOCTYPE html>
- <html
lang
=
"en"
>
- <head
>
- <meta
charset
=
"UTF-8"
>
- <meta
http-equiv
=
"X-UA-Compatible"
content
=
"IE=edge"
>
- <meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
- <title
>
JS - More Less</
title
>
- <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"
/
>
- <link
rel
=
"stylesheet"
href
=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity=
"sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"
crossorigin=
"anonymous"
>
- <link
rel
=
"stylesheet"
href
=
"assets/css/styles.css"
>
- <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
>
- <script
src
=
"https://code.jquery.com/jquery-3.6.1.js"
integrity=
"sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin=
"anonymous"
></
script
>
- <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
>
- <script
src
=
"assets/js/script.js"
></
script
>
- <style
>
- </
style
>
- </
head
>
- <body
>
- <main>
- <nav
class
=
"navbar navbar-expand-lg navbar-dark bg-gradient"
>
- <div
class
=
"container"
>
- <a
class
=
"navbar-brand"
href
=
"./"
>
JS - More Less</
a
>
- <div
>
- <a
href
=
"https://sourcecodester.com"
class
=
"text-light fw-bolder h6 text-decoration-none"
target
=
"_blank"
>
SourceCodester</
a
>
- </
div
>
- </
div
>
- </
nav
>
- <div
id
=
"main-wrapper"
>
- <div
class
=
"container px-5 my-3"
>
- <script
>
- start_loader()
- </
script
>
- <div
class
=
"mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12"
>
- <div
class
=
"card rounded-0 mb-3 shadow"
>
- <div
class
=
"card-header rounded-0"
>
- <div
class
=
"card-title"
><b
>
Content 101</
b
></
div
>
- </
div
>
- <div
class
=
"card-body rounded-0"
>
- <div
class
=
"container-fluid"
>
- <div
class
=
"truncate-el"
>
- <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
>
- <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
>
- <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
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- <div
class
=
"mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12"
>
- <div
class
=
"card rounded-0 mb-3 shadow"
>
- <div
class
=
"card-header rounded-0"
>
- <div
class
=
"card-title"
><b
>
Content 102</
b
></
div
>
- </
div
>
- <div
class
=
"card-body rounded-0"
>
- <div
class
=
"container-fluid"
>
- <div
class
=
"truncate-el"
>
- <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
>
- <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
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- <div
class
=
"mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12"
>
- <div
class
=
"card rounded-0 mb-3 shadow"
>
- <div
class
=
"card-header rounded-0"
>
- <div
class
=
"card-title"
><b
>
Content 103</
b
></
div
>
- </
div
>
- <div
class
=
"card-body rounded-0"
>
- <div
class
=
"container-fluid"
>
- <div
class
=
"truncate-el"
>
- <p
>
Pellentesque et maximus ipsum. Integer a efficitur sapien. Fusce rutrum bibendum blandit. Donec sit amet blandit metus.</
p
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- </
div
>
- <footer
class
=
"bg-gradient bg-light shadow-top py-4 col-auto"
>
- <div
class
=
""
>
- <div
class
=
"text-center"
>
- All Rights Reserved ©
<span
id
=
"dt-year"
></
span
>
| <span
class
=
"text-muted"
>
JS - More Less</
span
>
- </
div
>
- <div
class
=
"text-center"
>
- <a
href
=
"mailto:[email protected]"
class
=
"text-decoration-none text-success"
>
[email protected]</
a
>
- </
div
>
- </
div
>
- </
footer
>
- </
main>
- <script
src
=
"assets/js/truncate-moreless.js"
></
script
>
- </
body
>
- </
html
>
JavaScript
truncate-moreless.js
- const
truncateEL =
document.querySelectorAll
(
'.truncate-el'
)
- const
maxString =
300
;
- truncateEL.forEach
(
el =>
{
- var
textContent =
el.innerText
- var
textLenght =
textContent.length
- var
originalConent =
el.innerHTML
- //Check if Element Text content is over the maximum string length
- if
(
textLenght >
maxString)
{
- // Truncated String
- var
lessContent =
textContent.substr
(
0
,
maxString)
- // Create Show More Ancor
- var
showMore =
document.createElement
(
'a'
)
- showMore.setAttribute
(
'href'
,
'#'
)
- showMore.innerText
=
`Show More`
- // Create Show Less Ancor
- var
showLess =
document.createElement
(
'a'
)
- showLess.setAttribute
(
'href'
,
'#'
)
- showLess.innerText
=
`Show Less`
- // Add ellipsis
- lessContent +=
`...`;
- el.innerHTML
=
lessContent
- // Add Show More
- el.appendChild
(
showMore)
- // Show More Click Event Listener
- showMore.addEventListener
(
'click'
,
function
(
)
{
- // temporarily hide (for animation)
- el.style
.opacity
=
'0'
- setTimeout(
(
)
=>
{
- // update html content to original content
- el.innerHTML
=
originalConent
- // add the show less anchor
- el.appendChild
(
showLess)
- // show html content
- el.style
.opacity
=
'1'
- }
,
300
)
- }
)
- showLess.addEventListener
(
'click'
,
function
(
)
{
- // temporarily hide (for animation)
- el.style
.opacity
=
'0'
- setTimeout(
(
)
=>
{
- // update html content to truncated content
- el.innerHTML
=
lessContent
- // add the show more anchor
- el.appendChild
(
showMore)
- // show html content
- el.style
.opacity
=
'1'
- }
,
300
)
- }
)
- }
- }
)
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.