Chartjs not showing up in Foundation5 Tabs - javascript

I'm using Chartjs with Foundation I have three charts that I want to be displayed on three tabs.
The chart only shows in the first tab. How can I get it to show in the second and third tabs? Can someone demonstrate a solution with a JSFiddle?
HTML:
<ul id="view-tabs" class="row tabs" data-tab>
<li class="tab-title active small-12 medium-4 day">View Day</li>
<li class="tab-title small-12 medium-4 week">View Week</li>
<li class="tab-title small-12 medium-4 month">View Month</li>
</ul>
<div class="tabs-content">
<div class="content day-data active" id="day">
<canvas id="day-graph" width="300" height="300"></canvas>
</div>
<div class="content week-data" id="week">
<canvas id="week-graph" width="300" height="300"></canvas>
</div>
<div class="content month-data id="month">
<canvas id="month-graph" width="300" height="300"></canvas>
</div>
</div>
Chartjs js
- this script just shows the #day-graph but it won't show if I place it in the 2nd or 3rd tab.
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "Visitors",
fillColor : "rgba(148,194,116, 0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("day-graph").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}

As u can see, u're executing new instance of Chart within window.onload function. This is the first reason.
Take a closer look - at the execution:
var ctx = document.getElementById("day-graph").getContext("2d");
You took the context over one canvas object, but in tabs you have three views. Sciprt cannot figure out that it should exec other charts.
U need to repeat the approach 3 times - the number of charts inside the tabs, for example:
//some previous code
var ctx = document.getElementById("week-graph").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
But for the optimalization purposes u should execucute the instance IF the tab in currently avaiable. And this thing u should do by yourself.
http://foundation.zurb.com/docs/components/tabs.html#callbacks

Related

Dynamic ChartJS Chart Updated in Rails with AJAX

I am using Rails 5 and the latest ChartJS library (http://www.chartjs.org/docs/).
What I want to accomplish is to GET the latest 20 items from the SensorReading model and update the Chart with setInterval and AJAX.
I've built the AJAX call and I've loaded the Chart but I fail in two things.
First of of all I get a Syntax Error when reading data from Rails:
SyntaxError: expected expression, got '&'
var labels = ["2016-07-03 10:33:49 +0300", "2016-07-03 10:3
No matter what I tried, they keep to appear with " instead of quotes.
Secondly I am unable to update the Chart, as I need a handler available for the Chart itself to call .update() on it.
index.html.erb
<h1>Dashboard</h1>
<div class="ui divider"></div>
<div class="ui padded grid">
<div class="four wide column">
<div class="ui statistic">
<div class="value">
<%= #temperature %>.C
</div>
<div class="label">
TEMPERATURE
</div>
</div>
<br>
<div class="ui statistic">
<div class="value">
<%= #humidity %>%
</div>
<div class="label">
HUMIDITY
</div>
</div>
</div>
<div class="twelve wide column">
<div class="ui segment">
<div class="line-chart" style="max-height: 400px; display:block;">
<canvas id="updating-chart"></canvas>
</div>
</div>
</div>
</div>
<br>
<script>
var labels = <%= #sensor_readings.map(&:created_at) %>;
var canvas = document.getElementById('updating-chart'),
ctx = canvas.getContext('2d'),
startingData = {
labels: labels,
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: <%= #sensor_readings.map(&:temperature) %>
},
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: <%= #sensor_readings.map(&:humidity) %>
}
]
},
latestLabel = startingData.labels[6];
// Reduce the animation steps for demo clarity.
var myLiveChart = new Chart(ctx , {
type: "line",
data: startingData,
animationSteps: 15
});
setInterval(function(){
// Add two random numbers for each dataset
//myLiveChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLiveChart.update(); // Calling update now animates the position of March from 90 to 50.
}, 5000);
</script>
dashboard.js
var ready = function(){
setInterval(refreshSensorReadings, 3000);
function refreshSensorReadings(){
console.log("--> Called");
$.rails.ajax({
type: "GET",
dataType: 'script',
url: "/sensor_readings_chart_data.js",
success: function(result){
//$('.line-chart').html(result);
console.log(result);
}
});
};
};
$(document).on('turbolinks:load', ready);
route
get 'sensor_readings_chart_data', to: 'sensor_readings#chart_data'
sensor_readings_controller.rb
def chart_data
#sensor_readings = SensorReading.last(20)
respond_to do |format|
format.json { head :no_content }
format.js
end
end
Any advice will be appreaciated.
Try the html_safe method:
Marks a string as trusted safe. It will be inserted into HTML with no
additional escaping performed. It is your responsibilty to ensure that
the string contains no malicious content. This method is equivalent to
the raw helper in views. It is recommended that you use sanitize
instead of this method. It should never be called on user input.
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: <%= #sensor_readings.map(&:temperature).html_safe %>
},
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: <%= #sensor_readings.map(&:humidity).html_safe %>
}
]

