Skip to content

Instantly share code, notes, and snippets.

@shawnbot
Created November 29, 2012 02:00
Show Gist options
  • Save shawnbot/4166283 to your computer and use it in GitHub Desktop.
Save shawnbot/4166283 to your computer and use it in GitHub Desktop.
d3 "mouseenter" and "mouseleave" event support
(function() {
// get a reference to the d3.selection prototype,
// and keep a reference to the old d3.selection.on
var d3_selectionPrototype = d3.selection.prototype,
d3_on = d3_selectionPrototype.on;
// our shims are organized by event:
// "desired-event": ["shimmed-event", wrapperFunction]
var shims = {
"mouseenter": ["mouseover", relatedTarget],
"mouseleave": ["mouseout", relatedTarget]
};
// rewrite the d3.selection.on function to shim the events with wrapped
// callbacks
d3_selectionPrototype.on = function(evt, callback, useCapture) {
var bits = evt.split("."),
type = bits.shift(),
shim = shims[type];
if (shim) {
evt = [shim[0], bits].join(".");
callback = shim[1].call(null, callback);
return d3_on.call(this, evt, callback, useCapture);
} else {
return d3_on.apply(this, arguments);
}
};
function relatedTarget(callback) {
return function() {
var related = d3.event.relatedTarget;
if (this === related || childOf(this, related)) {
return undefined;
}
return callback.apply(this, arguments);
};
}
function childOf(p, c) {
if (p === c) return false;
while (c && c !== p) c = c.parentNode;
return c === p;
}
})();
@aolieman
Copy link

Thanks Shawn, this works beautifully!

@cjrd
Copy link

cjrd commented May 31, 2013

Excellent general purpose d3 callback shim: thanks!

@Miyayx
Copy link

Miyayx commented Jul 14, 2013

It really helped a lot. Thank you!

@bengolder
Copy link

This has been really useful, thank you! I forked and edited it to allow for callback removal with .on(eventType, null)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment