Coder Social home page Coder Social logo

reading-time's Introduction

Reading Time

CDNJS

Inspired by Medium, Reading Time is a simple, lightweight jQuery plugin used to display an estimated time to read some text.

See a demo

See a demo using a remote file

See a demo using multiple remote files

Instructions

Include jQuery and the plugin in the head or footer of your page.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script src="/js/plugins/readingtime.js"></script>

Create an element with the class of 'eta' where the estimated reading time will display.

<article>
	<div class="eta"></div>
</article>

Optionally you can also create an element with whatever class or ID you want to display the total word count.

The word count will only be displayed if you set the wordCountTarget parameter when initiating the plugin (see below).

<article>
	<div class="eta"></div>
	<div class="word-count"></div>
</article>

Initialize the plugin targeting the class, ID or element that contains the text in which you want to estimate the reading time of.

$('article').readingTime();

Options

  1. readingTimeAsNumber: boolean
    If you want to take reading time as integer, you can use this (default: 'false').
  2. readingTimeTarget: "id / class / element"
    A string that defines the ID, class or element that will store the estimated reading time (default: 'eta').
  3. wordCountTarget: "id / class / element"
    A string that defines the ID, class or element that will store the total word count (default: '').
  4. remotePath: "path"
    A string that indicates the path to the remote file (default: null).
  5. remoteTarget: "id / class / element"
    A string that defines the ID, class or element in the remote file that contains the text in which you want to estimate the reading time of (default: null).
  6. wordsPerMinute: integer
    An integer that defines the words per minute at which to calculate the estimated reading time (default: 270).
  7. round: boolean
    A boolean value that indicates whether or not the estimated reading time should be rounded to the closest minute (default: true).
  8. lang: "en / fr / de / es / nl / sk / cz / ru / zh / kr"
    A two letter string that indicates the language to be used (default: "en").
  9. lessThanAMinuteString: string
    A string that changes the default "Less than a minute" copy (default: '').
  10. prependTimeString: string
    A string that is prepended before the estimated reading time (default: '').
  11. prependWordString: string
    A string that is prepended before the total word count (default: '').
  12. success: function(data) {}
    A callback function that runs if the plugin was successful (default: `function()`).
  13. error: function(data) {}
    A callback function that runs if the plugin fails (default: `function(message)`).
Example:
$(function() {

	$('article').readingTime({
		readingTimeAsNumber: true,
		readingTimeTarget: $('.reading-time'),
		wordsPerMinute: 275,
		round: false,
		lang: 'fr',
		success: function(data) {
			console.log(data);
		},
		error: function(data) {
			console.log(data.error);
			$('.reading-time').remove();
		}
	});
});
Multiple Articles

Often you will have multiple articles or excerpts on a single page, in which case you would want to iterate through each.

$('article').each(function() {

	let _this = $(this);

	_this.readingTime({
		readingTimeTarget: _this.find('.reading-time')
	});
});
Using a Remote File

If you want to display the estimated reading time of copy that lives in a remote file, you would initialize the plugin and use the remotePath and remoteTarget options.

In this case, the plugin would display the amount of text contained in the element with the class of "my-article" in the file called "remote.html."

$('article').readingTime({
	remotePath: 'path/to/remote/file.html',
	remoteTarget: '.my-article'
});

See a demo using a remote file

Using Multiple Remote Files

If you want to display the estimated reading time of copy for multiple articles that live in remote files, you would want to iterate through each article on your page and use data attributes to declare the file and target for each article. Be sure to initialize the plugin on the body and use the remotePath and remoteTarget options.

Here is what your markup might look like (notice the data-file and data-target attributes on each article):

<!-- first article excerpt -->
<article data-file="articles/a.html" data-target="article">

	<h1>Magna Lorem Quam Nullam</h1>

	<p>By: Mike Lynch</p>

	<!-- reading time and word count -->
	<p><span class="eta"></span> (<span class="words"></span> words)</p>

	<p>Nullam id dolor id nibh ultricies vehicula ut id elit. Curabitur blandit tempus porttitor. Nulla vitae elit libero, a pharetra augue. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

	<a href="articles/a.html" class="btn">Read more</a>

</article>

<!-- second article excerpt -->
<article data-file="articles/b.html" data-target="article">

	<h1>Justo Cursus Inceptos Ipsum</h1>

	<p>By: Mike Lynch</p>

	<!-- reading time and word count -->
	<p><span class="eta"></span> (<span class="words"></span> words)</p>

	<p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Aenean
	lacinia bibendum nulla sed consectetur. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>

	<a href="articles/b.html" class="btn">Read more</a>

</article>

<!-- third article excerpt -->
<article data-file="articles/c.html" data-target="article">

	<h1>Sem Vehicula Dapibus Malesuada</h1>

	<p>By: Mike Lynch</p>

	<!-- reading time and word count -->
	<p><span class="eta"></span> (<span class="words"></span> words)</p>

	<p>Nullam quis risus eget urna mollis ornare vel eu leo. Nulla vitae elit libero, a pharetra augue. Maecenas faucibus mollis interdum. Nullam id dolor id nibh
	ultricies vehicula ut id elit. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>

	<a href="articles/c.html" class="btn">Read more</a>

</article>

Here is what your JS would look like:

$('article').each(function() {

	let _this = $(this);

	_this.readingTime({
		readingTimeTarget: _this.find('.eta'),
		wordCountTarget: _this.find('.words'),
		remotePath: _this.attr('data-file'),
		remoteTarget: _this.attr('data-target')
	});
});

