CanvasXpress Methods & Events

A guide to programmatic control and custom interactions in CanvasXpress.

Introduction to the CanvasXpress API

The power of CanvasXpress goes beyond its configuration object. Its extensive JavaScript API provides full programmatic control over every aspect of your visualizations. This section introduces the core concepts of methods and events, which allow you to dynamically control and respond to your charts within a web application.

This document provides a developer-focused, in-depth guide to the event system in CanvasXpress. Events are a powerful mechanism that allows you to transform a static chart into a fully interactive and dynamic data visualization experience. By hooking into the chart's lifecycle and user interactions, you can create custom behaviors, integrate with other UI components, and build a responsive application around your data.

How to Customize Events

The primary mechanism for customizing chart behavior is the events object, which you include in your main CanvasXpress configuration. This object acts as a map, where each key is the name of a specific event (e.g., click, mouseover), and its value is a JavaScript function—your "event handler"—that will be executed when that event occurs. You can also add them dynamically at runtime using the addEventListener method and remove them with removeEventListener (See the playground section below).

The Event Handler Function Signature

Every event handler you write will be called by CanvasXpress with three specific and very useful arguments. Understanding these is key to unlocking the full potential of the event system.

function(dataObject, event, canvasXpressInstance) { ... }

dataObject (object | null)

This is arguably the most important parameter for creating context-aware interactions. It's a dynamically generated object that contains detailed information about the specific chart element that was interacted with.

What it contains: The contents of dataObject vary depending on the graph type and what you interacted with. For example, if you click on a bar in a bar graph, it will contain the value of that bar, its corresponding sample and variable names, and its index. If you click on a node in a network graph, it will contain the node's ID and any associated metadata.

How to explore it: The best way to understand what dataObject provides for a specific event is to inspect it directly. A simple console.log(dataObject) inside your handler will reveal its structure and contents for any given interaction.

When it's null: If an event occurs on a part of the chart that isn't associated with a specific data point (like clicking the background), dataObject will often be null. Your code should always check if dataObject exists before trying to access its properties.

event (Event)

This is the raw, native DOM Event object that the browser generated. This is useful for advanced scenarios where you need low-level information like mouse coordinates or modifier keys.

Examples: You can get the precise X/Y coordinates of the mouse pointer (event.clientX, event.clientY), or check if a modifier key like Ctrl, Shift, or Alt was held down during the event (event.ctrlKey, event.shiftKey). You can also call methods like event.preventDefault() to stop the browser's default behavior (e.g., to prevent the context menu from appearing on a right-click).

canvasXpressInstance (object)

This is a direct reference to the chart instance itself. It's your gateway to the entire public API of CanvasXpress.

What it's for: From within an event handler, you can call any other CanvasXpress method. For example, after a user clicks a data point, you could programmatically trigger a zoom (canvasXpressInstance.zoom()), apply a filter (canvasXpressInstance.filterSamples()), or even destroy the chart (canvasXpressInstance.destroy()).

Live Example

Interact with the chart below. The code demonstrates how to use the click and mouseover events to display information. The full code is shown underneath the chart.

  var data = {
      "y": {
        "vars": ["Gene1"],
        "smps": ["Smp1", "Smp2", "Smp3"],
        "data": [[10, 35, 88]]
      }
  };

  var conf = {
    "graphType": "Bar"
  };

  var evts = {
    "mousemove": function(o, e, t) {
      t.showInfoSpan(e, "<pre>" + t.prettyJSON(o) + "</pre>");
    },
    "click": function(o, e, t) {
      var s = "click on var " + o.y.vars[0] + " and smp " + o.y.smps[0];
      t.showInfoSpan(e, s);
    },
    "dblclick": function(o, e, t) {
      var s = "dblclick on var " + o.y.vars[0] + " and smp " + o.y.smps[0];
      t.showInfoSpan(e, s);
    }
  };

  var cX = new CanvasXpress("canvasId", data, conf, evts);

Best Practices for Event Handling

Keep Handlers in Your Application Code

Your event handler functions are part of your application's logic. They should never be added directly into the CanvasXpress library files to avoid issues with upgrades and to maintain a clean separation of concerns.

Organizing Your Handler Functions

For complex applications, it's a great practice to group your handlers into a dedicated object. This acts as a "namespace" for your event logic.

var eventHandlers = {
  "mousemove": function(dataObject, event, canvasXpressInstance) {
    // Do something on mouse move...
  },
  "mouseout": function(dataObject, event, canvasXpressInstance) {
    // Do something on mouse out...
  },
  "click": function(dataObject, event, canvasXpressInstance) {
    // Do something on click...
  },
  "dblclick": function(dataObject, event, canvasXpressInstance) {
    // Do something on double-click...
  }
};

var cx = new CanvasXpress("DOMId", data, conf, eventHandlers);

Using the canvasXpressInstance Parameter

You should always use the canvasXpressInstance object passed as the third parameter to interact with the chart, and avoid relying on the this keyword. The canvasXpressInstance parameter is a guaranteed, stable reference to the chart object.

Example Event Handler Collection (ES5)

This section provides a complete collection of "boilerplate" or "scaffolding" functions for all of CanvasXpress's custom events. Use this as a starting point for your own application.

/**
 * A collection of placeholder event handler functions for CanvasXpress (ES5 compatible).
 * Each function demonstrates the standard signature and includes a console log to confirm it's firing.
 *
 * @param {object | null} dataObject - An object with details about the event target, or null.
 * @param {Event} event - The native DOM event object.
 * @param {object} canvasXpressInstance - The instance of the CanvasXpress chart.
 */

// Fired when a data element is clicked.
var handleClick = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: click', { dataObject: dataObject });
  if (dataObject && dataObject.y) {
    var varName = dataObject.y.vars[0];
    var smpName = dataObject.y.smps[0];
    console.log('Clicked on sample '' + smpName + '' of variable '' + varName + ''');
  }
};

// Fired when a legend item is clicked.
var handleClickLegend = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: clicklegend', { dataObject: dataObject });
  if (dataObject) {
    console.log('Clicked on legend item:', dataObject.legend);
  }
};

// Fired on a right-click. Useful for a custom context menu.
var handleContextMenu = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: contextmenu', { dataObject: dataObject });
  // To show your own menu instead of the browser's, you must prevent the default behavior.
  // event.preventDefault();
};

// Fired on a double-click.
var handleDoubleClick = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: dblclick', { dataObject: dataObject });
};

// Fired continuously during a drag operation.
var handleDrag = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: drag', { dataObject: dataObject });
};

// Fired in Network graphs after a node drag operation is finished.
var handleEndDragNode = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: enddragnode', { dataObject: dataObject });
  if (dataObject && dataObject.nodes) {
    console.log('Finished dragging node:', dataObject.nodes[0].id);
  }
};

// Fired once after all rendering is complete.
var handleEndDraw = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: enddraw - Chart rendering is complete.');
};

// Fired once after motion is complete.
var handleMotion = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: motion - Chart is in motion.');
};

// Fired when the mouse moves over the elements in the chart.
var handleMouseMove = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: mousemove', { dataObject: dataObject });
};

// Fired when the mouse moves out of the elements in the chart.
var handleMouseOut = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: mouseout', { dataObject: dataObject });
};

// Fired when the mouse enters a data element.
var handleMouseOver = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: mouseover', { dataObject: dataObject });
};

// Fired when a mouse button is released.
var handleMouseUp = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: mouseup', { dataObject: dataObject });
};

// Fired when the chart is updated by a remote source.
var handleRemote = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: remote', { dataObject: dataObject });
};

// Fired after a selection of data points has been made.
var handleSelect = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: select', { dataObject: dataObject });
};

// Fired when the mouse wheel is used over the chart.
var handleWheel = function(dataObject, event, canvasXpressInstance) {
  console.log('Event: wheel', { dataObject: dataObject });
};

Playground

Explore CanvasXpress events in the interactive playground below. Click an event name to dynamically add or remove its handler from the chart. For a deeper look, open your browser's developer console to view the event logs and inspect the returned data object. For convenience, the returned data is also displayed in the container next to the chart.

 // Get the CanvasXpress instance
  var canvasXpressInstance = ...;

  // Add a click event listener
  canvasXpressInstance.addEventListener('click', function(dataObject, event, canvasXpressInstance) {
    console.log('Custom click event triggered', { dataObject: dataObject });
  });
  // Remove the click event listener
  canvasXpressInstance.removeEventListener('click', function(dataObject, event, canvasXpressInstance) {
    console.log('Custom click event triggered', { dataObject: dataObject });
  });

click

 

clicklegend

 

contextmenu

 

dblclick

 

drag

 

enddragnode

Network Graphs Only

enddraw

 

motion

Motion Charts Only

mousemove

 

mouseout

 

mouseover

 

mouseup

 

remote

Remote Charts Only

select

 

wheel

 

Accessing CanvasXpress Instances in the DOM

CanvasXpress instances on the web page can be retrieved and accessed at any time using their `targetId`.


      var cX = CanvasXpress.$("canvasId");
        

Similarly, any CanvasXpress instance on the web page can be destroyed programmatically. This is essential for cleanly removing an instance and all its associated events.


        CanvasXpress.destroy("canvasId");