Search code examples
jquerymorris.js

Morris js chart loads twice


I'm using Morris js to draw basic line chart. Here is my code:

function getChart(range) {
    $.ajax({
        type: 'GET',
        url: "page.php?doChart=1&range=" + range,
        dataType: 'json'
    }).done(function(json) {
        Morris.Line({
            element: 'chart',
            data: json.data,
            xkey: 'month',
            ykeys: json.xkey,
            labels: json.label,
            parseTime: false
        });
    });
}
$(document).ready(function() {
    getChart('all');
    $("#timeRange").on('click', function() {
        getChart($(this).data('value'))
    });
});

The above code works just fine on page load, the problem is when I try to load chart for different period, using on click event. Original container id #chart is being replaced, but for some reason the same instances of chart is being created just below #chart div.


Solution

  • Try it like this:

    function getChart(range) {
      $("#chart").empty();
      $.ajax({
    ... etc
    

    Every time you run the Morris.Line function, it inserts an <svg> element into your chosen element ("chart" in your case). It doesn't overwrite the previous one, it adds an extra one. So you need to clear the old chart out first.

    See this demo to demonstrate the duplication issue: http://jsbin.com/yelonizoce/1/edit?html,js,output

    And this one to demonstrate the use of .empty(); http://jsbin.com/xinegovoqo/1/edit?html,js,output