ChartDirector 6.0 (Ruby Edition)

Javascript Clickable Charts




This example demonstrates using ChartDirector image maps to invoke client side Javascript functions.

In this example, a clickable area chart will be produced. Apart from responding to mouse clicks, detail information about the data points will be displayed in a dynamic HTML block when the mouse pointer moves over the chart. This is accomplished using "onmouseover" and "onmouseout" event handlers with client side Javascript.

The code for this example is listed below.

[Ruby On Rails Version - Controller] app/controllers/jsclick_controller.rb
require("chartdirector")

class JsclickController < ApplicationController
    include ChartDirector::InteractiveChartSupport

    def index()
        @ctrl_file = File.expand_path(__FILE__)

        #
        # For demo purpose, we use hard coded data. In real life, the following data could come from
        # a database.
        #
        revenue = [4500, 5600, 6300, 8000, 12000, 14000, 16000, 20000, 24000, 28000]
        grossMargin = [62, 65, 63, 60, 55, 56, 57, 53, 52, 50]
        backLog = [563, 683, 788, 941, 1334, 1522, 1644, 1905, 2222, 2544]
        labels = ["1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005"]

        # Create a XYChart object of size 600 x 360 pixels
        c = ChartDirector::XYChart.new(600, 360)

        # Add a title to the chart using 18pt Times Bold Italic font
        c.addTitle("Annual Revenue for Star Tech", "timesbi.ttf", 18)

        # Set the plotarea at (60, 40) and of size 480 x 280 pixels. Use a vertical gradient color
        # from light green (eeffee) to dark green (008800) as background. Set border and grid lines
        # to white (ffffff).
        c.setPlotArea(60, 40, 480, 280, c.linearGradientColor(60, 40, 60, 280, 0xeeffee, 0x008800),
            -1, 0xffffff, 0xffffff)

        # Add a multi-color bar chart layer using the revenue data.
        layer = c.addBarLayer3(revenue)

        # Set cylinder bar shape
        layer.setBarShape(ChartDirector::CircleShape)

        # Add extra field to the bars. These fields are used for showing additional information.
        layer.addExtraField2(grossMargin)
        layer.addExtraField2(backLog)

        # Set the labels on the x axis.
        c.xAxis().setLabels(labels)

        # In this example, we show the same scale using both axes
        c.syncYAxis()

        # Set the axis line to transparent
        c.xAxis().setColors(ChartDirector::Transparent)
        c.yAxis().setColors(ChartDirector::Transparent)
        c.yAxis2().setColors(ChartDirector::Transparent)

        # Set the axis label to using 8pt Arial Bold as font
        c.yAxis().setLabelStyle("arialbd.ttf", 8)
        c.yAxis2().setLabelStyle("arialbd.ttf", 8)
        c.xAxis().setLabelStyle("arialbd.ttf", 8)

        # Add title to the y axes
        c.yAxis().setTitle("USD (millions)", "arialbd.ttf", 10)
        c.yAxis2().setTitle("USD (millions)", "arialbd.ttf", 10)

        # Create the image and save it in a temporary location
        session["chart1"] = c.makeChart2(ChartDirector::PNG)

        # Client side Javascript to show detail information "onmouseover"
        showText = "onmouseover='showInfo(\"{xLabel}\", {value}, {field0}, {field1});' "

        # Client side Javascript to hide detail information "onmouseout"
        hideText = "onmouseout='showInfo(null);' "

        # "title" attribute to show tool tip
        toolTip = "title='{xLabel}: US$ {value|0}M'"

        # Create an image map for the chart
        @imageMap = c.getHTMLImageMap(url_for(:controller => "xystub"), "", sprintf("%s%s%s",
            showText, hideText, toolTip))
    end

end

