Book Image

Data Visualization with D3 and AngularJS

By : Erik Hanchett, Christoph Körner
Book Image

Data Visualization with D3 and AngularJS

By: Erik Hanchett, Christoph Körner

Overview of this book

Table of Contents (16 chapters)
Data Visualization with D3 and AngularJS
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Listen for events


Interactions in JavaScript are based on the concept of events and event listeners. This concept works like this: first, one defines an event listener on an element. Then, it waits for a specific event of the element to occur, for example, this could be a click event. Every time the event occurs (the element is clicked on), a callback function is executed. Having said that, we can attach listeners to any element of the DOM and trigger functions as soon as the event occurs.

In D3.js, we can attach listeners directly to Selections via the .on(event, callback) method. Whenever D3.js handles an event, the d3.event variable stores all the information of the currently triggered event. Let's look at a simple example:

svg.on('click', function(){

  var e = d3.event;

  // Get relative cursor position
  var xpos = (e.offsetX==undefined) ? e.layerX : e.offsetX;
  var ypos = (e.offsetY==undefined) ? e.layerY : e.offsetY;

  svg.append("circle")
    .attr("cx", xpos)
    .attr("cy", ypos...