A “Read More” feature is a nice way of displaying a glimpse of some content which can be fully revealed by clicking a link. Let’s see how to create a simple Read More feature for you content using JQuery.
See here the end result of this tutorial:
See the Pen Simple "Read More" Feature by WebTutorialSource (@webtutorialsource) on CodePen.
Why Use Read More Feature?
It may be a good idea sometimes to use a Read More link when you have a long section with lot of reading. This gives the user the option to display the rest of the content only if he’s interested in finding out more. In addition, it offers a better user experience and makes your page not so lengthy if you already have a lot of content.
Preparing Our HTML
I tried to make it as simple as possible so it’s very easy to setup. So all you have to do in your HTML is add a <div class="read-more">
tag around the content you want to hide.
<p>My visible content here...</p>
<div class="read-more">
<p>Here is the hidden content...</p>
</div>
Adding Some JQuery
As I want this feature to require a minimum setup, I need to rely more on JavaScript to make it work.
<script>
jQuery(function($) {
var elem = $(".read-more");
elem.each(function() {
$(this).wrapInner( "<div class='hide' style='display:none' />");
});
elem.append("<a href='#' class='read-more--button'>Read More</a>");
$(document).on('click', 'a.read-more--button', function(e) {
var $this = $(this);
$this.parent('.read-more').find('.hide').slideDown();
$this.hide();
e.preventDefault();
});
});
</script>
In the .each()
loop, I add a wrapper around the content found inside the .read-more
container in order to allow more control.
You can add as many paragraphs (or other tags) as you need or even an image without any issues.
The Read More link is dynamicaly inserted right after our wrapper using the JQuery method .append()
I hope you enjoyed this short tutorial and I wish you all the best for the new coming year.