67

I'm trying like that (also at https://gist.github.com/1703994):

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.27.2"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.time.js?1.27.2"></script>

    <script type="text/javascript" src="js-libs/jquery-1.7.js"></script>

    <style>
      <!--
      #test {
      width: 400px;
      height: 500px;
      }
      -->
    </style>
  </head>

  <body>

    <script type="text/javascript">
      $(function() {
        var w = 600,
            h = 350;

        var vis = d3.select("#test").append("svg:svg")
        .attr("width", w)
        .attr("height", h)
        .append("svg:g")
        .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");

        var g = vis.selectAll("g")
        .data([ { x:1 , y: 2} ])
        .enter().append("svg:g");

        g.append("svg:path")
        .attr("fill", "red")
        .attr("stroke", "red")
        .attr("stroke-width", "10")
        .attr("d", "M 100 350 l 150 -300")

        g.select("path")
        .on("click", function() { console.log("Hello"); });

        // XXX: how to execute click programmaticaly?
      })
    </script>

    <div id="test"></div>
  </body>
</html>

But doesn't work

I think we may use https://github.com/mbostock/d3/wiki/Internals#wiki-dispatch_on

But how to do it?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
mad
  • 902
  • 1
  • 7
  • 10

11 Answers11

87

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();
Deewendra Shrestha
  • 2,313
  • 1
  • 23
  • 53
handler
  • 1,463
  • 11
  • 11
71

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);
natevw
  • 16,807
  • 8
  • 66
  • 90
  • 6
    For anyone that's using the latter of @natevw's solution, I filled in the remaining values using `window, 1`. The entire call looks like: `e.initUIEvent("click", true, true, window, 1);` – Andrew C Oct 15 '14 at 23:48
  • using the first method, you'll have the wrong "this" - see Andrew Plank's answer for a fix. – mathheadinclouds May 22 '15 at 05:31
34

With D3 v4 you will likely want this:

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

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

Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
  • 6
    this is the best answer as of 09/2020 – Moustache Sep 06 '20 at 01:22
  • If you need to select a single element from a group of elements based on some condition, you can chain the select on to a selectAll like this: `d3.selectAll('.some-class').select(function(d){ if (condition === true) { return this } }).dispatch('click');`. – neuquen Sep 24 '20 at 15:48
14

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]);
});                
Andrew Plank
  • 942
  • 10
  • 22
8

This answer might be somewhat unrelated - but hopefully useful to someone searching for how to invoke a click event of a SVG element - since jQuery $(mySvgElement).trigger("click") won't work.

This is how you would programmatically trigger/invoke/raise a click event for a SVG element:

var ev = document.createEvent("SVGEvents");
ev.initEvent("click",true,true);

var target = $("svg>g>path[fill='#0011cc']").get(0); // get the SVG element here
target.dispatchEvent(ev);  // like $(target).trigger('click') - but working!
Fredrik Johansson
  • 3,477
  • 23
  • 37
4

I came this thread looking for a d3 mousemove event for angular unit testing.

@natevw answer

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

helped a lot on mouseover event. But, applying that to mousemove was giving an e.source null error.

The work around was to set the d3 event programmatically.

d3.event = document.createEvent('MouseEvent');
d3.event.initMouseEvent("mousemove");
d3.select(elm[0]).select("rect").on("mousemove")();

Hope this helps.

massanishi
  • 2,044
  • 1
  • 15
  • 9
1

You can go super manual by getting the mouse event and passing it the arguments that d3 would otherwise provide for you. This gives you a fairly clean way to do it while still using d3 constructs. For a single element use the following:

var path = g.select('path');
path.on('click').call(path.node(), path.datum());

For multiple elements, you can trigger each one in turn:

g.selectAll('path').each(function(d, i) {
  d3.select(this).on('click').apply(this, arguments);
});

The latter can also be used for a single element if your selector is specific enough, or if you use .select() instead of .selectAll() to only return the first element.

Yony
  • 1,264
  • 1
  • 10
  • 19
0

@handler answer did not work for me entirely. It would click the svg element but additional simulated events would not register. This is what worked for me:

function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

Usage:

eventFire(document.getElementById(element_id), 'click');
Cybernetic
  • 12,628
  • 16
  • 93
  • 132
-1

This is how I do it.

g.selectAll("path").on("click", function(d, i){
                                    my_function(d, i);
                                });

I've found the the callbacks work with anonymous functions. So for the code above, any path that is clicked will call my_function and pass in the current datum d and index i of the path that was clicked.

-2

I find next workaround:

d3.selectAll("path").each(function(d, i) {
                    onClickFunc.apply(this, [d, i]);
                });

Where d is data and i is index this data

mad
  • 902
  • 1
  • 7
  • 10
  • 1
    this doesn't answer your question really, it just does `d3.selectAll("path").each( onClickFunc )` with more typing. What's onClickFunc? – artm Nov 13 '12 at 07:29
  • This does nothing. Should accept natevw or handler 's answer. – sudipto Jun 05 '14 at 07:07
  • 1
    Missing a vital line of code as the first line of the callback: var onClickFunc = d3.select(this).on("click"); – Andrew Plank Jun 17 '14 at 08:35
-5

Try g.select("path").trigger("click")

Nabor
  • 1,661
  • 3
  • 20
  • 45
  • doesn't help, d3 not contain `trigger` prop – mad Jan 30 '12 at 12:35
  • sorry, thought it was jQuery, it looks like... But then I suggest you take this code. It works without any framework, but I only use it under Firefox... 'var section = document.getElementById("section"); if (section) { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); section.dispatchEvent(evt); }' – Nabor Jan 30 '12 at 12:38