If you want to catch a click event on a bullet or column in chart you can use the old trusty "clickGraphItem" event. Just add the listener and be done with it:
chart.addListener("clickGraphItem", function (event) { // click event occurred // let's do something cool });
However, sometimes you need to do something else on double click. Handling double click events in JavaScript is problematic, unreliable and it differs from browser to browser.
The solution is to monitor time passed between two "click" events. If the last click occurred, say, less than 300 milliseconds ago, we treat the subsequent click as the double click.
To make it even more realistic, we delay all click events by 300 milliseconds to wait for second click to occur immediately after that. This will ensure that on double click, no single click will be triggered.
OK, so here is the code: (it's commented to make it understandable; link to a working example at the end of the article)
// SET UP CLICK EVENTS // create prerequisite properties AmCharts.clickTimeout = 0; // this will hold setTimeout reference AmCharts.lastClick = 0; // last click timestamp AmCharts.doubleClickDuration = 300; // distance between clicks in ms - if it's less than that - it's a doubleckick // let's define functions to actually do something on clicks/doubleclicks // you will want to replace the insides of these with your own code AmCharts.doSingleClick = function (event) { var div = document.getElementById("events"); div.innerHTML = "Click<br />" + div.innerHTML; } AmCharts.doDoubleClick = function (event) { var div = document.getElementById("events"); div.innerHTML = "Double Click<br />" + div.innerHTML; } // create click handler AmCharts.myClickHandler = function (event) { var ts = (new Date()).getTime(); if ((ts - AmCharts.lastClick) < AmCharts.doubleClickDuration) { // it's double click! // let's clear the timeout so the "click" event does not fire if (AmCharts.clickTimeout) { clearTimeout(AmCharts.clickTimeout); } // reset last click AmCharts.lastClick = 0; // now let's do whatever we want to do on double-click AmCharts.doDoubleClick(event); } else { // single click! // let's delay it to see if a second click will come through AmCharts.clickTimeout = setTimeout(function () { // let's do whatever we want to do on single click AmCharts.doSingleClick(event); }, AmCharts.doubleClickDuration); } AmCharts.lastClick = ts; } // add handler to the chart chart.addListener("clickGraphItem", AmCharts.myClickHandler);
You will probably need to modify the AmCharts.doSingleClick and AmCharts.doDoubleClick functions to make them do whatever you want them to do.
And here's the link to a live example: http://jsfiddle.net/amcharts/j4yL8/
(click or double click on any bullet or column)
Comments