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
Yes, you don't need d3 to trigger the event, vanilla javascript is enough for that. You simply need to use the
dispatchEvent
function.Here is an example of how you would do it (from a button for example).
I added both the d3.select way and the plain JS way, both should work fine.
The following will trigger the
mouseleave
event on the elements viadispatchEvent()
.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)
You can make one constant function for mouseleave and call it on mouse leave or externally as well like this :
If you are already on D3 v4, you can use
selection.dispatch()
which was specifically designed to do exactly what you are looking for:This was included in v4 as a result of the issue "Ability to trigger event handlers manually. #100".
Furthermore, the method will enable you to dispatch events of the same type to all elements contained in the selection. The implementation of that method looks similar to the approach the other answerers took by putting
event.dispatch()
to use, but will make your life somewhat easier. The following snippet has a listener for each individual circle, which may all be triggered by the button at once.