passing value to a function on a mouseover event

2,822 views
Skip to first unread message

Jeff Pflueger

unread,
Aug 31, 2011, 1:11:18 PM8/31/11
to d3...@googlegroups.com
Hi,
I'd like to pass a value to the textmouseover function when some text is moused over. But when I put parenthesis behind a call to the function (either empty or with a value), the function is executed once whether or not there is a mouseover event - and then the function does not execute when there is a mouseover.

Any ideas on this?
Thanks for any help.

This produces the message "3 We are here" without a mouseover happening:

vis.append('svg:text')
    .attr('x', 100)
    .attr('y', 100 )
    .attr('dy', '.71em')
    .attr('text-anchor', 'middle')
    .attr('class', 'labels')
    .text('Here is some text to mouseover')
    .on('mouseover', textmouseover(3) );

function textmouseover(value) {
    console.log(value + ' We are here');
}

And this produces the message "We are here" only on mouseover (parenthesis removed):

vis.append('svg:text')
    .attr('x', 100)
    .attr('y', 100 )
    .attr('dy', '.71em')
    .attr('text-anchor', 'middle')
    .attr('class', 'labels')
    .text('Here is some text to mouseover')
    .on('mouseover', textmouseover );

function textmouseover() {
    console.log('We are here');
}


Mike Bostock

unread,
Aug 31, 2011, 1:20:41 PM8/31/11
to d3...@googlegroups.com
Correct; if you say textmouseover(3), you're calling the function
textmouseover, passing in the value 3. Then, the return value of this
function is passed to .on("mouseover"); since the return value is
undefined, the behavior of your code is to remove the mouseover
listener, if any.

There are a few ways that you could fix this. One useful technique is
closures. In this case, you create a new listener that is bound to the
value 3:

function textmouseover(value) {
return function() {
console.log(value + " We are here.");
};
}

A more idiomatic way of doing this with D3 is to use data binding.
Like most other functions in D3, your event listener is called with
two arguments: the current data (d) and index (i). The `this` context
of the callback function is the associated DOM element. For example:

vis.append("svg:text")
.data([3])
.on("mouseover", textmouseover);

function textmouseover(d) {
console.log(d + " We are here.");
}

More details:

https://github.com/mbostock/d3/wiki/Selections#wiki-on

Mike

Chris Viau

unread,
Sep 4, 2011, 7:04:43 PM9/4/11
to d3...@googlegroups.com
Or, I suppose, another way of doing exactly the same thing as Mike's first solution:

  .on('mouseover', function(){return textmouseover(3)});

Erick Katzenstein

unread,
Mar 4, 2014, 5:46:50 PM3/4/14
to d3...@googlegroups.com
Perfect! Thanks Chris.
Reply all
Reply to author
Forward
0 new messages