3

How to add Event Listeners to google charts(Column Chart) column name(label). For example, the lables such as 2004,2005,2006, 2007 should throw events.

When the user clicks on column name(label), event(select) should be triggered.

There is a provision to add event listener to the visualisation data but not to the column label.

Fire an event with the name 'select' when the user selects some data within the visualization. The event does not send any arguments to the listening functions. https://developers.google.com/chart/interactive/docs/dev/events#The_Select_Event

enter image description here

0

2 Answers 2

4

Use a "click" event handler:

google.visualization.events.addListener(chart, 'click', function(e) {
    var match = e.targetID.match(/hAxis#\d#label#(\d)/);
    if (match != null && match.length) {
        var rowIndex = parseInt(match[1]);
        // get the value from column 0 in the clicked row
        var label = data.getValue(rowIndex, 0);
        alert('You clicked on ' + label);
    }
});
0
0

One option is the following: each column label is created as svg text element like:

<g>
<text text-anchor="middle" x="233.75" y="425.9" font-family="Arial" font-size="14" stroke="none" stroke-width="0" fill="#222222">2004</text>
</g>

so you can get those elements and attach event listeners using:

    var colLabels = document.querySelectorAll('text[text-anchor="middle"]');

    for (var i = 0; i < colLabels.length; ++i) {
        console.log(colLabels[i]);
        colLabels[i].addEventListener('click', function(e) {
            console.log(this.innerHTML);

            console.log('event');
            console.log(e);
        }, false); 
    }

There is a problem with this approach: you will attach event listener also to hAxis title Year so you will have to filter it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.