Saving ZingChart State With JavaScript localStorage

This is a small post to show ZingChart users how to use local storage with our charts. The main reason you would use local storage with ZingChart is to preserve the graph interactions from users during a page reload. The following demos will show you how to persist the state of toggled legend items and zoom levels of a chart.

JavaScript Local Storage

The JavaScript behind the demos is simple. Just use ZingChart's API Events to register the state we want to save. Within each event handler, set a variable in local storage using setItem.

Preserving Legend State

With two easy steps, you can preserve the legend state. The first step is to save the legend interactions.

function legendToggle(e){
  localStorage.setItem('zingchart_plot_' + e.plotindex + '_visibility', !e.visible);
}

zingchart.bind('myChart', 'legend_item_click', legendToggle);
zingchart.bind('myChart', 'legend_marker_click', legendToggle);

Second, assign plot visibility in the graph configuration based on local storage values.

series:[
   ...
   {
     "background-color": "#76FF03",
     "values": [64063481],
     "text": "STANDARD PO",
     "visible": localStorage.getItem('zingchart_plot_4_visibility') ? localStorage.getItem('plot_4_visibility') : true
      }
]

Preserving Zoom State

The same two steps apply for saving zoom state. The first step is to save the zoom interactions to local storage.

zingchart.bind('myChart','zoom', function(e) {
  localStorage.setItem('zingchart_zoom_min', e.kmin);
  localStorage.setItem('zingchart_zoom_max', e.kmax);
});

The second step is to assign the zoom values using zoom-to-values in the graph configuration.

// some light sanity checks before assigning in the graph configuration
var zoomLevel = [0,0];

// if the local storage items are both set, then reset zoom
if (localStorage.getItem('zingchart_zoom_min') && 
    localStorage.getItem('zingchart_zoom_max')) {
  zoomLevel = [parseInt(localStorage.getItem('zingchart_zoom_min')), parseInt(localStorage.getItem('zingchart_zoom_max'))];
}

var myConfig = {
  ...
  "scaleX":{
        "zooming":true,
        'zoom-to-values': zoomLevel,
    }
  ...
}