score:42
you can use jquery.extend()
and highcharts.setoptions
.
so first you'll make the first object which will be extended by all your charts, this object will contain your highchart default functions.
you can do it using namespacing.
the following way is good when you have very different charts.
default graphic:
var defaultchart = {
chartcontent: null,
highchart: null,
defaults: {
chart: {
alignticks: false,
bordercolor: '#656565',
borderwidth: 1,
zoomtype: 'x',
height: 400,
width: 800
},
series: []
},
// here you'll merge the defauls with the object options
init: function(options) {
this.highchart= jquery.extend({}, this.defaults, options);
this.highchart.chart.renderto = this.chartcontent;
},
create: function() {
new highcharts.chart(this.highchart);
}
};
now, if you want to make a column chart, you'll extend defaultchart
var columnchart = {
chartcontent: '#yourchartcontent',
options: {
// your chart options
}
};
columnchart = jquery.extend(true, {}, defaultchart, columnchart);
// now columnchart has all defaultchart functions
// now you'll init the object with your chart options
columnchart.init(columnchart.options);
// when you want to create the chart you just call
columnchart.create();
if you have similar charts use highcharts.setoptions
which will apply the options for all created charts after this.
// `options` will be used by all charts
highcharts.setoptions(options);
// only data options
var chart1 = highcharts.chart({
chart: {
renderto: 'container1'
},
series: []
});
var chart2 = highcharts.chart({
chart: {
renderto: 'container2'
},
series: []
});
reference
score:4
to add to @ricardo's great answer, i have also done something very similar. in fact, i won't be wrong if i said i went a step further than this. hence would like to share the approach.
i have created a wrapper over the highchart library. this gives multiple benefits, following being the main advantages that encouraged going in this path
- decoupling: decouples your code from highcharts
- easy upgrades: this wrapper will be the only code that will require modification in case of any breaking changes in highchart api after upgrades, or even if one decides to move to a differnt charting library altogether (even from highchart to highstock can be exhaustive if your application uses charts extensively)
- easy of use: the wrapper api is kept very simple, only things that may vary are exposed as options (that too whose values won't be as a deep js object like hc already has, mostly 1 level deep), each having a default value. so most of the time our chart creation is very short, with the constructor taking 1
options
object with merely 4-5 properties whose defaults don't suit the chart under creation - consistent ux: consistent look & feel across the application. eg: tool tip format & position, colors, font family, colors, toolbar (exporting) buttons, etc
- avoid duplication: of course as a valid answer of the asked question it has to avoid duplication, and it does to a huge extent
here is what the options
look like with their default values
defaults : {
charttype : "line",
starttime : 0,
interval : 1000,
chartdata : [],
title : "product name",
navigator : true,
legends : true,
presettimeranges : [],
primarytoolbarbuttons : true,
secondarytoolbarbuttons : true,
zoomx : true,
zoomy : false,
height : null,
width : null,
panning : false,
reflow : false,
ydecimals : 2,
container : "container",
allowfullscreen : true,
credits : false,
showall : false,
fontsize : "normal", // other option available is "small"
showbtnsinnewtab : false,
xaxistitle : null,
yaxistitle : null,
onload : null,
pointmarkers : false,
categories : []
}
as you can see, most of the times, its just chartdata
that changes. even if you need to set some property, its mainly just true/false types, nothing like the horror that highchart constructor expects (not critizing them, the amount of options they provide is just amazing from customization point of view, but for every developer in the team to understand & master it can take some time)
so creation of chart is as simple as
var chart=new mylib.chart({
chartdata : [[1000000,1],[2000000,2],[3000000,1],[4000000,5]]
});
score:6
i know this has already been answered, but i feel that it can be taken yet further. i'm still newish to javascript and jquery, so if anyone finds anything wrong, or thinks that this approach breaks guidelines or rules-of-thumb of some kind, i'd be grateful for feedback.
building on the principles described by ricardo lohmann, i've created a jquery plugin, which (in my opinion) allows highcharts to work more seamlessly with jquery (i.e. the way that jquery works with other html objects).
i've never liked the fact that you have to supply an object id to highcharts before it draws the chart. so with the plug-in, i can assign the chart to the standard jquery selector object, without having to give the containing <div>
an id
value.
(function($){
var charttype = {
myarea : {
chart: { type: 'area' },
title: { text: 'example line chart' },
xaxis: { /* xaxis settings... */ },
yaxis: { /* yaxis settings... */ },
/* etc. */
series: []
},
mycolumn : {
chart: { type: 'column' },
title: { text: 'example column chart' },
xaxis: { /* xaxis settings... */ },
yaxis: { /* yaxis settings... */ },
/* etc. */
series: []
}
};
var methods = {
init:
function (chartname, options) {
return this.each(function(i) {
optsthis = options[i];
charttype[chartname].chart.renderto = this;
optshighchart = $.extend (true, {}, charttype[chartname], optsthis);
new highcharts.chart (optshighchart);
});
}
};
$.fn.cbhchart = function (action,objsettings) {
if ( charttype[action] ) {
return methods.init.apply( this, arguments );
} else if ( methods[action] ) {
return methods[method].apply(this,array.prototype.slice.call(arguments,1));
} else if ( typeof action === 'object' || !action ) {
$.error( 'invalid arguments to plugin: jquery.cbhchart' );
} else {
$.error( 'action "' + action + '" does not exist on jquery.cbhchart' );
}
};
})(jquery);
with this plug-in, i can now assign a chart as follows:
$('.columnchart').cbhchart('mycolumn', optionsarray);
this is a simplistic example of course; for a real example, you'd have to create more complex chart-properties. but it's the principles that concern us here, and i find that this approach addresses the original question. it re-uses code, while still allowing for individual chart alterations to be applied progressively on top of each other.
in principle, it also allows you to group together multiple ajax calls into one, pushing each graph's options and data into a single javascript array.
the obligatory jfiddle example is here: http://jsfiddle.net/3gyhg/1/
criticism welcome!!
Source: stackoverflow.com
Related Query
- Manage multiple highchart charts in a single webpage
- Highchart multiple bar charts in a single webpage
- Can we manage multiple highchart charts in a single function by changing type in chart drawing functionm
- Highchart multiple axes - sync axes on multiple charts
- Highcharts multiple charts on a single page using c# asp.net mvc3
- Highchart Single Legend to control Multiple chart
- Multiple charts in separate divs, single range and zoom picker
- When adding point on dynamically created Multiple Highchart Graphs on a single page, the plot line draws to the start point instead of last point?
- How to plot multiple lines in a single graph using HighChart with JSON
- How to display Multiple Highchart in single page
- Multiple Charts on single page RAZOR MVC4
- Highstock Single Navigator for multiple Charts
- Why code of Horizonal line(y-axis) on a single in Highcharts get applied to all other charts integrated with Webdatarocks
- Hightcharts - multiple data in one single pie charts
- Highchart - adding more series to one of multiple synced highstock charts
- Multiple Pie Charts Of Variable Data With Single Legend Item Click
- Highchart Color Issue for series with single data with multiple colors
- Highchart - Angular 9: How to export all charts into single pdf?
- Draw multiple series in Highchart from single JSON data container
- Drilldown multiple levels Highchart
- Background color for multiple Highchart panes, in Vue app
- Polymer Template Repeat Over Multiple Charts
- Highcharts - multiple charts
- Multiple series in HighStock charts
- Highchart axis max with multiple axes
- Highcharts: update series on multiple charts with same data
- Highcharts: Plot multiple values in single category
- Is multiple level Highchart Drilldown possible in adjacent charts?
- Single series drilldown to multiple series Highcharts
- highchart change color of single bar in single category
More Query from same tag
- Highcharts Sunburst levels radius
- Converted PHP code that built an array to JS and now highcharts doesn't work - what did I do wrong?
- Highchart Callback Refactoring not working, and how to display multiple series using multiple Ajax data
- Highcharts - SMA Indicator does not display
- Highcharts - Export server not generating image
- Highcharts - Funnel, Line and Scatter
- How can I style highchart select to look like hover?
- Using modified JS version in Highcharts to bring back the pre-3.0 export buttons
- How to render highcharts from external json for multiple series
- How to add and resize image in context button of highcharts
- Adding an empty series changes axis minimum value
- How to use Jquery knob like text label with highchart Jquery plugin
- Highcharts Drawing a line with chart.renderer.path
- Highcharts - overlapping values with the x-Axis
- Highcharts:Remove the color area below the 2 series
- How to parse dates in highcharts from csv
- Highcharts: Return PlotBands Click function via JSON
- Pie Chart tooltip thousand seperator and rtl labels doesn't work in highchart
- Using Highcharts Export Server, how to include commas in labels?
- HighCharts Adding a Back Button when data is set through point.events.click
- How to display tooltip data below x-axis category labels using Highcharts
- Get only visible x axis dates when zooming in highcharts
- I am working on highcharts, and want to adjust tooltip with chart name ( chart title )
- How to add a background image (pattern) to highchart column graph?
- keeping highcharts stacked columns borderWdith but removing stacking gap
- How to add synchronized-charts in drilldown?
- Highchart - Editing the tooltip date format content on hover
- Highcharts - master-detail - master with multiple color
- Highcharts - Display Marker Icon on Single Value
- How to position rangeSelector buttons to the right Highstock/Highcharts