[Ruby On Rails Version - View] app/views/jsclick/index.html.erb
<html>
<body style="margin:5px 0px 0px 5px">
<script type="text/javascript">
//
//Client side script function to show and hide detail information.
//
function showInfo(year, revenue, grossMargin, backLog) {
    var obj;
    if (document.getElementById)
        //IE 5.x or NS 6.x or above
        obj = document.getElementById('detailInfo');
    else
        //IE 4.x
        obj = document.all['detailInfo'];

    if (!year)
    {
        obj.style.visibility = "hidden";
        return;
    }

    var content = "<table border='1' cellpadding='3' style='font-size:10pt; " +
       "font-family:verdana; background-color:#CCCCFF' width='480'>";
    content += "<tr><td><b>Year</b></td><td width='300'>" + year + "</td></tr>";
    content += "<tr><td><b>Revenue</b></td><td>US$ " + revenue + "M</td></tr>";
    content += "<tr><td><b>Gross Margin</b></td><td>" + grossMargin + "%</td></tr>";
    content += "<tr><td><b>Back Log</b></td><td>US$ " + backLog + "M</td></tr>";
    content += "</table>";

    obj.innerHTML = content;
    obj.style.visibility = "visible";
}
</script>
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Javascript Clickable Chart
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20">
    <%= link_to "Source Code Listing",
        :controller => "cddemo", :action => "viewsource",
        :ctrl_file => @ctrl_file, :view_file => File.expand_path(__FILE__) %>
</div>
<img src="<%= url_for(:action => 'get_session_data', :id => 'chart1',
    :nocache => rand) %>" border="0" usemap="#map1">
<map name="map1">
<%= raw(@imageMap) %>
</map>
<div id="detailInfo" style="margin-left:60px"></div>
</body>
</html>

In the above code, the chart is created and saved in a session variable. An <IMG> tag is used in the view to retrieve the chart with the "get_session_data" action. The "get_session_data" action is implemented in the InteractiveChartSupport class that is included as a mixin in the controller.

The image map for the chart is created using the following code:

# Client side Javascript to show detail information "onmouseover"
showText = "onmouseover='showInfo(\"{xLabel}\", {value}, {field0}, {field1});' "

# Client side Javascript to hide detail information "onmouseout"
hideText = "onmouseout='showInfo(null);' "

# "title" attribute to show tool tip
toolTip = "title='{xLabel}: US$ {value|0}M'"

# Create an image map for the chart
@imageMap = c.getHTMLImageMap(url_for(:controller => "xystub"), "", sprintf(
    "%s%s%s", showText, hideText, toolTip))

Note that in additional to the "title" attribute for the tooltips, the image map also includes event handlers "onmouseover" and "onmouseout". These event handles call the client side Javascript function "showInfo", which creates and hides the dynamic HTML block for displaying the additional information.

<script type="text/javascript">
//
//Client side script function to show and hide detail information.
//
function showInfo(year, revenue, grossMargin, backLog)
{
    var obj = document.getElementById('detailInfo');

    if (!year)
    {
        obj.style.visibility = "hidden";
        return;
    }

    var content = "<table border='1' cellpadding='3' style='font:10pt verdana; " +
        "background-color:#CCCCFF' width='480px'>";
    content += "<tr><td><b>Year</b></td><td width='300px'>" + year + "</td></tr>";
    content += "<tr><td><b>Revenue</b></td><td>US$ " + revenue + "M</td></tr>";
    content += "<tr><td><b>Gross Margin</b></td><td>" + grossMargin + "%</td></tr>";
    content += "<tr><td><b>Back Log</b></td><td>US$ " + backLog + "M</td></tr>";
    content += "</table>";

    obj.innerHTML = content;
    obj.style.visibility = "visible";
}
</script>

In this example, we are displaying extra information, such as the "grossMargin" and "backLog" fields, which do not come from the x or y value of the bars. This is achieved by associated these fields as "extra fields" to the data items with Layer.addExtraField2. These extra fields can then be represented using the template "{fieldN}", where "N" represents the field number. (The first field is 0, the second field is 1, etc.)

In addition to responding to mouse over and mouse out events, the chart is also clickable using the "xystub" controller as the handler. For demo purpose, the handler simple displays information on what is clicked. It's code is as follows.

[Ruby On Rails Version - Controller] app/controllers/xystub_controller.rb
class XystubController < ApplicationController
    def index()
        @ctrl_file = File.expand_path(__FILE__)
    end
end

[Ruby On Rails Version - View] app/views/xystub/index.html.erb
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Simple Clickable XY Chart Handler
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20px">
    <%= link_to "Source Code Listing",
        :controller => "cddemo", :action => "viewsource",
        :ctrl_file => @ctrl_file, :view_file => File.expand_path(__FILE__) %>
</div>
<div style="font-size:10pt; font-family:verdana;">
<b>You have clicked on the following chart element :</b><br />
<ul>
    <li>Data Set : <%= params["dataSetName"] %></li>
    <li>X Position : <%= params["x"] %></li>
    <li>X Label : <%= params["xLabel"] %></li>
    <li>Data Value : <%= params["value"] %></li>
</ul>
</div>
</body>
</html>