How to invoke "click" event programmatically in d3?

not sure why, but there appears to be a discrepancy with the way jQuery and d3 handle events that causes a jQuery induced click event $("#some-d3-element").click() to not dispatch to the d3 element.

a workaround:

jQuery.fn.d3Click = function () {
  this.each(function (i, e) {
    var evt = new MouseEvent("click");
    e.dispatchEvent(evt);
  });
};

and then call it:

$("#some-d3-element").d3Click();

Simply call the .on method as a getter for the registered value (i.e. your handler function), then call the result of that:

g.select("path").on("click")();

It gets a little more complicated if your handler uses the bound data and/or event fields, or if you've got multiple event listeners bound (e.g "click.thing1" and "click.thing2"). In that case, you're probably best off just firing a fake event using the standard DOM methods:

var e = document.createEvent('UIEvents');
e.initUIEvent('click', true, true, /* ... */);
g.select("path").node().dispatchEvent(e);

With D3 v4 you will likely want this:

d3.select('#some-id').dispatch('click');

Ref.: https://github.com/d3/d3-selection#selection_dispatch


This works. I'm using pie charts, so I'm selecting all the "selected" pie slices, and for each of them, retrieving the attached "click" callback (that I have attached in another portion of code not included here, using d3's .on() method) and then invoking with the expected parameters in the correct context.

d3.selectAll("g.selected").each(function(d, i) {
    var onClickFunc = d3.select(this).on("click");
    onClickFunc.apply(this, [d, i]);
});