The d3.selection.on() function in D3.js is used to add a particular event listener to an element. An event may be a string of event type click, mouseover, etc.
Syntax:
selection.on(typenames[, listener[, options]])
Parameters: This function accepts two parameters as mentioned above and described below:
- Typename Listener: It is a string event type such as click, submits, etc.
- Options: This is an optional object that may tell about the special characteristics of the listener.
Note: If a listener is not specified then it returns the currently assigned event for the particular element.
Return Values: This function returns the object.
Below examples illustrate the D3.js selection.on() function in JavaScript:
Example1:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < meta name = "viewport" path1tent=" width = device -width, initial-scale = 1 .0"/> < title >D3.js selection.on() Function</ title > </ head > < style > li { background-color: green; color: #ffffff; width: 50px; margin-bottom: 5px; padding: 20px; height: 40px; } li:hover { cursor: pointer; opacity: 0.8; } </ style > < body > < ul > < li >Geeks for neveropen</ li > < li >GEEKS FOR GEEKS</ li > </ ul > < script src = </ script > < script src = </ script > < script > let li = d3.select("li"); let x = li.on("click", () => { console.log("Clicked"); }); </ script > </ body > </ html > |
Output:
Before clicking on the box:
After clicking on the box:
Example 2:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < meta name = "viewport" path1tent=" width = device -width, initial-scale = 1 .0"/> < title >D3.js selection.on() Function</ title > </ head > < style > li { background-color: green; color: #ffffff; width: 100px; margin-bottom: 5px; padding: 20px; height: 50px; } li:hover { cursor: pointer; opacity: 0.8; } </ style > < body > < ul > < li >Geeks for neveropen</ li > </ ul > < script src = </ script > < script src = </ script > < script > let li = d3.select("li"); let x = li.on("mouseover", () => { let li = document.querySelector("li"); li.innerHTML = "mouseOver event"; }); // When cursor moves out of the li tag x = li.on("mouseout", () => { let li = document.querySelector("li"); li.innerHTML = "Geeks for neveropen"; }); </ script > </ body > </ html > |
Output:
On mouseover:
On mouseout: