HTML5 and CSS3, Second Edition

(singke) #1
To build the graph, we need to grab the graph’s title, the labels, and the data
from the HTML document and pass it to the RGraph library. RGraph takes
in arrays for both the labels and the data. We can use jQuery to quickly build
those arrays. Add this code to javascripts/graph.js:

html5_canvas/javascripts/graph.js
Line 1 varcanvasGraph=function(){


  • vartitle= $('#graph_datah1').text();

  • varlabels= $("#graph_data>ul>li>p[data-name]").map(function(){

  • returnthis.getAttribute("data-name");
    5 });

  • varpercents= $("#graph_data>ul>li>p[data-percent]").map(function(){

  • returnparseInt(this.getAttribute("data-percent"));

  • });

  • varbar =newRGraph.Bar('browsers', percents);
    10 bar.Set('chart.gutter', 50);

  • bar.Set('chart.colors', ['red']);

  • bar.Set('chart.title', title);

  • bar.Set('chart.labels', labels);

  • bar.Draw();


(^15) $('#graph_data').hide();



  • }


First, on line 2, we grab the text for the header. Then, on line 3, we select all
the elements that have the data-name attribute. We use jQuery’s map function
to turn the values from those elements into an array.

We use that same logic on line 6 to grab an array of the percentages.


On line 7, we’re forcing the value from the data attribute to be an integer. We
could also use jQuery’s data() method, which can read HTML5’s data attributes
and automatically convert the value to the appropriate data type.

With the data collected, RGraph has no trouble drawing our graph (see Figure
20, Our graph rendered on the canvas, on page 124).

Displaying Alternative Content


In Describing Data with HTML, on page 121, we could have placed the graph
between the starting and ending <canvas> tags. This would hide these elements
on browsers that support the canvas element while displaying them to browsers
that don’t. However, the content would still be hidden if the user’s browser
supports the canvas element but the user has disabled JavaScript.

Let’s leave the data outside the canvas element and then hide it with jQuery
once we’ve checked that the browser supports the canvas. We’ll use standard
JavaScript instead of Modernizr to detect canvas support, since it’s really
easy.

report erratum • discuss

Graphing Statistics with RGraph • 123


Download from Wow! eBook <www.wowebook.com>

Free download pdf