HighCharts.JS / General Javascript - javascript

I've found a few posts on this but none that have helped me solve the situation. I'll try to explain the best I can.
My HighCharts example code works fine when I put it in an ASP.NET user control and simply browse to a page that contains my user control, as it is simply the same example that comes with the highcharts package. The following code is therefore in an asp.net web user control.
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/highcharts.js"></script>
<!-- 1a) Optional: add a theme file -->
<!--
<script type="text/javascript" src="/js/themes/gray.js"></script>
-->
<!-- 1b) Optional: the exporting module -->
<script type="text/javascript" src="/js/modules/exporting.js"></script>
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Under / Over 2.5 Goals'
},
tooltip: {
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Under / Over 2.5 Goals',
data: [
['Under', 33.0],
['Over', 67.0]
]
}]
});
});
</script>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto">
</div>
When however I am loading this same user control into my page dynamically using AJAX the chart is not rendering and I am getting an empty white as per the inline styling. I am presuming that this is because the JS code is executing when the document is ready and this will not work when I am loading the control dynamically.
The following code resides in an external .js file
Service.GetChartData(OnGetChartDataSuccess, OnGetChartDataFailure);
function OnGetChartDataSuccess(result) {
$get('ChartDataContent').style.display = 'none';
Sys.UI.DomElement.removeCssClass($get('ChartDataContent'), 'loading');
$get('ChartDataContent').innerHTML = result;
$('#ChartDataContent').fadeIn(500);
}
function OnGetChartDataFailure(result) {
alert('Error loading control data');
}
Now at the point where the Ajax call to the service has succeeded I need to be able to get the chart to do its rendering etc to the container.
As it stands this is just using the example and there is no need for me to be using Ajax, but in practice there will be some long running calculations that need to take place before the chart is rendered.
If I need to add more information to this then please say and Ill do my best to explain further.
Thanks in advance

The simplest option you have is to use the Highcharts .Net library from codeplex that acts as a wrapper around the Highcharts js library, allowing you to create the charts using only C#.
However, if you so not want to go that way, you can always use a helper function to load the series into the chart as shown in the example here

Related

Chart is empty upon initialization

I have a single chart showing on my site. Viewers can then click links beside the chart in order to change the chart data. My problem is that the data will not show in the chart upon initialization - only if you start clicking the buttons beside the chart will the data load. I load data into the charts using JSON. I have been told that the problem might be that the JSON data is loaded after the chart is first displayed (an asynchronous problem), but I don't know how to fix this.
Below is the code I use for setting the first chart I have (chartOptions.chart1) into the "container" div. This will initialize the chart structure but it will not call my data - the data will only show if I start clicking the div-links.
$('chart').ready(function() {
//common options
Highcharts.setOptions({
chart: {
marginRight: 0
},
legend: {
enabled: false
},
plotOptions: {
bar: {
pointPadding: .01
},
column: {
borderWidth: 0.5
},
line: {
lineWidth: 1
},
},
series: [{
color: '#027ff7',
data: []
}]
});
$('#container').highcharts(chartOptions.chart1);
chart = $('#container').highcharts();
$(document).on('click', '.chart-update', function() {
$('div').removeClass('selected');
$(this).addClass('selected');
chart.destroy();
$('#container').highcharts(chartOptions[$(this).data('chartName')]);
chart = $('#container').highcharts();
});
});
</script>
</head>
<body>
<span class="wrapper">
<span class="block chart"><div id="container" style="width:400px;height:300px;float:left;"></div></span>
<span class="block buttons">
<div id="divchart" class="chart-update selected" data-chart-name="chart1">Chart1</div>
<div id="divchart" class="chart-update" data-chart-name="chart2">Chart2</div>
</span>
</span>
</body>
So I am wondering if I can use something else instead of the
$('#container').highcharts(chartOptions.chart1);
in order to have the first chart initialized in the container-div when visitors first enter the site? Of if there is some javascript code that will automatically trigger the on-"click" part - since this works just fine.

How do I encode HTML characters within Javascript functions?

