Events in D3

As in all other libraries, D3 also supports built-in events and custom events. We can bind an event listener to any DOM element using d3.selection.on() method.

d3.selection.on(type[, listener[, capture]]);

The on() method adds an event listener to all selected DOM elements. The first parameter is an event type as string such as "click", "mouseover" etc. The second parameter is a callback function which will be executed when an event occurs and the third optional parameter capture flag may be specified, which corresponds to the W3C useCapture flag.

The following table lists important event handling method and objects.

Event Methods Description
selection.on() Add or remove event listeners to capture event types like click, mouseover, mouseout etc.
selection.dispatch() Captures event types like click, mouseover, mouseout. Typenames is the eventname, listener is the event listener
d3.event Event object to access standard event fields such as timestamp or methods like preventDefault
d3.mouse(container) Gets the x and y coordinates of the current mouse position in the specified DOM element.
d3.touch() Gets the touch coordinates to a container

The following example demonstrates handling of mouseover and mouseout events.

Example: Event Handling
<!doctype html>
        div {
            height: 100px;
            width: 100px;
            background-color: steelblue;
    <script src=""></script>
<div> </div>
      .on("mouseover", function(){

            .style("background-color", "orange");

          // Get current event info
          // Get x & y co-ordinates
      .on("mouseout", function(){

            .style("background-color", "steelblue")

In the above example, we have two div elements and applied a css to each with a steelblue color. We have captured the mouseover and mouseout events of all div elements using selection.on(event) and added event listener functions to each captured event. Then we went on to apply the styles to each of these event, viz. orange on mouseover and steelblue on mouseout.

Notice that we display current event object (d3.event) and x & y co-ordinates of the mouse using d3.mouse() method to the developer console of the browser.

Visit D3 documentation to know more about Event Handling.