Read more Read less buttons come handy when you want to hide additional information while still providing the visitors with a glimpse of what the article or post is about.
You may have Multiple posts or paragraphs where you might want to use these buttons. But writing separate code for each button seems to be very time-consuming. It might also affect the performance of your website.
In today’s tutorial, we create a Read More Read Less button for multiple paragraphs with minimum lines of code. We will be using jQuery to implement the button. So before we move to the actual coding, let us quickly copy-paste the code snippet below in the head section of our code.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
This is the jQuery CDN.
HTML:
<div class="post">
<h1>Post title 1</h1>
Lorem ipsum dolor sit amet, ne sed idque quidam. Vim assum corpora an Pro ut erat consetetur, vocent expetendis sit at. Posse populo no usu
<span class="dots">...</span>
<span class="more">
Pro ut erat consetetur, vocent expetendis sit at. Posse populo no usu, nam elit postea nusquam id.
</span>
<button class="read">read more</button>
</div>
CSS:
body{
background-color: #0f2e51;
padding: 0;
margin: 0;
}
section{
padding: 20px;
}
h1{
margin: 0 0 15px 0;
color: white;
font-size: 28px;
font-weight: 700;
font-family: 'Poppins',sans-serif;
text-transform: uppercase;
letter-spacing: 1.2px;
}
.more{
display: none;
}
.post{
color: #e5e5e5;
font-size: 18px;
text-align: justify;
line-height: 25px;
font-family: 'Work Sans',sans-serif;
}
.post:not(:last-child){
margin-bottom: 30px;
}
button{
margin-top: 15px;
display: block;
background-color: #e41d3f;
color: white;
border:none;
outline: none;
padding: 8px 20px;
text-transform: capitalize;
cursor: pointer;
font-size: 20px;
}
jQuery:
$(document).ready(function(){
$(".read").click(function(){
$(this).prev().toggle();
$(this).siblings('.dots').toggle();
if($(this).text()=='read more'){
$(this).text('read less');
}
else{
$(this).text('read more');
}
});
});
I hope you find this useful. You can download the source code or watch a preview of code in action below. If you have any suggestions and feedback to let me know through the comments. Also to stay updated with the latest tutorials and resources, subscribe to me on Youtube.
I couldn’t resist commenting. Perfectly written!
have a doubt, i am trying to use it but inside my divs works backwards, and outside my divs works perfect, idk what am I doing wrong
Awesome!! This helps a lot, thanks
great
This doesnt work at all. Button is hidden by default and after click it hide elements instead show.
Didn’t work for me at all. Showed the whole text with the read more button at the bottom and when you click on it all the text disappears. Disappointed.