to all Javascript experts this question might be just basics. I'm using jQuery and I am working on a tooltip created with jQuery.flot.
The following is a part of my javascript function within an html file and this is exactly what I need to have the tooltip div to be rendered correctly:
$('<div id="tooltip">' + contents + '</div>').css( {
Because the div is not shown I used Firebug to look for the reason and the line of code from above shows the special characters < and > encoded as html entities < and > as you can see here:
$('<div id="tooltip">' + contents + '</div>').css( {
I was searching several online sources for a solution and tried things like .replace(/lt;/g,'<') or .html().text() and it took me more than three hours but nothing was helpful.
I works fine on localhost.
Full Source Code:
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../JavaScript/flot/jquery.flot.categories.js"></script>
<![CDATA[
<script type="text/javascript">
$(function () {
var data = [ ]]>{e1Array}<![CDATA[ ];
$.plot($("#placeholder1"), [ data ], {
series: {
bars: {
show: true,
barWidth: 1,
align: "center"
}
},
grid: {
hoverable: true,
clickable: true
},
xaxis: {
mode: "categories",
tickLength: 0
},
yaxis: {
min: 0,
max: 1,
ticks: 0
}
} );
});
var previousPoint = null;
$("#placeholder1").bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.datapoint) {
previousPoint = item.datapoint;
$("#tooltip1").remove();
showTooltip(item.pageX, item.screenY, item.series.data[item.dataIndex][0] + ': ' + item.series.data[item.dataIndex][1] + ' Einträge');
}
} else {
$("#tooltip1").remove();
previousPoint = null;
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: 100,
left: x,
border: '1px solid #fdd',
padding: '2px',
'background-color': '#fee',
opacity: 0.80
}).appendTo("#e1-container").fadeIn(0);
}
</script>
]]>
<div class="e1-container" id="e1-container">
<div id="placeholder1" class="e1"></div>
</div>
<![CDATA[
<script type="text/javascript">
This seems to be your problem, or at least the reason why FireBug does show html entities in your code. If you want to use cdata at all, you should place it inside of the <script> tags.
On why the tooltip is not shown at all, I can only guess, but for text content I'd recommend to use
$('<div id="tooltip"></div>').text(contents)
instead of using it as a html string.
You use appendTo(), which is fine.
You append the node only when the plothover flot event is fired.
This is correct, too.
So your code looks fine, you should probably look into this:
Jquery Flot "plothover" event not working
EDIT: You also can put the JS <script> after the HTML.
Do not directly add the contents inside the selector.
1) Create your DOM : var k = $('<div id="tooltip"></div>');
2) Fill your DOM :
// Add after
k.append(contents);
// Replace
k.html(contents);
// Replace and the content is just some text
k.text(contents);
3) Set the CSS : k.css({ ... })
4) Add the DOM to your page k.appendTo('#container');. You can also use $('#container').html(k); to replace the container contents and avoid to have a duplicate
In short :
var k = $('<div id="tooltip"></div>')
.append(contents)
.css({})
.appendTo('#container');
NOTE: The best way is to already create your tooltip div and just fill the elements to avoid to create two div with same ID, ... If you are afraid it perturbs the page, add display : none; to the CSS before to edit it, then change the classes when you edit it.
You will need to create div on 2 conditions :
The pages is created on load with variable number of components
You want to dynamically load CSS or JS.

jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts

I use EnhancedLegendRenderer plugin for my jqPlot charts, however I am unable to get it working for Pie charts.
If I click on the legend labels, they don't show or hide series. Here is jsFiddle example.
legend: {
renderer: $.jqplot.EnhancedLegendRenderer,
rendererOptions: {
numberColumns: 3,
seriesToggle: true
},
show: true
}
Has anybody came across and found a solution?
The answer of Merrily somehow correct, ZingChart looks good and have such functionality out of the box, but jqPlot is free and open source.
I rewrote jqPlot Pie Chart plugins and now the Pie chart from your example will work. Here is my blog post with explanation what I changed.
Download these 2 files:
extendedPieRenderer.js (it replaces jqplot.pieRenderer.js)
enhancedPieLegendRenderer.js (it replaces
jqplot.enhancedLegendRenderer.js)
And use them like this code:
<script type="text/javascript" src="jquery.jqplot.js"></script>
<script type="text/javascript" src="extendedPieRenderer.js"></script>
<script type="text/javascript" src="enhancedPieLegendRenderer.js"></script>
<script type="text/javascript">
...
var plot = $.jqplot('chart', data, {
seriesDefaults: {
renderer: $.jqplot.PieRenderer
},
legend: {
renderer: $.jqplot.EnhancedPieLegendRenderer
}
});
...
</script>
I also created this jsFiddle which you can open and verify that showing and hiding works: http://jsfiddle.net/19vzL5h2/1/
I'm not sure how tied to jqPlot you are, but many libraries have this sort of option baked in. Highcharts has it (and is free in most cases if that is your concern) and I saw it in AmCharts recently too.
It is also available through the ZingChart JavaScript charting library. I've made a demo with the toggle legend for you to try.
<html>
<head>
<script src="https://blog.pint.com/include_files/zingchart-html5-min.js"></script>
<script src="http://cdn.zingchart.com/zingchart-core.min.js"></script>
<script>zingchart.MODULESDIR="http://cdn.zingchart.com/modules/";</script>
<meta charset="utf-8">
<title>Pie chart with legend</title>
</head>
<div id="zc"></div>
<script>
var piedemo ={
"type":"pie",
"plot":{
"value-box":{
"text":"%v"
}
},
"series":[
{
"text":"Apples",
"values":[5]
},
{
"text":"Oranges",
"values":[8]
},
{
"text":"Bananas",
"values":[22]
},
{
"text":"Grapes",
"values":[16]
}
],
"legend":{
"header":{
"text":"Click an item to toggle"
},
"layout":"x4",
"marker":{
"type":"circle",
"size":4,
"border-color":"#333"
}
}
};
zingchart.render({
id: 'zc',
data: piedemo,
height: 400,
width: 400
});
</script>
</body>
</html>
I'm on the ZingChart team so if you have any questions on this demo, please feel free to reach out.

