Event Handling in D3.js
d3.selection.on(type[, listener[, capture]]);
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.
Let’s discuss each method in detail.
This method can be applied to add or remove the event listener for depicting the event types such as mouseout, mouseover, and click.
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.
It can be applied to obtain both (x and y) coordinates of the existing mouse position within the stated DOM’s element.
This will help you to access the standard fields of events like timestamp. It also helps you to access the function, such as preventDefault.
This method can be applied to access the essential coordinates over to the container.
Here, we have an example to demonstrate the mouseout and mouseover event handling:
console.log(d3.event); // Get current event info
console.log(d3.mouse(this)); // Get x & y co-ordinates
After the execution of the above example code, you got the following result.
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: