Accepted answer

This sounds pretty much like a similar problem I had to fight my way through a couple of weeks ago. Your approach was the first which occured to me at that time. After doing some research I concluded it is not going to work for the following reasons:

The jQuery spec tells us about the jQuery.trigger() method:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

There are two drawbacks resulting from this behaviour:

  1. The d3.event will not get populated with the triggered event leaving it null as you have already mentioned.

  2. Even if you tried to set the d3.event programmatically to the synthesized event jQuery created you would just stumble into the next problem noticing that it is pretty much blank. Since the event did not result from a real mouse click there won't be any coordinates (like .clientX, .clientY) in it. Your code would therefore break on this shortcomming.

Eventually, I ended up creating my own MouseEvent:

// Initialize the event as needed.
var mouseEventInit = {
    "button": 0,
    "clientX": 0,  // maybe something like circle.getBoundingClientRect().left + 1
    "clientY": 0   // maybe something like circle.getBoundingClientRect().top + 1
    // ... fill any properties you need.

// create new event and...
var event = new MouseEvent("click", mouseEventInit);

If you need to support Internet Explorer you have to use the deprecated method MouseEvent.initMouseEvent() since the use of a new event object which was created via the constructor is not yet supported by IE:

var event = document.createEvent("MouseEvents");
event.initMouseEvent( /* params */ );

I used browser detection and switched to the correct way of setting up the event object.

Having created the new event object you are ready to dispatch it to the desired target by using method dispatchEvent() of interface EventTarget which is implemented by DOM's Element:

// dispatch it to the target

This way you end up with a fully fledged event which will also be recognized by d3 putting it to d3.event accordingly.


This might be a scoping issue. Try calling the d3.event within the mousedown handler and see if the value is still null. If so, simply move the getWindowPosition function declaration to within the mousedown handler scope.

Related Query