chart.js 2.xx and scroll into view
Hi,
I have a very simple bar chart, which has a load animation. I've been various hours (or days !) trying to find a solution for it to "load its animation" when I scroll into its position. Currently, it just loads its animation when the page initially loads and when I get into its position, it has already finished (its loading animation).
I know there are a lot of threads about this same problem, and I've read most of them and tried a lot of different solutions, but none of them worked for me. I finally found out that what all those other threads have in common is that they use an old version of chart.js (1.xxx). I'm using, and would like to keep using the new 2.xx version. I think that with this new version all those other valid solutions for 1.xxx don't work.
Would anyone be so nice to advise me on how to achieve that effect ? I would really appreciate it (I'm kind of desperate right now).
Thank you.
P.S: Here is my Fiddle link:
https://jsfiddle.net/javinv/ew44ko4j/4/
`var canvas = document.getElementById('myChart'); var data = { labels: ["Experiencia > 4 años", "Experiencia > 10 años", " ", "Formación Superior", "Formación Máster", " ", "2 idiomas", "3 o más idiomas", " ","Experiencia Internacional", "Experiencia Internacional"], datasets: [ { label: "Perfil profesional de nuestro Equipo", backgroundColor: ["rgba(254,127,81,0.2)", "rgba(254,127,81,0.6)", "blue", "rgba(254,127,81,0.2)", "rgba(254,127,81,0.6)", "coral", "rgba(254,127,81,0.2)", "rgba(254,127,81,0.6)", "gray", "rgba(254,127,81,0.2)", "rgba(254,127,81,0.6)"], borderColor: "rgba(254,127,81,1)", borderWidth: 2, hoverBackgroundColor: "rgba(254,127,81,0.4)", hoverBorderColor: "rgba(254,127,81,1)", data: [56, 34, , 30, 80, , 65, 30, , 50, 35], scaleGridLineWidth : 5, }] };
Chart.defaults.global.responsive = true;
Chart.defaults.global.legend.display = false;
Chart.defaults.global.animation.easing = "easeOutElastic";
Chart.defaults.global.animation.duration = "2000";
Chart.defaults.bar.stacked = false;
Chart.defaults.bar.scales.xAxes[0].categorySpacing = 0
var option = { scales: { yAxes:[{ stacked:true, gridLines: { display:true, color:"rgba(120,128,134,0.2)" } }], xAxes: [{ barPercentage: 1.2, categorySpacing: 0, }] } };
var myBarChart = Chart.Bar(canvas,{ data:data, options:option });`
@javinv you should create the chart when the canvas scrolls into view the first time.
@etimberg that makes a lot of sense, but how ?
P.S: THANK YOU
@etimberg I've been trying to stop the load state using a scroll trigger until the div containing the chart enters the visible area but it still shows no animation, it just appears without any animation, as in the jsfiddle that I posted in my first message. I'm using webflow to develop the page in which the chart appears, and I'm using its own tools to trigger the load of the chart.
Would it be possible to not create the chart modifying the script of the chart?(since with webflow what I'm achieving, it seems, it's just to stop its appearance in the screen?) should I use a plugin such as waypoints or appear.js ? or is it possible to just tell the chart in its own script to not create it until a certain div or section is scrolled into, since as I told you I tried multiple solutions that I found but none of them worked when I utilize chartjs v2.
Thank you !!
@javinv how did you "stop the load state" of the chart?
@simonbrunel in webflow, I've tried various combinations of "interaction" effects, changing the initial appearance state to "display:none" of both the chart itself or the div or section containing it; then I scroll trigger it to change to "display:block" when it enters the visible area of the screen.
In the script itself I've tried the multiple solutions that appear here and on stackoverflow and that normally produce an error in which with every scroll along the chart, it gets bigger and bigger or smaller, depending on the script. I've found out that those solutions work when the chart.js version is 1.x but I've not been able to make them work with v2.x .
Is there anyway in which I can tell the chartjs just to not create the chart until its visible, as @etimberg wrote ?
This is one of the solutions I tried:
$(window).bind("scroll", function(){
$('.chartClass').each(function(i){
var myBarChart = [
{value: 100, color:"#6abd79"},
{value: 20, color:"#e6e6e6"}
];
var graphic = new Chart(document.getElementById("myChart").getContext("2d")).Bar(Data, options);
$(window).unbind(i);
});
});
And this one is the stackoverflow thread I was referring to:
http://stackoverflow.com/questions/18772547/how-to-make-the-chart-js-animate-when-scrolled-to-that-section
Thank you.
I'm not familiar with jQuery, but looks like your code can't work because it reacts to all scroll events and as soon as one occurs, creates the Chart. You would need to check first if the canvas is visible and if so, create your chart. The stackoverflow solution you posted should work for you, just replace #canvasby your own element ID #myChart.
Also worth noting that Chart.js doesn't check DOM visibility in order to update the canvas, so changing the canvas chart display or visibility will have no impact on when the chart will load and animate initial data.
Well that's part of my problem. The stackoverflow solution that you highlighted in your last message doesn't work just like it is, it's necessary to add an external link to chart.js and if you use v1.1:
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.min.js
Then it works, with the same issue that the user of that original message described (the chart grows every time you scroll by its position).
But if you use as external reference a V2 version of chart.js , then it doesn't load anything:
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js
Here you have the jsfiddle of the solution that you suggested me with the v1.1.1 chart.js version:
http://jsfiddle.net/javinv/TSmDV/193/
and here you have it with the V2.x:
http://jsfiddle.net/javinv/TSmDV/194/
That's because in Chart.js version 2, the data structure has changed, please take a look to the documentation. Then you can try this fiddle (I just changed the data object and how to create the Chart instance).
Yours is perfect !!! but it doesn't work on mine !!!
I've read over and over the documentation of V2 during the last few days, trying to find what is failing on my version :(
https://jsfiddle.net/javinv/ew44ko4j/8/
Maybe it would be easier to re-write mine over your example !
If you open the browser console, you will get the following error: Uncaught ReferenceError: $ is not defined. That's because jQuery is not loaded in your fiddle. When correctly setup, it works: https://jsfiddle.net/ew44ko4j/9/.
Thank you so much !!!! It finally works !!!!
I'm gonna try to better tune it up now that it's working! Will see if I can make it load just once as you propose and adjust the hover on option, now it acts weird !
I really thought it would never work ! Thank you !!
https://jsfiddle.net/javinv/ew44ko4j/13/
All fixed and working ! Thank you so much @simonbrunel !!!
You're welcome @javinv, your fiddle looks good and actually your issue makes me think that a Chart.js plugin will be great. It will not be based on any 3rd parties (such as jQuery) and will only defer the chart initial update, meaning that once loaded, the chart will not animate again if the user scroll away and back (like in your previous fiddle).
The difference with your solution is that the chart instance can be created at any time, it doesn't need to be created when it becomes visible (no hassle for the dev). Only the data animation will be deferred, so legend and scales will be visible immediately. This allows deferring the data animation based on other criteria and make sure that the user will fully see the animation without having the legend/scales "popping" on the screen.
The first version will offer 3 options: xOffset, yOffset and delay. The offset is the number of pixels (or percent of width/height) of the canvas that need to be displayed on screen before loading it. The delay is the number of milliseconds to delay the loading after the chart is considered visible.
It's still in progress but you can see a preview here. Any feedback/ideas are welcome of course.
I think it's perfect! I was actually trying to delay the start of the animation of mine, and even tried to add a "y offset".
Those are options that would make chartjs so more useful !
I would be glad to try your plugin in my page and contribute with feedback if I may find something interesting.
I really think that the options that appear on your preview page should be basic configuration parameters of chartjs and that they would improve a lot its visual impact (as well as its easy of use: thouse would have been real game changer parameters in my personal experience with chartjs from the last days!).
I will keep you posted on this thread!
Okay thank you !!
@javinv, finally released Chart.Deferred.js, let me know if it works as expected. That's a small plugin, but still an alpha version, so should be fairly tested before using it in production. Don't hesitate to report issues.
@simonbrunel thank you ! I'll let you know if I find out something interesting !
I understand this thread is two years old. However I found it extremely helpful and would love some assistance to expand on this solution to two (or more) graphs on a single page.
I have this working to some degree (by adding a second $(window).scroll(function()). However it will only load the first graph that comes into view. If you scroll from the bottom again only the bottom will be in view.
This is the JS I am using (adapted from the previous solution):
//BAR DATA var color = Chart.helpers.color;
var canvas1 = document.getElementById('canvas-bar');
var databar = {
labels: ["BCAA", "TYROSINE", "PHENYLALANINE"],
datasets: [{
label: 'Control',
fontFamily: "Open Sans",
backgroundColor: color(window.chartColors.orangeww).alpha(0.5).rgbString(),
borderColor: window.chartColors.orangeww,
borderWidth: 1,
data: [42,34,27]
}, {
label: '8 Hr Shift',
fontFamily: "Open Sans",
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
borderWidth: 1,
data: [8,-2,-10]
}]
};
var optionsbar = {
responsive: true,
legend: {
position: 'bottom',
fontFamily: "Open Sans"
},
title: {
display: true,
text: 'Change In Amino Acid Level After 8hr Shift',
fontSize: 14,
fontFamily: "Open Sans"
},
scales: {
yAxes: [{
ticks: {
callback: function(value, index, values) {
return value + '%';
},
min: -10,
max: 50,
fontFamily: "Open Sans"
},
scaleLabel: {
display: true,
labelString: '% Change Ref. to Baseline',
fontFamily: "Open Sans"
},
}]
}
};
//LINE DATA
var canvas2 = document.getElementById('canvas-line');
var dataline = {
labels: ["19:40","21:40","23:00","00:10","01:40","03:10","04:40","06:10"],
datasets: [{
label: "Placebo",
fontFamily: "Open Sans",
fill: false,
backgroundColor: window.chartColors.orangeww,
borderColor: window.chartColors.orangeww,
borderWidth: '2',
lineTension: 0,
pointRadius: 2,
data: [22,22,23,25,37,55,160,178],
}, {
label: "Tyrosine",
fontFamily: "Open Sans",
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
borderWidth: '2',
lineTension: 0,
pointRadius: 2,
data: [23,23,24,25,28,42,77,82,]
}]
};
var optionsline = {
responsive: true,
legend: {
position: 'bottom',
fontFamily: "Open Sans"
},
title:{
display:true,
text:'Visual Tracking Error During Sleep Deprivation',
fontSize: 14,
fontFamily: "Open Sans"
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Time of Day',
fontFamily: "Open Sans"
}
}],
yAxes: [{
display: true,
ticks: {
min: 0,
max: 200,
fontFamily: "Open Sans"
},
scaleLabel: {
display: true,
labelString: 'RMS Error',
fontFamily: "Open Sans"
}
}]
}
};
//LOAD
Chart.defaults.global.animation.duration = "2000";
var inView = false;
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemTop <= docViewBottom) && (elemBottom >= docViewTop));
}
$(window).scroll(function() {
if (isScrolledIntoView('#canvas-bar')) {
if (inView) { return; }
inView = true;
new Chart(
document.getElementById("canvas-bar").getContext("2d"),{type: 'bar', data: databar, options: optionsbar}
);
}
});
$(window).scroll(function() {
if (isScrolledIntoView('#canvas-line')) {
if (inView) { return; }
inView = true;
new Chart(
document.getElementById("canvas-line").getContext("2d"),{type: 'line', data: dataline, options: optionsline}
);
}
});
@bellshaw5 why not using chartjs-plugin-deferred instead of re-implementing your own solution?