.on()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Dec 19, 2023
Contribute to Docs

In D3.js, the d3.selection.on() function is used to add a specific event handler to an element. An event can be any Document Object Model (DOM) event type such as click, zoom, mouseenter, mouseleave, mouseover, mouseout, and mousemove.

Syntax

selection.on(event type, callback function)
  • event type: The event type is a string that specifies the DOM event type used.
  • callback function: The callback function is the function that is called when the event is triggered.

Example

In the following code snippet, hovering over a square makes it turn yellow:

d3.selectAll('square').on('mouseover', function () {
d3.select(this).style('fill', 'yellow');
});

Output: Code output

All contributors

Looking to contribute?

Learn JavaScript:D3 on Codecademy