Search code examples
javascriptchart.jsuislider

Implementing range slider in Chart.js


I am currently trying to use a range slider to manipulate the bars on my Chart.js graph. However, even though I have the code written, which I used from a previous project, it still won't work. I have attached the code below, and if someone can tell me why clicking sliding the range slider won't change the bar graph.

I have two main pieces of code:

<input type="range" class="slider" value="5" min="30" max="50" id="points" onchange="function()">

var heating [] =  parseInt(document.querySelector('#points').value);

Essentially, the heating variable is assigned to this, and then by onchange the function is run. Now, I'm not sure why it's not happening as of now. If someone can check, that would be great. I am attaching all the code below.

INDEX.HTML FILE

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lobster|Montserrat|Tangerine">
</head>
<body>
  <div id="chart-container">
    <canvas id="chart" style="font-family: 'Tangerine', serif; font-size: 1.9em;"></canvas>
    <form action="test.php" method="get">
      <label>BlockGroup<input  class="flex-wrapper"  type="text" name="BlockGroup"  placeholder="60014431031" ><br><br>    
        <label>Zip Code: <input style=" display:inline;" class="flex-wrapper"   type="text" name="ZipCode"  placeholder="94538"><br><br>    
        <label>City: <input style=" display:inline;" class="flex-wrapper"   type="text" name="City"  placeholder="Fremont"><br><br>    
        <label>State: <input style=" display:inline;" class="flex-wrapper" type="text" name="State"  placeholder="California"><br><br>    
        <!-- <label>County: <input style=" display:inline;" class="flex-wrapper"  id="myInput" type="text" name="County"  placeholder="Alameda" value='<?php echo $firstname; ?>' ><br><br> -->    
        <input type="submit" value="Submit">    
    </form>    
  </div>    
  <button id="shuffle">Sort Data</button>    
  <br>
  <p> <b> Heating Electrification <b> <p>
    <input type="range" class="slider" value="5" min="30" max="50"  id="points" onchange="function()">    
  <!-- javascript -->
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
  <script type="text/javascript" src="app.js"></script>    
</body>
</html>

APP.JS

const CHART = document.getElementById("chart");
var barChart = [];

Chart.defaults.global.animation.duration = 3000;
Chart.plugins.register({
  beforeUpdate: function(chart) {
    if (chart.options.sort) {
      // Get the data from each datasets.
      var dataArray = [];
      $.each(chart.data.datasets, function() {
        dataArray.push(this.data);
      });
      // Get the index after sorted.
      let dataIndexes = dataArray.map((d, i) => i);
      dataIndexes.sort((a, b) => {
        return dataArray[a] - dataArray[b];
      });
      // create after sorted datasets.
      var tempDatasets = [];
      $.each(dataIndexes, function() {
        tempDatasets.push(chart.data.datasets[this]);
      });
      // apply it
      chart.data.datasets = tempDatasets;
      return tempDatasets;
    }
  }
});