jHeatmap Javascript library tab behaves strangely

I have been struggling with this problem for days and it really baffled me. Hopefully someone skillful in JQuery could help out.
This is related to a very powerful and nice javascript library for creating interactive heatmaps. http://jheatmap.github.io/jheatmap/. I am modifying one of the examples -- Quickstart -- in order to display more than one heatmap on a page. The idea is to put heatmap on separate tabs and activate a heatmap by clicking on a particular tab. The tool couldn't do this naturally, instead it only displays one heatmap on each html page. The developer suggested a solution but here is the problem.
In this sample code, I intend to display three heatmaps (call them heatmap1, heatmap2 and heatmap3) on three tabs. The current situation is that I must click on heatmap1's tab first before clicking on tabs for heatmap2 or heatmap3. Since heatmap1 is displayed by default, so when the page is initially up, I can just go ahead to click on tab's for heatmap2 and that is fine. But now if I want to display heatmap3, I must go back to click on heatmap1's tab, then click on heatmap3's tab. After I manage to see heatmap3 using this trick, I will need to click on heatmap1's tab again in order to display heatmap2. It seems heatmap1 must be displayed before any other heatmaps to be shown.
Since my account won't allow me to attach a file, I put the code below. This is a direct modification of the Jheatmap's QuickStart step4 code. You will not be able to run it because the script loads/reads in text files. But I would greatly appreciate if you can take a look at the javascript around the three heatmaps and the html codes rendering the objects. I think someone skillful in JQuery could give me some advice on how to fix the bug.
Thanks much for your help.
<!DOCTYPE html>
<html>
<head>
<title>jHeatmap</title>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="prettify.css" rel="stylesheet" type="text/css">
<link href="../../styles/jheatmap-1.0.0.css" rel="stylesheet" type="text/css"/>
<style>
/* To center the heatmap */
table.heatmap {
margin: 0px auto;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="../../scripts/jheatmap-1.0.0.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
/* heatmap1 */
$('#heatmap1').heatmap(
{
data: {
rows: new jheatmap.readers.AnnotationReader({ url: "quickstart-rows.tsv" }),
cols: new jheatmap.readers.AnnotationReader({ url: "quickstart-cols.tsv" }),
values: new jheatmap.readers.TableHeatmapReader({ url: "quickstart-data.tsv" })
},
init: function (heatmap) {
// Column annotations
heatmap.cols.decorators["subtype2"] = new jheatmap.decorators.CategoricalRandom();
heatmap.cols.annotations = ["subtype"];
// Rows annotations
heatmap.rows.decorators["fm-bias"] = new jheatmap.decorators.PValue({ cutoff: 0.05 });
heatmap.rows.annotations = ["fm-bias"];
// Aggregators
heatmap.cells.aggregators["Mutation"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["CNA Status"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["Expression"] = new jheatmap.aggregators.Median();
// Decorators
heatmap.cells.decorators["Mutation"] = new jheatmap.decorators.Categorical({
values: ["0","1"],
colors : ["white","green"]
});
heatmap.cells.decorators["CNA Status"] = new jheatmap.decorators.Categorical({
values: ["-2","2"],
colors : ["blue","red"]
});
heatmap.cells.decorators["Expression"] = new jheatmap.decorators.Heat({
minValue: -2,
midValue: 0,
maxValue: 2,
minColor: [85, 0, 136],
nullColor: [255,255,255],
maxColor: [255, 204, 0],
midColor: [240,240,240]
});
}
});
/* heatmap2 */
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
// Load Heatmap2
if ($(this).tab()[0].hash == '#heatmap2Tab') {
$('#heatmap-loader').show();
$('#heatmap2').width($('#heatmap').width());
$('#heatmap2').heatmap(
{
data: {
rows: new jheatmap.readers.AnnotationReader({ url: "quickstart-rows.tsv" }),
cols: new jheatmap.readers.AnnotationReader({ url: "quickstart-cols.tsv" }),
values: new jheatmap.readers.TableHeatmapReader({ url: "quickstart-data.tsv" })
},
init: function (heatmap) {
// Column annotations
heatmap.cols.decorators["subtype"] = new jheatmap.decorators.CategoricalRandom();
heatmap.cols.annotations = ["subtype"];
// Rows annotations
heatmap.rows.decorators["fm-bias"] = new jheatmap.decorators.PValue({ cutoff: 0.05 });
heatmap.rows.annotations = ["fm-bias"];
// Aggregators
heatmap.cells.aggregators["Mutation"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["CNA Status"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["Expression"] = new jheatmap.aggregators.Median();
// Decorators
heatmap.cells.decorators["Mutation"] = new jheatmap.decorators.Categorical({
values: ["0","1"],
colors : ["white","green"]
});
heatmap.cells.decorators["CNA Status"] = new jheatmap.decorators.Categorical({
values: ["-2","2"],
colors : ["blue","red"]
});
heatmap.cells.decorators["Expression"] = new jheatmap.decorators.Heat({
minValue: -2,
midValue: 0,
maxValue: 2,
minColor: [85, 0, 136],
nullColor: [255,255,255],
maxColor: [255, 204, 0],
midColor: [240,240,240]
});
}
});
}
})
/* heatmap3 */
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
// Load Heatmap2
if ($(this).tab()[0].hash == '#heatmap3Tab') {
$('#heatmap-loader').show();
$('#heatmap3').width($('#heatmap').width());
$('#heatmap3').heatmap(
{
data: {
rows: new jheatmap.readers.AnnotationReader({ url: "quickstart-rows.tsv" }),
cols: new jheatmap.readers.AnnotationReader({ url: "quickstart-cols.tsv" }),
values: new jheatmap.readers.TableHeatmapReader({ url: "quickstart-data.tsv" })
},
init: function (heatmap) {
// Column annotations
heatmap.cols.decorators["subtype"] = new jheatmap.decorators.CategoricalRandom();
heatmap.cols.annotations = ["subtype"];
// Rows annotations
heatmap.rows.decorators["fm-bias"] = new jheatmap.decorators.PValue({ cutoff: 0.05 });
heatmap.rows.annotations = ["fm-bias"];
// Aggregators
heatmap.cells.aggregators["Mutation"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["CNA Status"] = new jheatmap.aggregators.AbsoluteAddition();
heatmap.cells.aggregators["Expression"] = new jheatmap.aggregators.Median();
// Decorators
heatmap.cells.decorators["Mutation"] = new jheatmap.decorators.Categorical({
values: ["0", "1"],
colors: ["white", "green"]
});
heatmap.cells.decorators["CNA Status"] = new jheatmap.decorators.Categorical({
values: ["-2", "2"],
colors: ["blue", "red"]
});
heatmap.cells.decorators["Expression"] = new jheatmap.decorators.Heat({
minValue: -2,
midValue: 0,
maxValue: 2,
minColor: [85, 0, 136],
nullColor: [255, 255, 255],
maxColor: [255, 204, 0],
midColor: [240, 240, 240]
});
}
});
}
})
});</script>
</head>
<body>
<div class="container">
<div class="row">
<ul class="nav nav-pills">
<li>Step 0</li>
<li>Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
<li class="active">Step 4</li>
<li>Step 5</li>
</ul>
<p>
Add column and row annotation headers.
</p>
</div>
<div class="row">
<div id="heatmap-loader">
<div class="background"></div>
<div class="loader">
<img src="../../images/loading.gif">
</div>
</div>
<ul id="myTab" class="nav nav-tabs">
<li class="active">Heatmap1</li>
<li>Heatmap2</li>
<li>Heatmap3</li>
<li>Javascript</li>
<li>quickstart-data.tsv</li>
<li>quickstart-cols.tsv</li>
<li>quickstart-rows.tsv</li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade in active" id="heatmap1Tab" style="">
<div id="heatmap1"></div>
</div>
<div class="tab-pane fade" id="heatmap2Tab" style="">
<div id="heatmap2" style="width:100%;"></div>
</div>
<div class="tab-pane fade" id="heatmap3Tab" style="">
<div id="heatmap3" style="width:100%;"></div>
</div>
<div class="tab-pane fade" id="javascriptTab">
<pre id="source" class="prettyprint linenums"></pre>
</div>
<div class="tab-pane fade" id="dataTab">
<pre id="data" class="prettyprint"></pre>
</div>
<div class="tab-pane fade" id="cdataTab">
<pre id="cdata" class="prettyprint"></pre>
</div>
<div class="tab-pane fade" id="rdataTab">
<pre id="rdata" class="prettyprint"></pre>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="prettify.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script>
var source = document.getElementsByTagName('script')[2].innerHTML;
source = source.replace(/</g, "<").replace(/>/g, ">");
$('#source').html(source);
window.prettyPrint && prettyPrint();
$('#source ol.linenums li').each(function(idx, li) {
if ((idx > 3 && idx < 6) || (idx > 10 && idx < 18)) {
$(li).css("background-color", "#FFFFB3");
}
});
jQuery.ajax({
url: "quickstart-data.tsv",
dataType: "text",
success: function (file) {
$('#data').html(file);
}
});
jQuery.ajax({
url: "quickstart-cols.tsv",
dataType: "text",
success: function (file) {
$('#cdata').html(file);
}
});
jQuery.ajax({
url: "quickstart-rows.tsv",
dataType: "text",
success: function (file) {
$('#rdata').html(file);
}
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-7336589-2', 'jheatmap.github.io');
ga('send', 'pageview');
</script>
</body>
</html>
I think that the main problem in your code is that you are binding two functions to all the click tab events. You only need to bind one function and this function will draw only one heatmap depending on the link that was clicked.
Here you have a simplified version that draws three heatmaps on different tabs:
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="http://jheatmap.github.io/jheatmap/css/jheatmap-1.0.0-min.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="http://jheatmap.github.io/jheatmap/js/jheatmap-1.0.0-min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script>
var draw_heatmap = function (tag_id) {
$('#'+tag_id).heatmap({
data: {
values: new jheatmap.readers.TableHeatmapReader({ url: "http://jheatmap.github.io/jheatmap/examples/quickstart/quickstart-data.tsv" })
}});
};
$(document).ready(function () {
/* Draw the default visible heatmap */
draw_heatmap('heatmap1');
/* Calculate the visible heatmap width */
var heatmap_width = $('#heatmap1').width();
/* Fix the width to all the heatmaps */
$('#heatmap1').width(heatmap_width);
$('#heatmap2').width(heatmap_width);
$('#heatmap3').width(heatmap_width);
/* Attach draw heatmap to tab click event */
$('#myTab a').click(function (e) {
e.preventDefault();
/* Show the clicked tab */
$(this).tab('show');
/* Show the loader indicator */
$('#heatmap-loader').show();
/* Draw the correct heatmap */
if ($(this).tab()[0].hash == '#heatmap1Tab') {
draw_heatmap('heatmap1');
}
if ($(this).tab()[0].hash == '#heatmap2Tab') {
draw_heatmap('heatmap2');
}
if ($(this).tab()[0].hash == '#heatmap3Tab') {
draw_heatmap('heatmap3');
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div id="heatmap-loader">
<div class="background"></div>
<div class="loader">
<img src="http://jheatmap.github.io/jheatmap/images/loading.gif">
</div>
</div>
<ul id="myTab" class="nav nav-tabs">
<li class="active">Heatmap1</li>
<li>Heatmap2</li>
<li>Heatmap3</li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade in active" id="heatmap1Tab">
<div id="heatmap1"></div>
</div>
<div class="tab-pane fade" id="heatmap2Tab">
<div id="heatmap2"></div>
</div>
<div class="tab-pane fade" id="heatmap3Tab">
<div id="heatmap3"></div>
</div>
</div>
</div>
</div>
</body>
</html>

Chart.js - Toggle visibility of charts

I really need help for this thing i'm working on.
Basically I have 4 charts rendered by chartjs. I've made 4 buttons, that simply show or hide the desired DIV. I'm pretty sure it's works on jQuery side, but I'm not so skilled to understand what's happening here on Chart.js side.
This is a demo https://jsfiddle.net/ttum6ppu/
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>
<button type="button" class="btn btn-default btn-xs stanza_button" id="stanza" style="display:none;">Per stanza</button>
<button type="button" class="btn btn-primary btn-xs stanza_selected" id="stanza"><i class="fa fa-eye"></i> Per stanza</button>
<button type="button" class="btn btn-default btn-xs settimanale_button" id="settimanale">Andamento settimanale</button>
<button type="button" class="btn btn-primary btn-xs settimanale_selected" id="settimanale" style="display:none;"><i class="fa fa-eye"></i> Andamento settimanale</button>
<button type="button" class="btn btn-default btn-xs mensile_button" id="mensile">Andamento mensile</button>
<button type="button" class="btn btn-primary btn-xs mensile_selected" id="mensile" style="display:none;"><i class="fa fa-eye"></i> Andamento mensile</button>
<button type="button" class="btn btn-default btn-xs annuo_button" id="annuo">Andamento annuo</button>
<button type="button" class="btn btn-primary btn-xs annuo_selected" id="annuo" style="display:none;"><i class="fa fa-eye"></i> Andamento annuo</button>
</p>
<script>
$(document).ready(function(){
$("#stanza").click(function(){
$(".stanza, .stanza_selected, .settimanale_button, .mensile_button, .annuo_button").show();
$(".settimanale, .mensile, .annuo, .stanza_button, .settimanale_selected, .mensile_selected, .annuo_selected").hide();
});
$("#settimanale").click(function(){
$(".settimanale, .settimanale_selected, .stanza_button, .mensile_button, .annuo_button").show();
$(".stanza, .mensile, .annuo, .stanza_selected, .settimanale_button, .mensile_selected, .annuo_selected").hide();
});
$("#mensile").click(function(){
$(".mensile, .mensile_selected, .stanza_button, .settimanale_button, .annuo_button").show();
$(".stanza, .settimanale, .annuo, .stanza_selected, .settimanale_selected, .mensile_button, .annuo_selected").hide();
});
$("#annuo").click(function(){
$(".annuo, .annuo_selected, .stanza_button, .settimanale_button, .mensile_button").show();
$(".stanza, .settimanale, .mensile, .stanza_selected, .settimanale_selected, .mensile_selected, .annuo_button").hide();
});
});
</script>
<div style="width: 50%">
<div style="height:70%;" class="stanza">
<canvas id="canvas" height="100px;"></canvas>
</div>
<div style="height:70%; display: none;" class="settimanale">
<canvas id="canvas2" height="100px;"></canvas>
</div>
<div style="height:70%; display: none;" class="mensile">
<canvas id="canvas3" height="100px;"></canvas>
</div>
<div style="height:70%; display: none;" class="annuo">
<canvas id="canvas4" height="100px;"></canvas>
</div>
</div>
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var barChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
var ctx = document.getElementById("canvas2").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
var ctx = document.getElementById("canvas3").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
var ctx = document.getElementById("canvas4").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
}
</script>
</body>
The first chart is displayed correctly, but when You press the second button it shows nothing.
Thank You in advance
In my view a better solution is to modify the DOM to replace the canvas element, so you can redraw it with your new data :
var canvas_html = '<canvas id="canvas" height="100px;"></canvas>';
var drawChart = function(data) {
// reinit canvas
$('#canvas_container').html(canvas_html);
// redraw chart
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(data, {
responsive : true
});
};
I have made an update of your fiddle so you can see the result.
This is fiddly, think it's because your using Chart.js which creates the charts using iframes which are never fun to work with. Without forcing a page reload I dont think you're going to be able to do it. The canvas is being drawn at 0px height and width on the hidden charts so just changing their parents divs display using jQuery to block isn't going to cut the mustard.
I've updated your fiddle so that clicking on each button shows each chart separately but the only thing I couldnt fix was hiding the last three charts on page load. Hopefully this is something that you can work with.
I've removed display: none from the charts
I had same issue and solved it by looking at visibility of container div, if div is visible render chart otherwise do nothing. so on switch tab call function to render chart, by that time div should be visible. here is sample code,
if ($(".canvas-holder2").is(":visible")) {
window['myDoughnut'] = new Chart($("#chart-area")[0]
.getContext("2d"))
.Doughnut(data, {
responsive: true,
animateScale: true
});
window['myDoughnut'].update();
}

chart.js pie chart issue with display: none

I have a problem with the pie chart when the container has a display property none in small devices and I have the following error :
Uncaught IndexSizeError: Failed to execute 'arc' on 'CanvasRenderingContext2D': The radius provided (-0.5) is negative.
my HTML code is
<div class="container-fluid charts hidden-xs">
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Annual sales</div>
<div class="panel-body">
<canvas class="annualChart" width="400" height="400"></canvas>
</div>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Visitors per shop</div>
<div class="panel-body">
<canvas class="visitorsChart" width="400" height="400"></canvas>
<div id="legend"></div>
</div>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Fans</div>
<div class="panel-body">
<canvas class="annualfanschart" width="400" height="400" ></canvas>
</div>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">General sales</div>
<div class="panel-body">
<canvas class="generalSalesChart" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
</div>
and my JS code for the pie chart div is (the others are line and bar charts)
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Men"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Women"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Children",
}
];
var options = {
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : true
}
var ctx = $(".visitorsChart").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(data,{
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color: <%=segments[i].fillColor%>\"></span><%if(segments[i].label){%> <%=segments[i].label%><%}%></li><%}%></ul>"
});
var legend = myPieChart.generateLegend();
$("#legend").html(legend);
I face this problem only with the pie type, the other types doesn't show errors
There's currently a bug in chart.js: https://github.com/nnnick/Chart.js/issues/592
Try to skip chart rendering if the element is not visible
if ($(".visitorsChart").is(":visible")) {
var ctx = $(".visitorsChart").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(data,{});
}

Chart.js not showing in my view

I have an app running with angular.js and one of my view should load an chart. I'm using chart.js for it, but for some reason it's not working and no error is shown on my console.
Here is my function that creates the chart:
$scope.writeBatteryChart = function(){
console.log("Function was called");
var data = {
labels: ["10:30am", "11:00am", "11:30am", "12:00pm", "12:30pm", "01:00pm", "01:30pm"],
datasets: [
{
label: "Battery",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var options = {
responsive: true,
bezierCurve : false
}
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).Line(data, options);
}
Here's the HTML where the chart should appear:
<div class="row">
<div class="col-md-8 col-sm-8 col-xs-8" style="padding-left: 0px;">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Battery <i class="fi-battery-half"></i></h3>
</div>
<div class="panel-body">
<canvas id="myChart" height="300"></canvas>
</div>
</div>
</div>
<div class="col-md-4 col-sm-4 col-xs-4" style="padding-left: 0px; padding-right: 0px;">
</div>
</div>
and I'm also loading the latest version of the Chart.js:
<!--Chart plugin -->
<script src="bower_components/Chart.js/Chart.js" language="javascript"></script>
One thing that I noticed is that the canvas is being rendered with 0 dimensions:
Does someone can see where I'm doing something wrong?
The problem: I was calling the function before the canvas be loaded on the view, so I used a setTimeout() to call the writeBatteryChart() with a delay in order to wait the canvas be rendered.
You have to add your rendered things inside of canvas. Hope it will help Link

Categories