Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass arguments to a d3 on "click" event callback

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

like image 448
rowyourboat Avatar asked Aug 01 '14 21:08

rowyourboat


People also ask

What is D3 js explain select () selectAll () and data () in brief?

D3 allows you to select DOM elements and manipulate them using functions provided by the library. Elements are selected with select() and selectAll() methods, which return selections. Selections have operators that allow you to modify, add, or remove elements.

What does selectAll do in D3?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.

What is D3 dispatch?

Dispatching is a convenient mechanism for separating concerns with loosely-coupled code: register named callbacks and then call them with arbitrary arguments. A variety of D3 components, such as d3-drag, use this mechanism to emit events to listeners.

How does D3 select work?

select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.


2 Answers

This 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.net/g45Ju/

thanks to jshanley

like image 96
rowyourboat Avatar answered Nov 15 '22 10:11

rowyourboat


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}
  });
like image 29
Rohit Rane Avatar answered Nov 15 '22 09:11

Rohit Rane