Chart.js plugin to defer initial chart updates

Overview

github travis codeclimate

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart animations when the user is likely to see them.

Requires Chart.js 3.x.

Documentation

Example

new Chart(ctx, {
  // ... data ...
  options: {
    // ... other options ...
    plugins: {
      deferred: {
        xOffset: 150,   // defer until 150px of the canvas width are inside the viewport
        yOffset: '50%', // defer until 50% of the canvas height are inside the viewport
        delay: 500      // delay of 500 ms after the canvas is considered inside the viewport
      }
    }
  }
});

Development

You first need to install node dependencies (requires Node.js):

> npm install

The following commands will then be available from the repository root:

> npm run build             // build dist files
> npm run build:dev         // build and watch for changes
> npm run lint              // perform code linting
> npm run lint -- --fix     // automatically fix linting problems
> npm run docs              // generate documentation (`dist/docs`)
> npm run docs:dev          // generate documentation and watch for changes
> npm run package           // create tgz and zip archives with dist files

License

chartjs-plugin-deferred is available under the MIT license.

Comments
  • Unable to es6 import plugin

    Unable to es6 import plugin

    I'm using ChartJS in my Aurelia app and it works fine. I wanted to add the deferred plugin so I've npm installed it and added the import like so:

    import Chart from 'chartjs';
    import 'chartjs-plugin-deferred';
    

    The package imports properly but the code throws errors: Uncaught TypeError: Cannot read property 'helpers' of undefined.

    My guess is it's because the plugin is trying to access the Chart object which I assume isn't global?

    (The first few lines of code try to do the following):

    var Chart = window.Chart;
    var helpers = Chart.helpers;
    

    I'm honestly a little new to using import (as opposed to just stacking <script> elements) so I might be doing something wrong, but I'd love to know what?

    Edit:After further testing the plugin actually seems to work properly, but I still get that error in the console which is really annoying. Any idea what could cause it?

    enhancement resolved 
    opened by powerbuoy 28
  • Doesn't work with fullPage.js

    Doesn't work with fullPage.js

    This plugin looks great! But as soon as I included chartjs-plugin-deferred.min.js, all of my existing charts stopped working. Could someone please provide workaround or fix for this issue?

    resolved support 
    opened by newUserForTesting 8
  • Add method to remove event listeners/cleanup

    Add method to remove event listeners/cleanup

    I really don't mean to spam you :)

    But while using the deferred plugin on my Aurelia SPA I've noticed that unless you view every chart on a page (at which point the plugin unwatches the chart's scroll event https://github.com/chartjs/chartjs-plugin-deferred/blob/master/src/plugin.js#L107); if you go to another page and scroll down you'll get Uncaught TypeError: Cannot read property 'offsetParent' of null from chartInViewport() (https://github.com/chartjs/chartjs-plugin-deferred/blob/master/src/plugin.js#L53 I believe).

    I might be missing something, but is there a way to manually remove the events? That way I can do so in my ViewModel's detached() (or React's componentWillUnmount()) similarly to how I can destroy the ChartJS instance with chart.destroy()?

    Or perhaps there's a way for the plugin itself to detect calls to chart.destroy() and clean up after itself?

    Again, sorry if I simply missed this feature or am using the plugin incorrectly, all I've done is import it and add the deferred options to my chart.

    bug resolved 
    opened by powerbuoy 7
  • Deferred update causes an uncaught error if `canvas` is destroyed

    Deferred update causes an uncaught error if `canvas` is destroyed

    It happens sometimes that canvas element and ctx are no longer exist during a deferred update. This causes errors like Cannot read property 'save' of null. To reproduce this behavior we have to construct a new chart and kill canvas before the delay is expired (e.g. when you navigate from one page to another without waiting for all charts to be rendered completely, including delayed updates).

    Screenshot 2019-12-20 at 10 06 31 Screenshot 2019-12-20 at 10 06 48

    bug resolved 
    opened by BR0kEN- 6
  • Impossible to configure the plugin

    Impossible to configure the plugin

    Hi,

    Can someone spot the mistake in this, the 10 seconds delay is not working, neither the yOffset, actually nothing works. The plugin is working, it renders the charts as soon as the first pixel is in the viewport, but impossible to configure it.

    Thank you

                      options: {
    			legend: {
    				display: false
    			},
    			tooltips: {
    				callbacks: {
    					label: function(tooltipItem, data) {
    						var allData = data.datasets[tooltipItem.datasetIndex].data;
    						var tooltipLabel = data.labels[tooltipItem.index];
    						var tooltipData = allData[tooltipItem.index];
    						var total = 0;
    						for (var i in allData) {
    							total += allData[i];
    						}
    						var tooltipPercentage = Math.round((tooltipData / total) * 100);
    						//return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
    						return tooltipLabel + ': ' + tooltipData + '%';
    					}
    				}
    			},
    			plugins: {
    				deferred: {           // enabled by default
    					enabled: true,
    					xOffset: 150,     // defer until 150px of the canvas width are inside the viewport
    					yOffset: '500%',   // defer until 50% of the canvas height are inside the viewport
    					delay: 10000        // delay of 500 ms after the canvas is considered inside the viewport
    				}
    			}
    		}
    resolved infrastructure 
    opened by romain-granai 6
  • Uncaught TypeError: Cannot read property 'ticking'

    Uncaught TypeError: Cannot read property 'ticking'

    chartjs-plugin-deferred.min.js:10 Uncaught TypeError: Cannot read property 'ticking' of undefined at HTMLDocument.a (chartjs-plugin-deferred.min.js:10)

    I'm getting this error in Chrome. Plugin version: 0.3.0. Chart.js version: 2.7.0 jQuery version: 3.2.1

    I'm not that experienced with JS, but please let me know if I need to provide more information.

    invalid 
    opened by NoLooseEnds 6
  • Uncaught TypeError: Cannot read property 'plugins' of undefined

    Uncaught TypeError: Cannot read property 'plugins' of undefined

    When I'm trying to use the plugin I'm always getting the error:

    Uncaught TypeError: Cannot read property 'plugins' of undefined

    I'm using

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-deferred.min.js"></script>

    and

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>

    Here's a fiddle that illustrates the error https://jsfiddle.net/aqgst865/

    support 
    opened by jakobgreenfeld 3
  • Error with global options

    Error with global options

    I was hoping to set some global deferred options with Chart.defaults.global.plugins.deferred, but it seems to be undefined.

    Chart.js (v2.7.0) chartjs-plugin-deferred (v0.3.0)

    resolved infrastructure 
    opened by FlyingLooper 3
  •  Uncaught TypeError: e.defaults.global is undefined

    Uncaught TypeError: e.defaults.global is undefined

    Hi,

    First of all thank you very much for ChartJs, it's a great tool that I've been using for more than 10 years.

    FYI, I have an error using the compiled and downloaded version at https://github.com/chartjs/chartjs-plugin-deferred/releases/download/v1.0.2/chartjs-plugin-deferred.min.js: "Uncaught TypeError: e.defaults.global is undefined" This error disappears if I use it from the sources : "git clone ... > npm install > npm build ..."

    Thanks again.

    • Chart.js v3.7.0
    • chartjs-plugin-deferred v1.0.2
    • chartjs-plugin-datalabels v2.0.0
    support 
    opened by paglop 2
  • TypeError: Cannot set property 'font' of null

    TypeError: Cannot set property 'font' of null

    Having issue when installed the deferred plugin and inserted as

    Chart.defaults.global.defaultFontFamily = "'Nunito Sans', sans-serif";
    
     
    chartObj = new Chart(refChart, {
            type: chartType,
            data: {
              labels: chartLabels,
              datasets: chartDataset,
            },
            plugins: [
              ChartColorSchemes,
              ChartDeferred,
            ],
            options: _merge({
              plugins: {
                colorschemes: {
                  scheme: "office.Breeze6",
                  custom: customColorSchema,
                  fillAlpha: 1,
                },
                deferred: {
                  xOffset: 150,
                  yOffset: "50%",
                  delay: 500,
                },
              },
            }, chartOptions),
          });
    

    chart.js version is 2.9.3 deferred plugin version is 1.0.1

    image

    any clue how to solve it?

    duplicate resolved 
    opened by gyto23 2
  • Having trouble getting plugin working inside of Vue.js

    Having trouble getting plugin working inside of Vue.js

    I can't seem to get this plugin working inside a Vuejs environment on my local computer. I'm using Chartjs 2.7.2, vue-chartjs 3.4.0, vue 2.5.17, and chartist-plugin-deferred 1.0.1

    I did successfully get it to work inside of Vuejs in a jsfiddle: https://jsfiddle.net/amfischer/eywraw8t/320627/

    Here is a simplified repo of the fiddle, and can't for the life of me figure this out: https://github.com/amfische/vue-chartjs-plugin-deferred

    I would greatly appreciate any help.

    support 
    opened by amfischer 2
  • ERR_PACKAGE_PATH_NOT_EXPORTED Server error

    ERR_PACKAGE_PATH_NOT_EXPORTED Server error

    Version:

    ├── [email protected]
    ├── [email protected]
    

    Stacktrace

    Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './helpers' is not defined by "exports" in /Users/doris/src/node_modules/chart.js/package.json
        at new NodeError (node:internal/errors:371:5)
        at throwExportsNotFound (node:internal/modules/esm/resolve:429:9)
        at packageExportsResolve (node:internal/modules/esm/resolve:638:7)
        at resolveExports (node:internal/modules/cjs/loader:482:36)
        at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
        at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
        at Function.Module._load (node:internal/modules/cjs/loader:778:27)
        at Module.require (node:internal/modules/cjs/loader:999:19)
        at require (node:internal/modules/cjs/helpers:102:18)
        at /Users/doris/src/node_modules/chartjs-plugin-deferred/dist/chartjs-plugin-deferred.js:8:89 {
      code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
    }
    

    I think it's the same issues reported in other chartjs plugins: https://github.com/chartjs/chartjs-plugin-annotation/issues/819 https://github.com/chartjs/chartjs-plugin-zoom/issues/709

    opened by dorisip 1
  • Additional Index to Draw Count

    Additional Index to Draw Count

    The _drawCount seems increase the value +1 from what the array length is. The array length is 29 but _drawCount has a value of 30 which creates an undefined for when deferred looks at element.hidden. It also seems like it had the proper count and then on another render the increase happened. Taking out Deferred takes away the issue. What could be the possible cause of the plugin adding an additional index? (I am using React and react-chartjs-2)

    image image image
    opened by jesseagleboy 0
  • Add support for an inView callbaack

    Add support for an inView callbaack

    I have a need to be able to set a state var once the chart is in view and the animation has started. Unfortunately I cannot rely solely on the events from the chart, I am using onComplete, but in adding this plugin, onComplete is immediately fired on startup, even if the chart isn't in view, which causes problems for me. I have yet to determine why onComplete is firing. Long story short, it would be helpful to have a callback/event like inView that fires once the chart scrolls into view. This would allow me to ignore the onComplete events until after this callback event happens.

    opened by mloit 1
Releases(v2.0.0)
Owner
Chart.js
Simple, clean and engaging charts for designers and developers
Chart.js
A Simple Dashboard Chart in Laravel Nova using Chart JS

A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

Kuncoro Wicaksono 177 Jan 4, 2023
Bar Funnel Chart extension for Chart.js

Chart.BarFunnel.js Provides a Bar Funnel Chart for use with Chart.js Documentation To create a Bar Funnel Chart, include Chart.BarFunnel.js after Char

Chart.js 58 Nov 24, 2022
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 24 Dec 12, 2022
Zoom and pan plugin for Chart.js

chartjs-plugin-zoom A zoom and pan plugin for Chart.js >= 3.0.0 For Chart.js 2.6.0 to 2.9.x support, use version 0.7.7 of this plugin. Panning can be

Chart.js 510 Jan 2, 2023
Chart.js plugin for more styling options

chartjs-plugin-style Chart.js plugin for more styling options This plugin requires Chart.js 2.6.0 or later. Installation You can download the latest v

Akihiko Kusanagi 57 Oct 27, 2022
Chart.js plugin for live streaming data

chartjs-plugin-streaming Chart.js plugin for live streaming data chartjs-plugin-streaming 2.x requires Chart.js 3.0.0 or later. If you need Chart.js 2

