Solved : hovering over Chartjs Bar Chart showing old data

·

,
chartjs-in-angular6

Hello to all, welcome to the therichpost.com. In this I will tell you how to Solved : hovering over Chartjs Bar Chart showing old data? Chartjs is the very popular for barchart, line chart and many more. I was facing one problem during working with chartjs. When I change my chartjs bar chart event then hover again, It was showing me old data and this was the big issue for me but I am able to solved this and today I am sharing that code with all of you. Here is the code for solved hovering over Chartjs Bar Chart showing old data:

var ctxLine = document.getElementById("line-chart").getContext("2d");
if(window.bar != undefined) 
window.bar.destroy(); 
window.bar = new Chart(ctxLine, {});

 

There are so many tricky code in Chartjs and I will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com

Comments

56 responses to “Solved : hovering over Chartjs Bar Chart showing old data”

  1. Navid Arfaie Avatar
    Navid Arfaie

    Thanks Very Very much 🙂
    It woks!

    1. Neeraj Avatar
      Neeraj

      Thanks , solved my problem !

  2. Ishan Avatar
    Ishan

    Thanks. Please tell me what does window.bar perform ?

    1. therichpost Avatar

      If the variable is defined outside a function then its most immediate execution context is the global context which in web browsers is the window object;
      // note that the following doesn’t throw an error
      console.log(bar) // undefined
      console.log(window.bar) // undefined
      console.log(window.hasOwnProperty(‘bar’)) // true

      1. ABHISHEK NEGI Avatar
        ABHISHEK NEGI

        I am using chart control and getting same error, can you tell me the way where to add this code of line in a function or in the render method

  3. Sachin Avatar
    Sachin

    Thank You so much,,, it is really working.

    1. therichpost Avatar

      you’re most welcome 🙂

  4. Cher Avatar
    Cher

    Thank you So Much!

  5. Jayson Avatar
    Jayson

    does not work on me im using it on angular 6

    1. Ajay Malhotra Avatar

      HI Jayson, can you send me code, I need to check once..Angular code?

  6. Max Avatar
    Max

    My Angular has no Idea what windows.bar should be and me either.
    How I get it working?

    1. Max Avatar
      Max

      I got it

      1. Dharmansh Avatar
        Dharmansh

        how did it worked ? I am facing the same issue and am using angular 6

        1. Ajay Malhotra Avatar

          Hi, Dharmansh, can you check this:
          https://therichpost.com/solved-hovering-over-chartjs-bar-chart-showing-old-data-in-angular

          ======================
          Tell me if it solve you issue.

    2. tukaram jahdav Avatar
      tukaram jahdav

      i have same problem please help me

      1. Ajay Malhotra Avatar

        Please tell me the problem

  7. anik Avatar
    anik

    I have two chats ( line chart and bar chart). for line chart, I have already used window.bar but for the bar chart window.bar does not work.

    1. Ajay Malhotra Avatar

      It will work and can you me show you code?

      1. Surabhi Sugandha Avatar
        Surabhi Sugandha

        Same issue with me, how to make window.bar work for both the charts

  8. nini Avatar
    nini

    how to use this code, i have initial data and ajax call data.

    1. Ajay Malhotra Avatar
      Ajay Malhotra

      Same, when you will add your chart code then add above code.

  9. alagar Avatar
    alagar

    Thanks Bro

  10. omar Avatar
    omar

    very very thanks more

  11. Prashant Sontale Avatar
    Prashant Sontale

    I am also facing the same Problem of hovering and showing old data. I tried using your code but it shows the old data on hovering.

    Below is my code

    $(document).ready(function () {

    $(‘#search’).on(‘click’, function () {

    var district=$(‘#district’).val();

    $.ajax({
    url: “index.php?r=dashboard/groups&district1=”+district,
    method: “GET”,
    dataType: “json”,
    success: function(data) {

    console.log(data);
    var district3 = [];
    var groups3 = [];

    for(var i in data) {
    district3.push(” ” +data[i].District);
    groups3.push(data[i].Groups);
    }

    var chartdata = {
    labels: district3,
    datasets : [
    {
    label: ‘Groups’,
    backgroundColor: ‘skyblue’,
    borderWidth:1,
    data: groups3
    }
    ]
    };

    var ctx = document.getElementById(“district_wise_group_1″);

    var barGraph = new Chart(ctx, {
    type: ‘bar’,
    data: chartdata,

    options: {
    scales: {
    yAxes: [{
    ticks: {
    beginAtZero:true,
    stepSize: 1

    },

    }],
    xAxes: [{
    barPercentage: 0.1
    }]
    },
    title: {
    display: true,
    text: ‘District wise Groups’,
    fontSize:15,
    fontColor:”black”,
    fontStyle:”bold”
    }

    },

    });

    if(window.bar != undefined)
    window.bar.destroy();
    window.bar = new Chart(ctx, {});

    },
    error: function(data) {
    console.log(data);
    }

    });

    });

    $(‘#reset’).on(‘click’, function () {

    $.ajax({
    url: “index.php?r=dashboard/grouprecords”,
    method: “GET”,
    dataType: “json”,
    success: function(data) {

    console.log(data);
    var district3 = [];
    var groups3 = [];

    for(var i in data) {
    district3.push(” ” +data[i].District);
    groups3.push(data[i].Groups);
    }

    var chartdata = {
    labels: district3,
    datasets : [
    {
    label: ‘Groups’,
    backgroundColor: ‘skyblue’,
    borderWidth:1,
    data: groups3
    }
    ]
    };

    var ctx = document.getElementById(“district_wise_group_1″);

    var barGraph = new Chart(ctx, {
    type: ‘bar’,
    data: chartdata,

    options: {
    scales: {
    yAxes: [{
    ticks: {
    beginAtZero:true,
    stepSize: 1

    },

    }],
    xAxes: [{
    barPercentage: 0.1
    }]
    },
    title: {
    display: true,
    text: ‘District wise Groups’,
    fontSize:15,
    fontColor:”black”,
    fontStyle:”bold”
    }

    },

    });

    },
    error: function(data) {
    console.log(data);
    }

    });

    });

    });

    1. Ajay Malhotra Avatar

      I think, you are you using it wrong way. Please check my code again carefully.

      thank you

  12. Neeraj Avatar
    Neeraj

    Thanks , solved my problem !

  13. Vijay Avatar
    Vijay

    Hi Ajay Malhotra
    I am using LIghtning component(Salesforce) and using

    inside loop and getting same issue
    and using ur code like below but solved 🙁

    ({
    createGraph : function(cmp, temp, selectedObjectName, viewtype) {

    var dataMap = {“chartLabels”: Object.keys(temp),
    “chartData”: Object.values(temp)
    };

    var el = cmp.find(‘barChart’).getElement();
    var ctx = el.getContext(‘2d’);

    var myChart = new Chart(ctx, {
    type: viewtype,
    data: {
    labels: dataMap.chartLabels,
    datasets: [
    {
    label: selectedObjectName,
    backgroundColor: “#3399ff”,
    data: dataMap.chartData
    }
    ]
    },
    options: {
    scales: {
    yAxes: [{
    ticks: {
    beginAtZero: true,
    // label formate for y axes
    // callback: function(value, index, values) {
    // return “U$ ” + (value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, ‘$&,’);
    // }
    max: 80,
    autoSkip: false,
    stacked: true
    }
    }] ,
    xAxes: [{
    gridLines: {
    offsetGridLines: true
    },
    ticks: {
    beginAtZero: true,
    // label formate for y axes
    // callback: function(value, index, values) {
    // return “U$ ” + (value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, ‘$&,’);
    // }
    max: 80,
    autoSkip: false,
    stacked: true
    }
    }]
    }
    },
    });

    var ctxLine = document.getElementById(“barChart”).getContext(“2d”);
    if(window.bar != undefined)
    window.bar.destroy();
    window.bar = new Chart(ctxLine, {});

    }
    })

    1. Ajay Malhotra Avatar

      Inside loop and there are one chart or multiple charts?

  14. brahim belkaz Avatar
    brahim belkaz

    thank you so much .

  15. tukaram jadhav Avatar
    tukaram jadhav

    hello bro i have same issue please me

    1. Ajay Malhotra Avatar

      Did you use my code?

  16. Andres Avatar
    Andres

    Thank you! it worked like a charm but for anyone out there that wasn’t sure on how to use it, in my case I had a function that took data as a parameter from an ajax call and inside that function I created my chart(Doughnut) so I simply replaced my old code:

    function loadTimelineEntriesCreatedByUserChart(data){
    // I processed data here…
    var ctx = $(“#timeline-created-by-user”).get(0).getContext(“2d”);
    var myChart = new Chart(ctx, {
    type: ‘doughnut’,
    data: {
    labels: theLabelsTop5,
    datasets: [{
    label: ‘# of Votes’,
    data: theDataTop5,
    backgroundColor: dynamicColors(),
    borderColor: dynamicColors(),
    borderWidth: 1
    }]
    },
    options: {
    responsive: false,
    legend: {
    position: ‘right’,
    labels: {
    boxWidth: 12
    }
    }
    }
    });
    }

    to :
    function loadTimelineEntriesCreatedByUserChart(data){
    // I processed data here…
    var ctx = $(“#timeline-created-by-user”).get(0).getContext(“2d”);

    if(this.chartTCBU != undefined){
    window.chartTCBU.destroy();
    }
    window.chartTCBU = new Chart(ctx, {
    type: ‘doughnut’,
    data: {
    labels: theLabelsTop5,
    datasets: [{
    label: ‘# of Votes’,
    data: theDataTop5,
    backgroundColor: dynamicColors(),
    borderColor: dynamicColors(),
    borderWidth: 1
    }]
    },
    options: {
    responsive: false,
    legend: {
    position: ‘right’,
    labels: {
    boxWidth: 12
    }
    }
    }
    });
    }

  17. OdooS Avatar
    OdooS

    Its not working for my code.
    Anyone can help me?

  18. Rajitha Gamage Avatar
    Rajitha Gamage

    Thanks brother it’s reallly working

  19. Ethan Avatar
    Ethan

    I don’t really understand why window.bar works instead of origin chart name. Maybe it’s correlated to the source code of Chart.js? But anyway it works perfectly. Thanks man!

  20. Sreerup Karmakar Avatar
    Sreerup Karmakar

    My intention is to update the chart on change of radio button. Can you help me where should I make the changes, as I followed your solution but not working. Here is the link to the code https://www.codepile.net/pile/G7rroN7Q

    1. Ajay Malhotra Avatar

      Hi I will check and update you.
      Thanks

  21. YenNhiTran Avatar
    YenNhiTran

    thank you so much, it works!!!!! I’m stuck 2 two days and many thanksss

    1. Ajay Malhotra Avatar
  22. dubesh shrestha Avatar
    dubesh shrestha

    Thank you so much.. really Nice…

  23. Ashutosh Avatar
    Ashutosh

    Thanks a lot It works

  24. Hari Avatar
    Hari

    Thank you so so much..it worked!!

    1. Ajay Malhotra Avatar

      Great and welcome.

  25. laxmi mohanty Avatar
    laxmi mohanty

    hi ajay
    my code is something different , in one dropdown onchange event I am binding the data, where there are 4 charts and i am dynamically handling using a tag.
    for example i am sending 2 functions here..

    getWSchartStandardData(tag:any){
    const elem = document.getElementById(‘standardChart’);
    const ctx:any = elem?.getContext(‘2d’);
    const gradient = ctx.createLinearGradient(0, 0, 0, 200);
    gradient.addColorStop(0, ‘#0098b8’);
    gradient.addColorStop(1, ‘#40afc9’);

    ////let datarr: any = [];
    //let levarr: any = [];
    this.levarr = this.stdlabelVal;
    this.datarr = this.stdDataArr;

    const datamin = Math.min(…this.datarr);
    let min = (datamin – 5 < 0) ? 0 : Math.floor(datamin – 5);
    let labelTag='';
    let labelString='';
    let unit:any;
    if(tag==1){
    labelTag = "Network Availability (Standard Data)";
    labelString = "Percentage (%)";
    unit = "%";
    }
    if(tag==2){
    labelTag = "Jitter (Standard Data)";
    labelString = "Milliseconds (ms)";
    unit = "ms";
    }
    if(tag==3){
    labelTag = "Latency (Standard Data)";
    labelString = "Milliseconds (ms)";
    unit = "ms";
    }
    if(tag==4){
    labelTag = "Packet Delivery (Standard Data)";
    labelString = "Percentage (%)";
    unit = "%";
    }
    console.log(this.levarr)
    console.log(this.datarr)
    this.chart = new Chart(ctx, {
    type: 'bar', //this denotes tha type of chart

    data: {// values on X-Axis
    labels: this.levarr,
    datasets: [
    {
    label: labelTag,
    data: this.datarr,
    backgroundColor: gradient
    }
    ]
    },
    options: {
    layout: {
    padding: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0
    }
    },
    legend: {
    display: false
    },
    responsive: true,
    maintainAspectRatio: false,
    scales: {
    yAxes: [{
    ticks: {
    // beginAtZero:true,
    precision: 0,
    min: min,
    maxTicksLimit: Math.max(…this.datarr)
    },
    display: true,
    scaleLabel: {
    display: true,
    labelString: labelString,
    },
    }],
    xAxes: [
    {
    scaleLabel: {
    display: true,
    labelString: "Months",
    },
    },
    ],
    }
    }
    });
    }

    getWSchartRealTime(tag:any){
    const elem = document.getElementById(‘realtimeChart’);
    const ctx:any = elem?.getContext(‘2d’);
    const gradient = ctx.createLinearGradient(0, 0, 0, 200);
    gradient.addColorStop(0, ‘#0098b8’);
    gradient.addColorStop(1, ‘#40afc9’);

    ////let datarr: any = [];
    //let levarr: any = [];
    this.levarr = this.rTlabelVal;
    this.datarr = this.rTDataArr;

    const datamin = Math.min(…this.datarr);
    let min = (datamin – 5 < 0) ? 0 : Math.floor(datamin – 5);
    let labelTag='';
    let labelString='';
    let unit:any;
    if(tag==1){
    labelTag = "Network Availability (Real Time)";
    labelString = "Percentage (%)";
    unit = "%";
    }
    if(tag==2){
    labelTag = "Jitter (Real Time)";
    labelString = "Milliseconds (ms)";
    unit = "ms";
    }
    if(tag==3){
    labelTag = "Latency (Real Time)";
    labelString = "Milliseconds (ms)";
    unit = "ms";
    }
    if(tag==4){
    labelTag = "Packet Delivery (Real Time)";
    labelString = "Percentage (%)";
    unit = "%";
    }
    this.chart = new Chart(ctx, {
    type: 'bar', //this denotes tha type of chart

    data: {// values on X-Axis
    labels: this.levarr,
    datasets: [
    {
    label: labelTag,
    data: this.datarr,
    backgroundColor: gradient
    }
    ]
    },
    options: {
    layout: {
    padding: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0
    }
    },
    legend: {
    display: false
    },
    responsive: true,
    maintainAspectRatio: false,
    scales: {
    yAxes: [{
    ticks: {
    // beginAtZero:true,
    precision: 0,
    min: min,
    maxTicksLimit: Math.max(…this.datarr)
    },
    display: true,
    scaleLabel: {
    display: true,
    labelString: labelString,
    },
    }],
    xAxes: [
    {
    scaleLabel: {
    display: true,
    labelString: "Months",
    },
    },
    ],
    }
    }
    });
    }

    i use ngdestroy
    ngOnDestroy() {
    if(this.chart!=undefined && this.chart!=null)
    this.chart.destroy();
    }

    the destroy is not working properly … as no data is showing after that .
    any help please..thank you

    1. therichpost Avatar

      Hi I got your point. Your data is coming from API but your chart init first so it is showing no data.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.