SachiDangalla SachiDangalla - 1 month ago 11
Javascript Question

How to externally trigger d3 events

I have a d3 selection upon which I have defined event callbacks.

var obj = d3.select("#kk").on("mouseleave",function(){
console.log("mouse leave");
});


How can I trigger the event externally? Is there something like:

obj.mouseleave(); // actuall mouse leave function calling


If there is, and if I select the object without referring to
obj
, will the trigger still work?

As in:

var newObje=d3.select("#kk");
newObje.mouseleave(); //will this trigger the previously defined instructions

Answer

The following will trigger the mouseleave event on the elements via dispatchEvent().

  var event = document.createEvent('Event');
  event.initEvent('mouseleave', true, true);

  d3.selectAll("circle").node().dispatchEvent(event);

Example: http://codepen.io/anon/pen/eBYvVN (I've added a button at the bottom to trigger it. The mouseleave event is attached to the circles)