Created
November 29, 2012 02:00
-
-
Save shawnbot/4166283 to your computer and use it in GitHub Desktop.
d3 "mouseenter" and "mouseleave" event support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
} | |
})(); |
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
It really helped a lot. Thank you!