morris pie chart with a larger data

I need to know how can with jquery maybe show a better pie chart with morris.js...with jquery flot the library I can hide the result with per example less than 100 coincidences but with morris I don't know how?
Here the capture:
and I want to show it like this one:
here is the jquery i use:
<script type='text/javascript' charset='utf-8'>
$(function () {
var pie = {
element: 'pie',
hideHover: 'auto',
resize: true,
data: <?php include('graficas6.php'); ?>,
colors: [
'#1424b8',
'#0aa623',
'#940f3f',
'#148585',
'#098215',
'#b86c14',
'#b83214'
],
formatter: function (y) {
return y + " "
}
}
donut1 = Morris.Donut(pie)
});
</script>
I would suggest if you have the large data then you should use pagination ,so that data will be shown on each of the different pages.
There are many benefits if you look into these website.
https://demo.aheadmetrics.com/#UIJGJX6MIQ
I am currently making my ecommerce sales report . Once it gets love i will put that link over here

Google chart: how to make right side of the "white space" empty?

I use Google Chart in order to build some graphichs together with text description.
On the first iteration I used small "title" for each graph type and that was looking well. But at some point I've added total value for each graph... and text started to be wrapped.
Question 1: Is there any way to prevent text wrapping (see the right portion of the chart)?
I've tried put text inside of "..." but Google chart just convert these tags into pure text.
Question 2: Is there any way to move whole graph to the left and consume unused area so the right part will have more space for text?
Any thoughts are welcome! Probably there is any other solution that will work for me?
P.S.
Please see how that looks right now on the screenshot:
P.P.S Here is JS code I use to display the graphs
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/google/jsapi.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
var expArray = [<%=ExperienceArray %>];
function drawChart() {
if (expArray.length > 0) {
$('#chart_div').show();
$('#MessagesDiv').hide();
var total = 0, train = 0, match = 0, ageing = 0;
for (var i = 0; i < expArray.length; i++) {
total += expArray[i][1];
train += expArray[i][2];
match += expArray[i][3];
ageing += expArray[i][4];
}
var data = google.visualization.arrayToDataTable([
['№', 'Total (' + total + ')', 'Training (' + train + ')', 'Matches (' + match + ')', 'Ageing (' + ageing + ')']
].concat(expArray));
var options = {
title: 'Gained experience',
allowHtml: 'true',
hAxis: { title: '', titleTextStyle: { color: 'black' } },
colors: ['#00FF00', '#6600CC', '#0000CC', '#000000']
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
} else {
$('#chart_div').hide();
alert("Data are absent");
}
}
</script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
Add the following code (adjust as necessary) to your options: chartArea: {left: 0}
So your options file would become this:
var options = {
title: 'Gained experience',
allowHtml: 'true',
hAxis: { title: '', titleTextStyle: { color: 'black' } },
colors: ['#00FF00', '#6600CC', '#0000CC', '#000000'],
chartArea: {left: 0}
};
Note: the current setting will slice off the entire axis labels, so you want to use something appropriate in size bigger than 0 (you can calculate something with an algorithm, or just fiddle until you have it like you want it).
For the legend, however, there is no trick.
When Google creates the SVG for the chart, it will split the legend in to two lines (two separate SVG text elements) so it's not easy to tweak. You can't very well fix it easily. One option is to create a separate chart with just the legend (and no chart area) which will mimic the legend, and then link the two charts together (if you want click interactivity with the legend).
Alternatively, you can reduce the font size using legend: {textStyle: {fontSize: 8}} or whatever font size will prevent the text from wrapping (again, you can create an algorithm or fiddle with it until it works).
As a separate option, you can create a manual legend and use javascript to mimic click interactivity, and then you can use CSS/Javascript to format it however you want.

Categories

Resources