$(document).ready(function() {
  $.ajax({
    url: "http://localhost:8888/test.php",
    method: "GET",
    success: function(data) {
      console.log(data);
      var sample = [];
      var electric = [];
      var mpg = [];
      var urban = [];
      var vmt = [];
      var airtravel = [];
      var renewable = [];
      var conservation = [];
      var heating = [];
      var water = [];
      var cefficiency = [];
      var shiftc = [];
      var healthyd = [];
      var heating[] = parseInt(document.querySelector('#points').value);

      for (var i in data) {
        sample.push(data[i].sample);
        electric.push(parseInt(data[i].electric));
        mpg.push(parseInt(data[i].mpg));
        urban.push(parseInt(data[i].urban));
        vmt.push(parseInt(data[i].vmt));
        airtravel.push(parseInt(data[i].airtravel));
        renewable.push(parseInt(data[i].renewable));
        conservation.push(parseInt(data[i].conservation));
        heating.push(parseInt(data[i].heating));
        water.push(parseInt(data[i].water));
        cefficiency.push(parseInt(data[i].cefficiency));
        shiftc.push(parseInt(data[i].shiftc));
        healthyd.push(parseInt(data[i].healthyd));
      }

      var chartdata = {
        labels: sample,
        datasets: [{
            label: "Electric Vehicles",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: electric,
            stack: 1
          },
          {
            label: "50+ MPG Vehicles",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: mpg,
            stack: 2
          },
          {
            label: "Urban Infill",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: urban,
            stack: 3
          },
          {
            label: "VMT Reduction",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: vmt,
            stack: 4
          },
          {
            label: "Air Travel Reduction",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: airtravel,
            stack: 5
          },
          {
            label: "Renewable Electricity",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: renewable,
            stack: 6
          },
          {
            label: "Energy Eficiency and Conservation",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: conservation,
            stack: 7
          },
          {
            label: "Heating Electrification",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: heating,
            stack: 8
          },
          {
            label: "Water & Waste",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: water,
            stack: 9
          },
          {
            label: "Commercial Efficiency",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: cefficiency,
            stack: 10
          },

          {
            label: "Shift Consumption",
            backgroundColor: "rgba(63,235,243,0.8)",
            data: shiftc,
            stack: 11
          },
          {
            label: "Healthy Diets",
            backgroundColor: "rgba(120,255,0,0.8)",
            data: healthyd,
            stack: 12
          },
        ]
      };

      barChart = new Chart(CHART, {
        type: 'horizontalBar',
        data: chartdata,
      });

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

document.getElementById('shuffle').addEventListener('click', function() {
  barChart.options.sort = true;
  barChart.update();
  barChart.options.sort = true;
});

Also, here is a picture of the above situation. When sliding my range slider nothing happens, so I am sort of concerned:

HTML File on Web Picture


Solution

  • Can you still get motivated to solve this problem?
    It's an easy thing, really. However, you need to understand a little bit more how it works.

    First of all, you wrote this code on the $(document).ready, that means this code is only ran after page ready.(once) There's no way that the chart is updated.

    var heating[] = parseInt(document.querySelector('#points').value);
    

    Also, you added event.

    <input type="range" class="slider" value="5" min="30" max="50" id="points" onchange="function()">
    

    This fact shows me you really don't understand things. Usually, you need to call a function, like this.

    <input type="range" class="slider" value="5" min="30" max="50" id="points" onchange="testFunction()">
    
    function testFunction() {
        // update chart...
    }
    

    Or add event (this time I use jQuery)

    <input type="range" class="slider" value="5" min="30" max="50" id="points">
    
    $("#points").on("change", function() {
        // update chart...
    });
    

    Lastly, to update Chart.js, you need to update the value in the datasets, and call its update method. You can updated a just one datasets.

    // Get heating datasets. (Yes, you can write 'barGraph.data.datasets[7].data = xxx')
    var heatDatasts = barGraph.data.datasets[7];
    // Update value
    heatDatasts.data = [$(this).val()];
    // Apply it to the view.
    barGraph.update();
    

    If you can't use a debug tool, I recommend at least use an alert. (I used in the jsfiddle)
    That way you can tell either the code is run or not.

    Example

    UPDATED1
    For first question.
    I updated the image, and I hope you understand.
    There are various way, but I pick up the two. Explain

    /*************** Pattern1 (Simply, using jQuery each) ***************/
    // Loop
    $.each(barGraph.data.datasets, function() {
        // Check the label or stack, in this case.
        if (this.label === "Heating Electrification") {
            // It's okay
            // heatDatasets = this;
            // Set value is also okay.
            this.data = [sliderValue];
            return false;
        }
    });
     /*************** Pattern2 (using jQuery grep or filter)***************/
     var heatDatasets = $.grep(barGraph.data.datasets, function(datasets) {
         return (datasets.label === "Heating Electrification");
     })[0];
     heatDatasets.data = [sliderValue];
    

    The second question.
    Basically, we don't use JavaScript variable on HTML. Some framework or library can looks like it can be possible, though.

    // Set value, min and max.
    // We can't use JavaScript variable on HTML, usually.
    var slider = $("#points");
    slider.prop("min", 0);
    slider.prop("max", 1000);
    slider.val(1000);
    

    For example

    UPDATED2
    I found that datasets can have any parameters, so you can add parameters anything.
    For example, I added 'barId' and modified the sliders(add id, which is the same as 'barId'.)
    For example