JavaScript:D3 .on()

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.

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn how to create bar charts with D3, the popular interactive data visualization library.
    • With Certificate
    • Intermediate.
      1 hour

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

Contribute to Docs

Learn JavaScript:D3 on Codecademy

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn how to create bar charts with D3, the popular interactive data visualization library.
    • With Certificate
    • Intermediate.
      1 hour