Here is my code:
function toggleClass(element, className){
d3.select(element).classed(className, !d3.select(element).classed(className));
}
d3.selectAll("rect").on("click", toggleClass(this, "clicked");
I cannot get it to work, it appears that passing arguments to a DOM event is bad news bears. Does anyone know a work-around for this?
Thank you
Here is my code:
function toggleClass(element, className){
d3.select(element).classed(className, !d3.select(element).classed(className));
}
d3.selectAll("rect").on("click", toggleClass(this, "clicked");
I cannot get it to work, it appears that passing arguments to a DOM event is bad news bears. Does anyone know a work-around for this?
Thank you
Share Improve this question asked Aug 1, 2014 at 21:57 rowyourboatrowyourboat 3411 gold badge4 silver badges14 bronze badges 2-
1
You can use an anonymous function to do this:
.on('click', function() { toggleClass(this, "clicked"); })
– jshanley Commented Aug 1, 2014 at 22:00 -
2
Arguments are always evaluated before they are passed to a function. So if you have
foo(bar())
, thenbar
is executed first and its return value is passed tofoo
. If you want to pass a callback, you have to pass a function, not call a function. – Felix Kling Commented Aug 1, 2014 at 22:04
2 Answers
Reset to default 11This works:
function toggleClass(element, className){
d3.select(element).classed(className, !d3.select(element).classed(className));
}
d3.selectAll("rect").on("click", function () {
toggleClass(this, "clicked");
});
here is the working fiddle: http://jsfiddle/g45Ju/
thanks to jshanley
Have you tried selection.datum()
function? This snippet might give you an idea :
d3
.select('svg')
.append('circle')
.datum({
'x':10,
'y':100,
'z':100
})
.on('click'),function(d){
//Here d = {'x':10,'y':100,'z':1000}
});