Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling click events on chart grid columns #2941

Open
fmal opened this issue Apr 5, 2016 · 22 comments
Open

Handling click events on chart grid columns #2941

fmal opened this issue Apr 5, 2016 · 22 comments
Assignees
Labels
difficulty: normal Issues that can be fixed with the average difficulty. enhancement priority: high topic: event
Milestone

Comments

@fmal
Copy link

fmal commented Apr 5, 2016

问题简述 (One-line summary)

Is there any way to capture click events on chart columns? My goal is to create a chart with possibility to select individual columns by clicking on them.

版本及环境 (Version & Environment)

  • ECharts 版本 (ECharts version): 3.1.3
  • 浏览器类型和版本 (Browser version): Google Chrome 49.0.2623.110
  • 操作系统类型和版本 (OS Version): Windows 8

期望结果 (Expected behaviour)

I would expect that chart.on('click', () => { console.log('click'); }); captures click events on the entire chart. Or at least i would expect an option like grid: { clickable: true }.

可能哪里有问题 (What went wrong)

chart.on('click', () => { console.log('click'); }); registers event only on chart components such as bars etc.

ECharts配置项 (ECharts option)

option = {

}
@coretez
Copy link

coretez commented Jun 1, 2016

You activate clickable on the chart. Then you need to create a function that captures the click. The function is assigned output the options. Example is:
http://echarts.baidu.com/echarts2/doc/example/event.html

@dev-johnny-gh
Copy link

But when I click between two columns, I can not receive any event. I wish I can get the dataIndex where the blue line located. Any idea? @coretez

image

@smnbbrv
Copy link

smnbbrv commented Jul 9, 2018

For me the following works:

  • on tooltip formatter remember the tooltip data into some global variable
  • add normal HTML click event listener on the chart parent element
  • use this click event in combination with data from tooltip

@hamidhasnain
Copy link

@fmal Did you happen to get a solution?

@jeffz2012
Copy link

https://echarts.apache.org/api.html#events.Mouse%20events.click

@prapakou
Copy link

prapakou commented Apr 5, 2019

https://echarts.apache.org/api.html#events.Mouse%20events.click

it doesn't work, when click not on line.

@Ovilia Ovilia added the stale Inactive for a long time. Will be closed in 7 days. label Jun 28, 2019
@stale stale bot closed this as completed Jul 5, 2019
@smnbbrv
Copy link

smnbbrv commented Jul 5, 2019

@Ovilia what does stale mean? The issue is not fixed, it is easily reproducible, lots of people experiencing it... Why is this stale?

@OlmoBarberis
Copy link

OlmoBarberis commented Sep 5, 2019

But when I click between two columns, I can not receive any event. I wish I can get the dataIndex where the blue line located. Any idea? @coretez

image

Have you tried with:
const zr = chart.getZr(); zr.on('click', (params) => { console.log(params); });

You can take extract coordinates from params and get dataIndex with chart.convertFromPixel.

I have used it in my project and I had found an example that used getZr() but I can't find it again now!

EDIT: I have found the example:
https://echarts.apache.org/examples/en/editor.html?c=line-pen

@Ovilia
Copy link
Contributor

Ovilia commented Sep 6, 2019

stale are for issues that aren't active for years.
I will re-open this and see if we can fix this ASAP.

@Ovilia Ovilia reopened this Sep 6, 2019
@stale stale bot removed stale Inactive for a long time. Will be closed in 7 days. labels Sep 6, 2019
@Ovilia
Copy link
Contributor

Ovilia commented Sep 6, 2019

We will discuss if to put this feature in ECharts v5.0 or the next major release. I'm adding the milestone 4.5.0 for now for milestone discussion and it may also be moved to 5.0.0 if we decide to implement this in v5.0.
Thanks for understanding.

@apache apache deleted a comment from stale bot Sep 6, 2019
@apache apache deleted a comment from stale bot Sep 6, 2019
@Ovilia Ovilia added difficulty: normal Issues that can be fixed with the average difficulty. priority: high labels Sep 6, 2019
@Ovilia Ovilia added this to the 4.5.0 milestone Sep 6, 2019
@pissang pissang self-assigned this Sep 24, 2019
@pissang pissang modified the milestones: 4.5.0, 5.0.0 Oct 31, 2019
@MCMcCallum
Copy link

One way to do this is to use an invisible graphic as a clickable element that covers the chart area. That is, add the following 'graphic' option to your chart

var chart_width = 1000
var chart_height = 200

function(params) {
  console.log('CLICK')
}

{graphic: {
  type: 'rect',
  shape: {
    x: 0,
    y: 0,
    height: chart_height,
    width: chart_width
  },
  onclick: onClick,
  invisible: true,
  z: 100
}}

@ljieyao
Copy link

ljieyao commented Apr 10, 2020

looking forward to have this feature too

@DoonPort0422
Copy link

DoonPort0422 commented Jul 7, 2020

I am looking for this feature too.
Execute me, when will v5.0 be released? Thanks.


