Event Handling in D3.js

D3 depicts an event when it occurs and stores it in the d3.event variable. This is a state variable and can be used in the callback function of the listener authorized with the operator’s d3 selection stage. The latest d3 running just after the JavaScript callback function has been completed. Similar to other libraries, D3.js facilitates with built-in and custom variable. You can easily wrap an event listener over to a DOM (Document Object Model) with the help of d3.selection.on() method.

Syntax

The above syntax helps you to add the event listener to the selected elements of DOM. In the above syntax, it contains the following parameters:

Event Type: It can be a string like “mouseover” and “click.”

Callback Function: This function executes during the occurring of the event

Capture: It an optional parameter. It is similar to the W3C capture flag.

Methods of Event Handling

Here, some essential methods of event handling and event handling objects are listed below.

  • selection.on()  
  • selection.dispatch()
  • d3.mouse(container)
  • d3.event
  • d3.touch

Let’s discuss each method in detail.

selection.on() 

This method can be applied to add or remove the event listener for depicting the event types such as mouseout, mouseover, and click.

selection.dispatch()

This method helps you to describe the event types such as mouseout, mouseover, click. It also use typename as an eventname, and the listener is an event listener.

d3.mouse(container)

It can be applied to obtain both (x and y) coordinates of the existing mouse position within the stated DOM’s element.

d3.event

This will help you to access the standard fields of events like timestamp. It also helps you to access the function, such as preventDefault.

d3.touch

This method can be applied to access the essential coordinates over to the container.

Example                                                                                                                

Here, we have an example to demonstrate the mouseout and mouseover event handling:

Output

After the execution of the above example code, you got the following result.

Event Handling in D3.js

In the above-given output, we have two div elements and covering the CSS portion for each with the black color. With the help of selection.on(event), we have depicted the mouseout and mouseover events and also added the listener’s function over to the described event.

Now, if you perform the mouseover event, then you will get the following output:

Event Handling in D3.js