Introduction to Interactivity

Get introduced to the basics of interaction in D3.js.

Let’s dive into interaction in D3.js by introducing the important concept of event listening.

Event listening

Event listening is an important technique to make data visualization interactive. The event listener will listen to the user. Every time the user interacts with the visualization, we will call some function and make changes to visualization based on interaction.

The user can interact through a mouse or keyboard with the visualization. Some of the common event listeners are:

  • mouseover: Cursor is moved onto the element that has the listener attached.
  • mouseout: Cursor is moved off the element that has the listener attached.
  • wheel: Wheel button of a mouse is rotated in any direction.
  • keydown: Any key is pressed

Example

Let’s demonstrate the event listener by an example where we will make an interactive bar chart. The event listener will listen to the event mouseover and every time we hover over the rectangles of the bar chart it will change its color.

Event listening

Explanation

As shown in the above code:

  • We have drawn the same bar chart as we did in the bar chart lesson.
  • Line 44-49: We have the defined two events mouseover and mouseout using the on function. We change the color of the rectangle to #FF96C5, where this refers to the object that has invoked the event listener every time we move our mouse over the rectangle. It changes back to #00A5E3 when the mouse cursor leaves the rectangle.

Zoom

Let’s explore another important concept of interactivity zoom. D3.js provides a d3.zoom() API which supports the zoom functionality. Let’s take the example of a simple circle where we would apply the zoom functionality.

Zoom code

Press and hold the circle with your cursor, and then scroll up or down with your mouse/touchpad to zoom in and out. The circle can also be dragged around the screen

Explanation

As shown in the above code:

  • Line 16-20: We have drawn the same circle as we did in the circle lesson.
  • Line 10-13: We have created an event listener, zoom, using the d3.zoom() API, so every time we zoom in or zoom out, it will call the function that will change the size of the circle using the transform function. This API allows you to drag the element as well.