See a demo using multiple remote files

reading-time's People

Contributors

127001 avatar andy00087 avatar blackskorpio avatar brunoew avatar dimayakovlev avatar extempl avatar fpshu avatar jeancarlozapata avatar kaocy avatar liqianggh avatar michael-lynch avatar midoalone avatar shanepark avatar stevelacey avatar takvol avatar thierrymichel avatar whitfin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reading-time's Issues

IE11 Problem

Message: Object doesn't support this property or method

Problem: wrong single quote character being used.

Fix
`
should be
'

Translation

Can we have the texts ("Less than a minute", "Min") in the default setting so they can be easily translated ? Or another solution ?

Thx

Not working on IE

I just want to note that the new plugin version is not working on IE because template literals are not supported on IE:

readingTime = ${readingTimeMinutes}:${readingTimeSeconds};

Not displaying on certain pages

Hi,

I am getting this error in console on some pages and this causes no reading time value in the eta div. Also, the scripts that are supposed to execute after reading time is invoked, they won't load most of the time and break the page layout. On simples pages it just works fine. Any clue, what is this error about?

image

-Amit

Support Chinese

use the regular expression of JavaScript to process the text

1.count the number of Chinese characters;
2.replace the Chinese and special characters with space;
3.split text by spaces to define total words.

Only works with article

If I try to use it on any other part besides the article, it doesn't work. For example, my markup looks sorta like this:

HTML:

<article class="article">
    <div class="post-header" />
    <div class="post-body" />
    <div class="post-footer" />
</article>

JQUERY

    $('.post-body').each(function() {
            let _this = $(this);
            _this.readingTime({
              readingTimeTarget: _this.find('.read-time'),
              wordCountTarget: _this.find('.word-count')
            });
          })

This doesn't work, but if I use $('.article'), then it does.

Languages like Chinese, Japanese, Vietnamese are not separated by blanks

The current implementation depends on counting the length of the array after separating texts by white spaces. While this will work for most Indo-European languages, text in some other languages, notably Chinese and Japanese, would fail to be counted.

Concretely, the world count for 你好,世界 is expected to be 5 (or 4 if the comma is ignored), but the current code returns 1.

Is it possible to add one more option for the user to specify whether to split or not before counting?

Problem if "wordCountTarget" is not in the selected tag.

`Hi,

Example :

<article>
        <p id="estimated-reading-time"><span class="reading-time"></span> (<span class="word-count"></span> words)</p>
    <p>Earlier this year</p>
    <p>Earlier this year</p>
    <p>Earlier this year</p>
</article>

The result is 9.

But...

<p id="estimated-reading-time"><span class="reading-time"></span> (<span class="word-count"></span> words)</p>

<article>
    <p>Earlier this year</p>
    <p>Earlier this year</p>
    <p>Earlier this year</p>
</article>

The result is 7. Also in this case, the white spaces are considered as words and readingTimeTarget does not work.

I use a CMS and it's easier if wordCountTarget is not necessarily in the selected tag... Is this can be changed ?

Looping through multiple remote articles?

Hello,

Is there a method you'd recommend for including multiple read estimates for multiple remote articles in a blog list? My skills in this area are shaky so I appreciate your input.

Thanks in advance,
LB

Bug: Target for remote files

There appears to be a bug with remote targets for multiple file references:

If the target is wrapped in any divs whatsoever inside the remote file, the script is unable to extract the read time estimate properly and outputs "Less than a minute (1 word)".

Thanks

readingTimeTarget anywhere

I ran into two issues while using this otherwise awesome plugin:

First, it looks like we are unable to target a class anywhere we want in the page with readingTimeTarget. It has to be within the targeted article. This has serious limitations if we have a specific design and while we can move the span around on success via jquery, it is not ideal.

Second, it would be nice to have an option to return only the number of minutes, without "min" appended to it. Better yet, two append options (singular/plural), but it may overcomplicate...

IE8 Problem

Hi, i get this error on console on I8. Is it possible to make this plugin compatible with IE8 ?

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
Timestamp: Fri, 4 Jul 2014 19:14:57 UTC

Message: Object doesn't support this property or method
Line: 12
Char: 999
Code: 0
URI: http://michael-lynch.github.io/reading-time/js/readingTime.min.js

Bower

Hey, it would be great if this plugin would be available through Bower. If you're familiar with it, please create a bower.json and publish it.

Thanks :)

Reading time for chinese language alwas show "less than a minute"

I am building multilingual website. The website has 3 languages, there are English, Bahasa Indonesia, and Chinese. The plugin seems working fine with English and Bahasa Indonesia language setting, but when using Chinese language setting it always show "less than a minute". Any idea how to fix this?

"each" method doesn't work with laravel foreach

I tried to use it with laravel in foreach, i want it to be displayed on every post, but it take only the last post in foreach loop and add the time & word-count to all other posts,
foreach
<div class="hidden" id="articleDesc">{{ $relatedPost->description }}</div>
<span class="eta"></span>
<span class="word-count"></span>
endforeach
$(function() {
$('#articleDesc').each(function() {
$(this).readingTime({
readingTimeTarget: '.eta',
wordCountTarget: '.word-count',
});
});
});

ReadingTimeTarget selector

This plugin assumes the reading time target is a descendant of the initialization element. Which is not the always case.

Example: I have my reading time target in the header of my page, while the actual article is in the main section of my page. With these settings it's impossible to use this plugin.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.