I am sorry, is this feature same as the following one (#9281), that,
Ovilia said:
We are going to add a feature that mouse events (mouseover, click, and etc.) be fired at grid area, which is the blank area

@Socrates005
Copy link

I got a similar problem with calendar. Although it seems to work, but gives some strange 'dates' back. Anyone an idea?
part option<<
calendar: {
range: ['2020-10-01','2020-10-30'],
cellSize: 'auto'
},
series: {
name:'ls01',
type: 'scatter',
coordinateSystem: 'calendar',
symbolSize: function(val) {
return val[1] / 50;
},
data: [['2020-10-19', 500],['2020-10-15',200]]
}

var zr = chartObstructie.getZr();
zr.on('click',function(params) {
    var pointInPixel = [params.offsetX, params.offsetY];
    var pointInGrid = chartObstructie.convertFromPixel('calendar', pointInPixel);

    console.log(new Date(pointInGrid));
});

When you click the first date -> 10/10 and suddenly it jumps several months/years - depending on the selected range.

@tamersalama
Copy link

tamersalama commented Feb 9, 2021

It'd be great to have this feature. Clicking on a series isn't convenient for a large data set (the tooltip already displays the closest value), while using zRender or convertFromPixel doesn't give the value of the closest point (rather gives just the value at the approximate clicked mouse position).
Thank you for a great library!

@tamersalama
Copy link

Here's my work-around (for line charts). It's not very efficient as it tries to extract the closest match in an array.
Tooltip already has the necessary logic that provides the closest match (or it's passed to it). Unfortunately, I wasn't able to get to that code or use it. The tooltip formatter can be used as a yet another work-around.

    /**
    * Find the closest number in an array from the passed number argument
    * This is used in click events to get the series number
    * https://www.tutorialspoint.com/get-closest-number-out-of-array-javascript
    */
    const closest = (arr, num) => {
        return arr.reduce((acc, val) => {
           if(Math.abs(val - num) < Math.abs(acc)){
              return val - num;
           }else{
              return acc;
           }
        }, Infinity) + num;
     }

     zr = chart.getZr();
     zr.on('dblclick', params => {
         var pointInPixel = [params.offsetX, params.offsetY];
         var pointInGrid = chart.convertFromPixel('series', pointInPixel);

         seriesDataX = chart.getOption().series[0].data.map(x => x[0])
         closestXPoint = closest(seriesDataX, pointInGrid[0])

         // Do something with closestXPoint
    });

@xgqfrms
Copy link

xgqfrms commented Apr 17, 2021

online demo

https://www.runoob.com/try/try.php?filename=tryecharts_event1

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts 实例</title>
    <!-- 引入 echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="width: 600px;height:400px;"></div>
    <script type="text/javascript">
        // 基于准备好的dom,初始化ECharts实例
        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        var option = {
            xAxis: {
                data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        // 处理点击事件并且弹出数据名称
        myChart.on('click', function (params) {
            console.log('params', params, params.name);
        });
	myChart.on('click', 'series', function (params) {
            console.log('series', params, params.name);
        });
        myChart.on('click', 'series.line', function (params) {
            console.log('series.line', params, params.name);
        });
    </script>
</body>
</html>

@sshanzel
Copy link

sshanzel commented Jun 20, 2021

@OlmoBarberis, you are a life-saver. Just so you know!

@zbyte64
Copy link

zbyte64 commented Oct 26, 2021

Would be nice if the grid emitted a click event if nothing else catches it. @OlmoBarberis example works, but if you change it from bar to line then it does not work as you might expect, one should be able to click on a series line and emit an event.

@yernarakimzhanov
Copy link

Still not working

@Ovilia Ovilia modified the milestones: 5.x, TBD Sep 1, 2022
@helgasoft
Copy link

helgasoft commented Dec 17, 2022

@zbyte64, @tamersalama, here is a workaround to detect line mouseover and click events.
Since there is a triggerLineEvent now, workaround thru zRender is no longer needed.

  Demo Code - move mouse + click on lines. Chart's title is used as text output.

image

@Pedanfer
Copy link

Pedanfer commented Aug 31, 2024

Here is a more explicit example for 2024 in React using @OlmoBarberis method.

 // Not shown but this goes into ref prop of your echarts component
  const chartRef = useRef<EChartsInstance>();

  useEffect(() => {
    var zr = chartRef.current.getZr();
    zr.on("click", function (params) {
      var pointInPixel = [params.offsetX, params.offsetY];
      var pointInGrid = chartRef.current.convertFromPixel({ gridIndex: 0 }, pointInPixel);

      if (pointInGrid) {
        // Index 0 is -0 for some reason
        var xValue = pointInGrid[0] * 1;
        var xAxis = chartRef.current.getModel().getComponent("xAxis", 0);
        const categoryClicked = xAxis.getCategories()[xValue];
        console.log("Category clicked:", categoryClicked);
      }
    });
  }, []);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
difficulty: normal Issues that can be fixed with the average difficulty. enhancement priority: high topic: event
Projects
None yet
Development

No branches or pull requests