Multiline Truncation With Ellipsis & Read More Button

With the help of JavaScript & CSS’s line-clamp property, we can detect if an HTML element has overflow content, truncate the text with ellipsis (…) & add a “Read more” button that expand the text when clicked.

In this article, we will show you how to detect the length of the content, truncate content accordingly to your need, and add a Read More button to expand the content when clicked.

View Demo: Detect Overflow Content & Add Read More Button

Prerequisites

We expect that you are familiar with the following:

  • HTML5 and CSS3 (Basic level)
  • JavaScript (Basic level)

Expected Learnings

Your key learnings from this project will be:

  • How to detect and know is the content overflow in a DIV
  • How to truncate a content and add a Read More button if the content is overflow

Overview of Code

<!DOCTYPE>
<html>
<head>
	<style>
		body {
			width: 320px;
		}
		#content {
		    display: -webkit-box;
		    -webkit-box-orient: vertical;
		    -webkit-line-clamp: 3;
		    overflow: hidden;
		    width: 320px;
		}
		#content.reveal-all {
			display: block;
		}
		#btn-expand-container {
			margin-top: 12px;
			text-align: right;
		}
		#btn-expand-container button {
			cursor: pointer;
		}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script>
		$(document).ready(function() {
			function detectIsOverflow(element) {
				return element.scrollHeight > element.clientHeight
			}
			function enableReadMoreButton(condition, element) {
				if(condition == true) {
					element.show();
				} else {
					element.hide();
				}
			}
			function toggleReadCloseText(parent, element_readmore, element_close) {
				if(element_readmore.is(":visible")) {
					parent.addClass('reveal-all');
					element_readmore.hide();
					element_close.show();
				} else {
					parent.removeClass('reveal-all');
					element_readmore.show();
					element_close.hide();
				}
			}
			var is_content_overflow = detectIsOverflow($('#content')[0]);
			enableReadMoreButton(is_content_overflow, $('#btn-expand-container'));
			$('#btn-expand-container button').on('click', function() {
				toggleReadCloseText($('#content'), $('.txt-readmore'), $('.txt-readless'));
			});
			
		});
	</script>
</head>
<body>
	<div id="content">
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque semper nisi sed interdum sollicitudin. Sed ac elit vitae lacus scelerisque cursus. Donec vehicula diam vel magna vestibulum, nec porttitor lacus ullamcorper. Suspendisse vehicula sapien sit amet eros vehicula accumsan. Vivamus lobortis, sem sit amet consectetur fermentum, quam erat hendrerit nunc, ut vestibulum lectus arcu cursus nisi. Donec blandit neque sed tristique rutrum. Cras vel mi eleifend purus fermentum mattis. Nulla fermentum erat at mauris congue, eu aliquet mi scelerisque. Duis in faucibus quam. Praesent facilisis vitae nulla in suscipit. Praesent porta sapien cursus odio rhoncus commodo. Maecenas ac magna vel velit finibus sagittis sed nec tortor.
	</div>
	<div id="btn-expand-container">
		<button class="txt-readmore">Read More</button>
		<button class="txt-readless" style="display: none;">Close</button>
	</div>
</body>
</html>

Step 1: Setup the HTML structure

<!DOCTYPE>
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
	<div id="content">
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque semper nisi sed interdum sollicitudin. Sed ac elit vitae lacus scelerisque cursus. Donec vehicula diam vel magna vestibulum, nec porttitor lacus ullamcorper. Suspendisse vehicula sapien sit amet eros vehicula accumsan. Vivamus lobortis, sem sit amet consectetur fermentum, quam erat hendrerit nunc, ut vestibulum lectus arcu cursus nisi. Donec blandit neque sed tristique rutrum. Cras vel mi eleifend purus fermentum mattis. Nulla fermentum erat at mauris congue, eu aliquet mi scelerisque. Duis in faucibus quam. Praesent facilisis vitae nulla in suscipit. Praesent porta sapien cursus odio rhoncus commodo. Maecenas ac magna vel velit finibus sagittis sed nec tortor.
	</div>
	<div id="btn-expand-container">
		<span class="txt-readmore">Read More</span>
		<span class="txt-readless" style="display: none;">Close</span>
	</div>
</body>
</html>
  • Load jQuery library into the page.
  • Set 2 DIV, one for content, another one act as a container for Read more / Close button

Step 2: Set the CSS styles

<style>
	body {
		width: 320px;
	}
	#content {
	    display: -webkit-box;
	    -webkit-box-orient: vertical;
	    -webkit-line-clamp: 3;
	    overflow: hidden;
	}
	#content.reveal-all {
	    display: block;
	}
	#btn-expand-container {
		margin-top: 12px;
		text-align: right;
	}
	#btn-expand-container button {
		cursor: pointer;
	}
</style>

We could ignore the styles for body and #btn-expand-container, as the styles that we defined for both elements are just for demonstration purpose.

