Last Updated: February 25, 2016
·
4.818K
· jacaetevha

Programmatically change column values in HighCharts

This fiddle uses button actions and a slider to change column values in a column-based HighChart.

Clicking on a column changes what the slider considers to be the primary column (the default is the middle column). Sliding to the right increases the currently selected column's value. It then distributes the difference of its new value and its old value into the columns to the right of it (increasing their values), and then the columns to the left of it (decreasing their values). Sliding to the left does the opposite. Finally, the values in the columns are weighted to add up to 100 and the slider's value is updated with the value of the current column.

It's sort of convoluted, but shows how to interact with several components at once, especially with the HighChart chart. Most of the work happens in the sliderChange function:

var sliderChange = function(event, ui) {
    // reset chart title
    chart.setTitle({
        text: 'Custom'
    });
    var difference = ui.value - originalValue;
    originalValue = ui.value;
    datapointAt(currentIndex).update(originalValue, false);
    var total = originalValue;
    // update all values with raw value, and calculate total
    for (var index = 1; index < 6; index++) {
        if (index !== currentIndex) {
            var datapoint = datapointAt(index);
            var newValue = 0;
            newValue = index < currentIndex ? datapoint.y - difference : datapoint.y + difference;
            if (newValue < 0) {
                newValue = 0;
            }
            datapoint.update(newValue, false);
            total += newValue;
        }
    }
    // weight the values from 0 - 100
    for (var index = 1; index < 6; index++) {
        var datapoint = datapointAt(index);
        var newValue = Math.floor(100 * datapoint.y / total);
        datapoint.update(newValue, true);
        if (index === currentIndex) {
            originalValue = newValue;
        }
    }
    updateSliderWithCurrentData();
};