Akihiko Kusanagi 401 Dec 27, 2022
Chart.js plugin to create charts with a hand-drawn, sketchy, appearance

chartjs-plugin-rough Chart.js plugin to create charts with a hand-drawn, sketchy, appearance Version 0.2 requires Chart.js 2.7.0 or later, and Rough.j

Akihiko Kusanagi 73 Dec 1, 2022
Chart.js plugin to calculate and draw statistical linear, exponential, power, logarithmic, and polynomial regressions.

chartjs-plugin-regression Chart.js plugin to calculate and draw statistical linear, exponential, power, logarithmic, and polynomial regressions using

Wilfredo Pomier 14 Dec 18, 2022
Draggable data points plugin for Chart.js

chartjs-plugin-dragdata.js Now compatible with Chart.js v3 ?? Looking for a version compatible to Chart.js < 2.9.x? Then visit the v2 branch! A plugin

Christoph Pahmeyer 196 Dec 18, 2022
Chart.js plugin for Prometheus data loading

Welcome to chartjs-plugin-datasource-prometheus ?? A Prometheus datasource for ChartJS. Dependencies: requires chart.js 2.7 or later. requires moment.

Samuel Berthe 77 Dec 6, 2022
Chart.js plugin to display labels on data elements

Overview Highly customizable Chart.js plugin that displays labels on data for any type of charts. Requires Chart.js 3.x. Documentation Introduction Ge

