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.

Syntax:
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>
<html>
<head>
    <style>
        div {
            height: 100px;
            width: 100px;
            background-color: steelblue;
            margin:5px;
        }
    </style>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div> </div>
<script>
    d3.selectAll("div")
      .on("mouseover", function(){
          d3.select(this)
            .style("background-color", "orange");

          // Get current event info
          console.log(d3.event);
          
          // Get x & y co-ordinates
          console.log(d3.mouse(this));
      })
      .on("mouseout", function(){
          d3.select(this)
            .style("background-color", "steelblue")
      });
</script>
</body>
</html>

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.