Categories

Friday, April 26, 2024
#919814419350 therichposts@gmail.com
ChartjsJquery

Solved : hovering over Chartjs Bar Chart showing old data

hovering over Chartjs Bar Chart showing old data

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

56 Comments

    • 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

      • 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

  • 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.

  • 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);
    }

    });

    });

    });

  • 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, {});

    }
    })

  • 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
    }
    }
    }
    });
    }

  • 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!

  • 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

Leave a Reply

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