Member-only story
When browsing through a website, most people want to get to the meat of the site, especially when they are shopping. This week I had to shorten the collection’s description after 3 lines of text on mobile devices because it was taking way too much space and none of the products showed on the screen on load.
After some googling, I found a “line clamp” property which allows you to truncate after a certain number of lines of text.
The implementation I took was the following:
On load, there is already the class “truncate-text” which shortens the text already.
On click of the “Read More” button, remove the “truncate-text” class and the button text changes to “Read Less”.
When the “Read Less” button is clicked, then the “truncate-text” class will be added.
In the JavaScript, first I created a variable to find the toggle button for “Read More” or “Read Less”.
Then add a ‘click’ event listener to that variable. Then I created a condition that if the class “truncate-text” exists, on the click, we remove the class “truncate-text” and also change the button innerText to “Read Less”, else the click event would add the “truncate-text” class and change the button innerText to “Read More”.
Here’s a link to my codepen to see it in action: https://codepen.io/jaywen/pen/QWaMvbz
I hope this explanation was clear and helps someone!