Making a 'Read More' Link Simply with Alpine.js
For those of us working with websites, we’ve probably come across big names like React, Vue, or Angular. These are tools that help us make our websites more interactive. Today, though, let’s chat about a lesser-known but very simple tool called Alpine.js.
We’ll look at how to make a ‘Read More’ link using Alpine.js. This is a common feature you see on websites where a short preview of text is shown, and you can click a link to see the rest of it.
Here’s our starting code:
<div
x-data="{ isCollapsed: false, maxLength: 300, originalContent: '', content: '' }"
x-init="originalContent = $el.firstElementChild.textContent.trim(); content = originalContent.slice(0, maxLength)">
<p x-text="isCollapsed ? originalContent : content">
Some long text..
</p>
<button @click="isCollapsed = !isCollapsed"
x-show="originalContent.length > maxLength"
x-text="isCollapsed ? 'Hide' : 'Show more'">
</button>
</div>
This bit of code helps us limit how much of our content shows on the screen and gives us a button to either show everything or go back to the short preview.
Let’s break it down:
- We start with a
div
tag withx-data
andx-init
. Thex-data
attribute lets us declare the rules for our ‘Read More’ feature. We haveisCollapsed
which tells us whether the content is currently hidden or not,maxLength
which is the maximum length of the preview, andoriginalContent
andcontent
to hold the full text and the preview text. - The
x-init
attribute sets up our initial state. In our case,originalContent
starts off as the full text that we want to display. content starts off as the preview, or the first 300 characters oforiginalContent
. - The
p
tag includesx-text
, which helps us switch between showing the full text or the preview based on whetherisCollapsed
is true or false. - The button tag includes
@click
to switchisCollapsed
from true to false or vice versa every time the button is clicked. Thex-show
attribute makes sure the button is only visible if the text is long enough to be shortened. Finally,x-text
changes the button text based on whether the text is collapsed or not.
And that’s it! With just these few lines of code and Alpine.js, we can create a ‘Read More’ link. This is a great example of how useful and simple Alpine.js can be. It’s a great tool for when you need a little bit of interactivity on your website but don’t want to pull in a bigger tool.