I have several "event" classes covering some of my svg elements. I'm assigning each class an event handler for mouseover
and mouseout
, and if an element has more than one class, I want both handlers to fire. How do I do this? It seems that when I do
d3.selectAll(".a-class")
.on("mouseover", function() {
// do A
})
.etc();
d3.selectAll(".another-class")
.on("mouseover", function() {
// do B
})
.etc();
then when I hover over an element that has both classes, only B
(the second handler) fires, apparently because it overrides the first one. Is there a method to "append" an event handler, rather than redefine it?
As per the documentation...
If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added. To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar".
Therefore you can achieve what you want by appending an arbitrary namespace to each of your handlers.
d3.selectAll(".a-class")
.on("mouseover.a", function() {
// do A
})
.etc();
d3.selectAll(".another-class")
.on("mouseover.b", function() {
// do B
})
.etc();
This has the added advantage that you can then refer explicitly to the added event handlers later (either individually or for an entire namespace) to replace or remove them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With