Search code examples
javascriptjqueryhighchartstooltip

Highcharts crosshair with labels on axes


Is it possible to make highcharts crosshair that vill show actual value on the axis in the separate label?

Regular crosshair example out from API doesnt do this. If I set

tooltip: {
        crosshairs: [true, true]
    }

, it doesnt do what I need. I need chart to look like this:

enter image description here


Solution

  • It's just general idea: http://jsfiddle.net/r7fdh/ - you need to add checking if cursor is inside plot (use chart.plot[Left/Top/Width/Height]) and you may need to use something else than event.page[X/Y] for getting position.

    Code:

    $("#container").mousemove(move);
    
    var chart = new Highcharts.Chart({
    
        chart: {
            renderTo: 'container'
        },
        series: [{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }]
    
    });
    
    function move(event) {
        var x = event.pageX,
            y = event.pageY,
            path = ['M', chart.plotLeft, y,
                'L', chart.plotLeft + chart.plotWidth, y,
                'M', x, chart.plotTop,
                'L', x, chart.plotTop + chart.plotHeight];
    
        if (chart.crossLines) {
            // update lines
            chart.crossLines.attr({
                d: path
            });
        } else {
            // draw lines
            chart.crossLines = chart.renderer.path(path).attr({
                'stroke-width': 2,
                stroke: 'green',
                zIndex: 10
            }).add();
        }
    
        if (chart.crossLabel) {
            // update label
            chart.crossLabel.attr({
                y: y + 6,
                text: chart.yAxis[0].toValue(y).toFixed(2)
            });
        } else {
            // draw label
            chart.crossLabel = chart.renderer.text(chart.yAxis[0].toValue(y).toFixed(2), chart.plotLeft - 40, y + 6).add();
        }
    }