We just need to take note on these 2 classes: #content, #content.reveal-all

  • For #content class, we’ve set it to only display maximum 3 lines of content using -webkit-line-clamp property. If the content is overflowing, an ellipsis will be shown at the point where the content is clamped. To learn more line-clamp, please read Truncate Multiple Line With CSS
  • For #content.reveal-all class, we’ve set the display property value to block, to instruct browser to forget about -webkit-line-clamp property.

Step 3: Detect is content overflow

$(document).ready(function() {
	function detectIsOverflow(element) {
		return element.scrollHeight > element.clientHeight
	}
	var is_content_overflow = detectIsOverflow($('#content')[0]);
});

Create a function called detectIsOverflow(element) to detect is the content in the #content DIV overflow. It will return a Boolean: true if the content is overflowing, and false if it is not.

Step 4: Show / Hide Read More button

$(document).ready(function() {
	function detectIsOverflow(element) {
		return element.scrollHeight > element.clientHeight
	}
	function enableReadMoreButton(condition, element) {
		if(condition == true) {
			element.show();
		} else {
			element.hide();
		}
	}
	var is_content_overflow = detectIsOverflow($('#content')[0]);
	enableReadMoreButton(is_content_overflow, $('#btn-expand-container'));
});

Create a function called enableReadMoreButton(condition, element). This function receives 2 arguments: condition and element. We use these 2 arguments to toggle the visibility of the Read more button:

  • We passed in the variable: is_content_overflow as a argument of condition into the enableReadMoreButton() function, and $(‘#btn-expand-container’) as second argument.
  • If the first argument’s value is true, the element (the Read More button) will be displayed, else the element will be hidden.

Step 5: Set the interactivity of Read More button

$(document).ready(function() {
	function detectIsOverflow(element) {
		return element.scrollHeight > element.clientHeight
	}
	function enableReadMoreButton(condition, element) {
		if(condition == true) {
			element.show();
		} else {
			element.hide();
		}
	}
	function toggleReadCloseText(parent, element_readmore, element_close) {
		if(element_readmore.is(":visible")) {
			parent.addClass('reveal-all');
			element_readmore.hide();
			element_close.show();
		} else {
			parent.removeClass('reveal-all');
			element_readmore.show();
			element_close.hide();
		}
	}
	var is_content_overflow = detectIsOverflow($('#content')[0]);
	enableReadMoreButton(is_content_overflow, $('#btn-expand-container'));
	$('#btn-expand-container button').on('click', function() {
		toggleReadCloseText($('#content'), $('.txt-readmore'), $('.txt-readless'));
	});
});

Create a function called toggleReadCloseText(parent, element_readmore, element_close). This function receives 3 arguments:

  • parent: The content container #content
  • element_readmore: Read more button’s text element .txt-readmore
  • element_close: Close button’s text element .txt-readless

Then triggers toggleReadCloseText() function on every click event of Read More button.

Conclusion

In this article, we explored a powerful and efficient way to manage content overflow in web development using JavaScript and CSS’s line-clamp property. By combining these technologies, we can effectively detect when an HTML element has more content than can be displayed, truncate the content with an ellipsis (), and give users a clean, intuitive way to expand the content via a “Read More” button.

This technique offers several significant advantages. First, it improves the visual presentation of your content, making your pages look more organized and user-friendly, particularly when dealing with lengthy text or dynamic content. Second, it enhances performance by avoiding the need to load large amounts of content all at once, which can contribute to faster page load times and a more seamless browsing experience. By truncating the content initially and loading it only when the user interacts, you can create a more responsive and engaging user interface.

By using CSS’s line-clamp property, we can easily control how many lines of text are visible before truncating, without needing to worry about complex calculations or additional layout adjustments. Pairing this with JavaScript allows you to dynamically detect content length, offering a highly flexible solution to meet various design and functional requirements. The inclusion of a “Read More” button ensures that users have the control to access the full content when they wish, making the interaction both efficient and satisfying.

Whether you are building blogs, product descriptions, or dynamic content interfaces, this approach can be seamlessly integrated into your projects to improve both functionality and user experience. It allows for a clean design without sacrificing accessibility or usability. Moreover, with the growing emphasis on responsive web design, this solution works well across different devices, ensuring that your content looks great whether viewed on a mobile device, tablet, or desktop.

In conclusion, the combination of JavaScript and CSS’s line-clamp property provides a simple yet effective solution for handling overflow content and improving content display. By truncating text with ellipsis and offering a “Read More” feature, you not only improve the aesthetic and usability of your website but also optimize performance, keeping your content manageable and engaging. Implementing these techniques in your projects can lead to a more polished, user-friendly experience and, ultimately, more satisfied users.

Follow onlyWebPro.com on Facebook now for latest web development tutorials & tips updates!


Posted

in

by

Post’s tag:

Advertisement