Book Image

Learning jqPlot

By : Scott Gottreu
Book Image

Learning jqPlot

By: Scott Gottreu

Overview of this book

Table of Contents (19 chapters)
Learning jqPlot
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a jqPlot chart


Download the current version of jqPlot and extract the files to your web server. We'll create the most basic chart we can, as shown in the following steps:

  1. We start by building our HTML file, including jQuery. We also include the jqPlot JavaScript and CSS files from the downloaded ZIP file. We must include jQuery because jqPlot is a plugin for jQuery, which means that it needs jQuery to function properly:

    <!doctype html>
        <head>
          <title>Learning jqPlot</title>
          <meta charset="utf-8">
          <link rel="stylesheet" href="/css/jquery.jqplot.min.css">
         <script src="../js/jquery.min.js"></script>
          <script src="../js/jquery.jqplot.min.js"></script>
        </head>
        <body>

    Note

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you

  2. Next, we create the div element that will contain our chart. We set id to firstChart so that jqPlot will know where to build our chart. Since we are just creating prototypes, we will set the width of our div inline, as shown in the following code.

       <div id="firstChart" style="width:600px"></div>
  3. Finally, we create our jqPlot object and store it in the plot variable. Then, we pass the id attribute of the div, which is firstChart. Finally, we include an array of numbers inside another array, which will be our data points. This is the simplest way to pass in the data:

        <script>
        $(document).ready(function(){
          var plot = $.jqplot ('firstChart', [[1,9,4,3,8,5]]);
        });
        </script>
    </body>
    </html>

Note

We can also create our chart by chaining the jqPlot plugin to the jQuery selector of our div. It will look like the following:

$("#firstChart").jqplot ([[1,9,4,3,8,5]]);

In our examples, we will store our objects in variables so that they are available globally in our JavaScript if required.

jqPlot will interpret each number as a point on the y axis, and it will assign a value for the x axis, starting with 1. We can see the result of our effort in the following screenshot: