A while back I wrote a simple Read More / Read Less JS package, called ReadMore.js
I’ve been meaning to overhaul the lib for a while, and finally got around to pushing v2. The api has been refactored, new features added, and it’s now a hybrid npm module that supports import
and require
. Oh, and since read-more was already taken on npm, I renamed the module to (ReadSmore) ccread-smore and updated the export / namespace.
New features
- Super lightweight, with no dependencies. Just vanilla JavaScript.
- Renamed default namespace to ReadSmore
- Supports truncating content by max Word or Character count.
- Uses data attributes to control max words/characters count within content/markup.
- Adds ellipse after truncated content.
- Preserves existing markup (nice).
- Read more / Read less text is customizable.
- The block level class name is customizable
- Read More text can be block level or inline via provided css
- Hybrid NPM Module supporting
import
andrequire
Install (via npm)
npm i read-smore
Usage
Add to your project
import ReadSmore from 'read-smore'
// target all read smore elements
const readMores = document.querySelectorAll('.js-read-smore')
// init
ReadSmore(readMores).init()
Or by require
const ReadSmore = require('read-smore')
const readMores = document.querySelectorAll('.js-read-smore')
ReadSmore(readMores).init()
Example by max word count
To truncate content by max word count, use the data attribute data-read-smore-words=""
with desired value.
<div
class="js-read-smore"
data-read-smore-words="70"
>
<p>Stuff and words and stuff and words.</p>
<p>Words and stuff and words and stuff.</p>
<!-- more HTML content -->
</div>
Example by max character count
To truncate content by max character count, use the data attribute data-read-smore-chars=""
with desired value.
<div
class="js-read-smore"
data-read-smore-chars="150"
>
<p>Stuff and words and stuff and words.</p>
<p>Words and stuff and words and stuff.</p>
<!-- more HTML content -->
</div>
Provide Options
ReadSmore supports a few options, such as editing the more/less text.
import ReadSmore from 'read-smore'
const readMores = document.querySelectorAll('.js-read-smore')
const options = {
blockClassName: 'read-more',
moreText: 'Custom more text',
lessText: 'Custom less text'
}
ReadSmore(readMores, options).init()
Check the ReadMe or Docs/Demo site for full table of options.
Inline Read more
By default the Read more text sits below the content block. However, you can make it inlined with the truncated text by importing the provided css:
@import 'read-more/read-more.css
Then provide the the data-attribute data-read-smore-inline="true"
<div
class="js-read-smore"
data-read-smore-words="70"
data-read-smore-inline="true">
</div>
ToDos
- Add a destroy method.
- Add custom events or callbacks for when active / inactive.
- Add some legit tests
Github
You can go check the code of ReadSmore.js on the Githubs, Right Here.