Chart.js 753 Dec 24, 2022
Annotation plugin for Chart.js

chartjs-plugin-annotation.js An annotation plugin for Chart.js >= 3.0.0 This plugin needs to be registered. It does not function as inline plugin. For

Chart.js 515 Dec 30, 2022
Redefined chart library built with React and D3

Recharts Introduction Recharts is a Redefined chart library built with React and D3. The main purpose of this library is to help you to write charts i

recharts 19.4k Jan 2, 2023
:bar_chart: A D3-based reusable chart library

c3 c3 is a D3-based reusable chart library that enables deeper integration of charts into web applications. Follow the link for more information: http

C3.js 9.2k Jan 2, 2023
GPL version of Javascript Gantt Chart

dhtmlxGantt Getting started | Features | Follow us | License | Useful links dhtmlxGantt is an open source JavaScript Gantt chart that helps you illust

null 952 Dec 29, 2022
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 2, 2023
:bar_chart: Re-usable, easy interface JavaScript chart library based on D3.js

billboard.js is a re-usable, easy interface JavaScript chart library, based on D3 v4+. The name "billboard" comes from the famous billboard chart whic

NAVER 5.4k Jan 1, 2023
:bar_chart: A library of modular chart components built on D3

Plottable Plottable is a library of chart components for creating flexible, custom charts for websites. It is built on top of D3.js and provides highe

Palantir Technologies 2.9k Dec 31, 2022
Chart image and QR code web API

QuickChart QuickChart is a service that generates images of charts from a URL. Because these charts are simple images, they are very easy to embed in

Ian Webster 1.3k Dec 25, 2022