Chart.js Update start date with button selector

Have been trying to add a range selector to my chart.

This is what I added to my php file.

  <div id="range-selector">
    <input type="button" id="30m" class="period ui-button" value="30m" />
    <input type="button" id="1h" class="period ui-button" value="1h"/>
    <input type="button" id="6h" class="period ui-button" value="6h"/>
    <input type="button" id="12h" class="period ui-button" value="12h"/>
    <input type="button" id="24h" class="period ui-button" value="24h"/>
  </div>

this is my chart.js file

var fanspeedlabels = [], fanspeed = [], temp = [];



function updateFanSpeedData() {


    function formatDate(itemdate) {
        return moment(itemdate).format("MMM Do HH:mm");
    }

    $.ajax({
        url: 'api.php?getFanSpeed24hrs&PHP',
        dataType: 'json'
    }).done(function (results) {

        results.forEach(function (packet) {
            if (fanspeedlabels.indexOf(formatDate(packet.start_time)) === -1) {
                fanspeedlabels.push(formatDate(packet.start_time));
                fanspeed.push(parseFloat(packet.fanspeed));
                temp.push(parseFloat(packet.temp));

            }

        });
        fanspeedChart.update();
        fanspeeddata = results;
    });
}


setInterval(function () {
    // console.log('updateFanSpeedData');
//    updateFanSpeedData();
}, 6000);


var fanspeedChartctx = document.getElementById("fanspeedChart");
var newfanspeed = fanspeed + "%";
var fanspeedChart = new Chart(fanspeedChartctx, {
    type: 'line',
    data: {
        labels: fanspeedlabels,
        datasets: [{
            label: 'FanSpeed',
            data: fanspeed,
            backgroundColor: 'rgb(60, 141, 188)',
            fill: false,
            borderColor: 'rgb(60, 141, 188)',
            borderWidth: 1,
            cubicInterpolationMode: 'monotone',
            yAxisID: "y-axis-1"
        },
            {
                label: 'Temp',
                data: temp,
                backgroundColor: 'rgba(255, 99, 132, 1)',
                fill: false,
                borderColor: 'rgba(255,99,132,1)',
                borderWidth: 1,
                yAxisID: "y-axis-1"
            }

        ]
    },
    options: {
        hover: {
            animationDuration: 0 // duration of animations when hovering an item
        },
        responsive: true,
        maintainAspectRatio: false,
        legend: {
            display: false
        },
        scales: {
            yAxes: [{
                type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
                display: true,
                position: "left",
                id: "y-axis-1",
                ticks : {
                    min: 0,
                    max: 100
                }
            },
                {
                    type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
                    display: true,
                    position: "right",
                    id: "y-axis-2",
                    ticks : {
                        min: 0,
                        max: 100
                    }
                }
            ],
            xAxes: [
                {
                    display: true,
                    scaleLabel: {
                        display: true
                    },
                    ticks: {
                        maxRotation: 0,
                        minRotation: 0
                    }
                }
            ]
        },
        tooltips: {
            enabled: true,
            mode: "x-axis",
            intersect: false,
            callbacks: {
                label: function(t, d) {
                    var xLabel = d.datasets[t.datasetIndex].label;
                    var yLabel = t.yLabel;
                    if(t.datasetIndex === 0) {
                        return 'Fan Speed: ' + yLabel.toFixed(0) + '%';
                    }
                    else if (t.datasetIndex === 1) {
                        return 'CPU Temp: ' + yLabel.toFixed(0) + '°C';
                    }
                }
            }
        }
    }
});

$(".period").click( function() {
  var period = this.id;
  minValue = new Date();
  switch(period){
    case "30m":
      minValue.setMinutes(minValue.getMinutes() - 30);
      break;
    case "1h":
      minValue.setHours(minValue.getHours() - 1);
      break;
    case "6h":
      minValue.setHours(minValue.getHours() - 6);
      break;
    case "12h":
      minValue.setHours(minValue.getHours() - 12);
      break;
    case "24h":
      minValue.setHours(minValue.getHours() - 24);
      break;
    default:
      minValue
    }
    var startdate = moment(minValue).format("MMM Do HH:mm");
    fanspeedChart.options.scales.xAxes[0].ticks.max = startdate;
    fanspeedChart.update();
});
updateFanSpeedData();

The buttons work, Did have a console.log and the dates change currently but it doesn’t update the chart with the current start point.

Any Help would be great, Starting to feel like I’m Going backwards.

Update something I Found

As I have dug a little deeper. The code seems to work, but because the "startdate" does not equal the exact date from the database it does not work. If by some chance there is the same date in the database it works. Is there a way I can make it so if any date higher than this date add. Dates show up as "Feb 16 19:50". if it sets min as "Feb 16 19:49" it will not work. Have tried suggestedMin aswell

11 thoughts on “Chart.js Update start date with button selector”

  1. As I worked out, as the min didn’t match any dates from my database, needed a way to get the closest date to the date provided.

    Added this and all working great now.

        let closest = Infinity;
    
        fanspeedlabels.forEach(function(d) {
            const date = new Date(d);
    
            if (date >= now && (date < new Date(closest) || date < closest)) {
               closest = d;
            }
        });
        fanspeedChart.options.scales.xAxes[0].ticks.min = closest;
        fanspeedChart.update();
    
    Reply

Leave a Comment