Easy Pie Chart - Documentation

Introduction

What is Easy Pie Chart?

Easy Pie Chart is a lightweight JavaScript plugin that allows you to easily create attractive and responsive circular progress bars (pie charts) on your web pages. It’s designed for simplicity and ease of use, requiring minimal code to integrate and customize. Easy Pie Chart focuses on providing a clean and visually appealing representation of percentage-based data, ideal for dashboards, progress indicators, and other applications where a quick visual representation of progress or completion is needed.

Key Features and Benefits

Installation and Setup

Easy Pie Chart can be integrated into your project in several ways:

1. Using a CDN (Content Delivery Network):

The easiest way to get started is by including the Easy Pie Chart JavaScript file from a CDN, such as jsDelivr:

<script src="https://cdn.jsdelivr.net/npm/easy-pie-chart@2.1.7/dist/jquery.easypiechart.min.js"></script>

Remember that this method requires jQuery to be included as well:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

2. Downloading and Including Locally:

Alternatively, you can download the Easy Pie Chart library from its source and include it in your project:

  1. Download the jquery.easypiechart.min.js file from the official repository or a package manager like npm.
  2. Place the downloaded file in your project’s JavaScript directory.
  3. Include the file in your HTML using a <script> tag:
<script src="path/to/jquery.easypiechart.min.js"></script>
```  Replace `"path/to/"` with the actual path to your file.  Again, ensure jQuery is included.

**3. Using a Package Manager (npm):**

If you are using npm, you can install Easy Pie Chart with the following command:

```bash
npm install easy-pie-chart

Then, include it in your project using a module bundler such as Webpack or Parcel.

After including the necessary files, you’re ready to start creating your Easy Pie Charts. Refer to the usage documentation for detailed instructions on how to initialize and configure the plugin.

Basic Usage

Creating a Simple Pie Chart

Creating a basic pie chart with Easy Pie Chart is straightforward. First, ensure you have included the necessary JavaScript files (jQuery and Easy Pie Chart) as described in the Installation and Setup section. Then, add a <div> element to your HTML where you want the chart to appear. This div will act as the container for your chart. Finally, use jQuery to initialize the plugin on this element.

<!DOCTYPE html>
<html>
<head>
  <title>Easy Pie Chart Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/easy-pie-chart@2.1.7/dist/jquery.easypiechart.min.js"></script>
  <style>
    .chart { width: 100px; height: 100px; }
  </style>
</head>
<body>

<div class="chart" data-percent="75"></div>

<script>
  $('.chart').easyPieChart();
</script>

</body>
</html>

This code creates a pie chart with a percentage of 75%. The data-percent attribute specifies the percentage to be displayed. The CSS sets a basic size; you can adjust this as needed.

Setting the Chart Size and Colors

You can customize the size and colors of your Easy Pie Chart using options passed to the easyPieChart() function. The options are passed as a JavaScript object.

$('.chart').easyPieChart({
  barColor: '#ef1e25', // Set the color of the progress bar
  trackColor: '#f2f2f2', // Set the color of the track
  scaleColor: false,     // Disable the scale
  lineWidth: 10,        // Set the width of the progress bar
  size: 150,            // Set the size of the chart (diameter)
  lineCap: 'round'      // Set the line cap style ('butt', 'round', 'square')
});

This example demonstrates how to change the bar color, track color, line width, and size. Experiment with different color values (hex codes, RGB, etc.) and lineCap options to achieve your desired look. Setting scaleColor to false hides the scale markings around the chart.

Data Input and Formatting

The percentage value can be set dynamically using the data-percent attribute or by providing the value in the options:

Using data-percent attribute:

This method is convenient for static values:

<div class="chart" data-percent="60"></div>

Using the percent option:

This approach is better for dynamically updating charts, using JavaScript variables:

let myPercentage = 85;
$('.chart').easyPieChart({
  percent: myPercentage
});

You can also format the displayed percentage using the onStep callback function. This function receives the current percentage as an argument, allowing for custom formatting:

$('.chart').easyPieChart({
  onStep: function(from, to, percent) {
    $(this.el).find('.percent').text(Math.round(percent));
  }
});

This example rounds the percentage to the nearest whole number. Remember that the onStep function needs a <span class="percent"> within the chart’s <div> for this specific formatting to work. You’ll likely want to add that span in your HTML. For more complex formatting, you can use string manipulation within the onStep function.

Customization

Configuring the Chart Appearance

Easy Pie Chart provides numerous options for customizing the visual appearance of your pie charts. These options are passed as a JavaScript object to the easyPieChart() function. Many of these were touched on previously, but we’ll delve deeper here.

The core options control the chart’s size, percentage display, and basic colors:

$('.chart').easyPieChart({
  size: 120,          // Diameter of the chart
  lineWidth: 5,       // Width of the progress bar
  scaleColor: '#dfe0e0', // Color of the scale (if shown)
  trackColor: '#e2e2e2', // Color of the background track
  barColor: '#3498db',   // Color of the progress bar
  scaleLength: 5,    // Length of scale lines
  percent: 80,         // Percentage to display
});

Remember to adjust the size proportionally with lineWidth to maintain a visually balanced chart.

Line Width and Cap

The lineWidth option controls the thickness of the progress bar. The lineCap option determines the shape of the ends of the progress bar:

$('.chart').easyPieChart({
  lineWidth: 12,
  lineCap: 'round' // or 'butt', 'square'
});

Scale and Value Display

The scaleColor option sets the color of the scale markings. Setting it to false hides the scale entirely. The percent option directly sets the displayed percentage, overriding any data-percent attribute. The animate option (discussed below) handles the animation of the chart.

$('.chart').easyPieChart({
  scaleColor: '#555', // Show scale with gray color
  percent: 55,
  animate: 1000      // Animation duration
});

$('.chart2').easyPieChart({
  scaleColor: false, // Hide the scale
  percent: 90
});

Animation Options

The animate option controls the animation speed of the chart. The value represents the animation duration in milliseconds. Setting it to 0 disables animation:

$('.chart').easyPieChart({
  animate: 1500 // 1.5-second animation
});

$('.chart2').easyPieChart({
  animate: 0 // No animation
});

Customizing Colors and Styles

Beyond the basic color options, more advanced styling can be achieved by using CSS to target the chart elements directly. Inspect the generated HTML structure to identify the classes you can target for further customization. You might style the track, the bar, and the percentage text separately using CSS.

For example, you could add your own CSS rules to style the percentage text:

.easyPieChart .percent {
  font-size: 2em;
  font-weight: bold;
  color: #007bff;
}

Adding a Track

Easy Pie Chart doesn’t explicitly offer a separate “track” element as a configurable option. The track is implicitly the background circle. You can customize its appearance using the trackColor option and by applying CSS to the chart container or its internal elements if you need more complex styling. Keep in mind the structure of the generated HTML.

Advanced Usage

Handling Events

Easy Pie Chart doesn’t directly offer a robust event system for tracking specific chart interactions. However, you can leverage jQuery’s event handling capabilities to monitor changes to the chart’s value or other relevant aspects. For example, if you update the chart’s percentage using JavaScript, you might trigger a custom event afterward to signal other parts of your application about the change.

let myChart = $('.chart').easyPieChart({
  percent: 50
});

//Simulate updating chart value after some time
setTimeout(() => {
  myChart.data('easyPieChart').update(75);
  $('.chart').trigger('chartUpdated'); //Trigger custom event
}, 2000);

//Listen to the custom event
$('.chart').on('chartUpdated', function() {
  console.log('Chart value updated!');
});

This approach uses a custom chartUpdated event, but you can choose any appropriate event name. Remember that directly accessing internal properties of the Easy Pie Chart instance (e.g., myChart.data('easyPieChart')) might be fragile and depend on the internal structure of the plugin; this is not officially supported.

Integrating with Other Libraries

Easy Pie Chart is designed to work well with other JavaScript libraries, especially jQuery. Its core functionality relies on jQuery, but its minimalist design generally ensures compatibility with most other libraries as long as there are no conflicting selectors or event handlers. You could integrate it with charting libraries, data visualization frameworks, or UI toolkits as long as you manage potential conflicts between libraries’ styles and behaviors.

Responsive Design and Mobile Support

Easy Pie Chart is inherently responsive; it scales correctly across different screen sizes. However, you might need to adjust its size and styles using CSS media queries to ensure optimal rendering on various devices.

For example:

@media (max-width: 768px) {
  .chart {
    width: 80px;
    height: 80px;
  }
}

This adjusts the chart’s size on screens narrower than 768 pixels. Always test your implementation across different devices and screen resolutions.

Troubleshooting and Common Issues

If you encounter problems not covered here, consult the Easy Pie Chart’s official documentation or search for relevant issues on GitHub or Stack Overflow. Providing details about your setup, code snippet, and error messages will help others assist you.

API Reference

Easy Pie Chart Constructor

The Easy Pie Chart plugin is initialized using jQuery’s easyPieChart() method. This method is applied to a jQuery selection of elements (typically a single <div> element) that will act as containers for the charts. Options for customizing the chart’s appearance and behavior are passed as a JavaScript object to this method.

$('.chart').easyPieChart({
  // options here...
});

The constructor returns a jQuery object containing the elements on which the plugin was initialized. Each element will have its Easy Pie Chart instance stored in its jQuery data using the key 'easyPieChart'. While you can access this data, directly manipulating the internal plugin objects is generally not recommended and is unsupported as the internal structure may change between versions.

Methods

The Easy Pie Chart plugin primarily relies on options provided at initialization. There isn’t an extensive public API with explicit methods to change options after initialization. However, there’s one crucial method available: update().

let myChart = $('.chart').easyPieChart({ percent: 50 });
setTimeout(() => { myChart.data('easyPieChart').update(80); }, 2000);

The update() method is accessible through the plugin instance that is stored in the jQuery data (myChart.data('easyPieChart')). Again, directly accessing this instance is not officially supported and might break in future versions of the plugin.

Options

The following options are available when initializing Easy Pie Chart. Most are described in previous sections. All values are optional unless specified otherwise.

Events

Easy Pie Chart itself does not define custom events. However, you can use jQuery’s event system to monitor changes or to trigger custom events in conjunction with methods like update(), as shown in the “Handling Events” section above. There are no built-in events triggered by the plugin itself.

Examples

Example 1: Basic Pie Chart

This example demonstrates the simplest implementation of Easy Pie Chart:

<!DOCTYPE html>
<html>
<head>
<title>Easy Pie Chart - Basic Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/easy-pie-chart@2.1.7/dist/jquery.easypiechart.min.js"></script>
</head>
<body>

<div class="chart" data-percent="75"></div>

<script>
  $('.chart').easyPieChart();
</script>

</body>
</html>

This creates a pie chart displaying 75% using the default styling. Remember to include jQuery and Easy Pie Chart.

Example 2: Customized Pie Chart

This example demonstrates customization of the chart’s appearance:

<!DOCTYPE html>
<html>
<head>
<title>Easy Pie Chart - Customized Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/easy-pie-chart@2.1.7/dist/jquery.easypiechart.min.js"></script>
<style>
  .chart-container { width: 200px; height: 200px; }
</style>
</head>
<body>

<div class="chart-container">
  <div class="chart" data-percent="60"></div>
</div>

<script>
  $('.chart').easyPieChart({
    barColor: '#ff6384',
    trackColor: '#e0e0e0',
    scaleColor: false,
    lineWidth: 15,
    size: 180,
    lineCap: 'butt'
  });
</script>

</body>
</html>

This creates a chart with a custom bar color, track color, line width, size, and line cap, and hides the scale.

Example 3: Dynamically Updating Charts

This example shows how to update the chart’s value dynamically using the update() method:

<!DOCTYPE html>
<html>
<head>
<title>Easy Pie Chart - Dynamic Update</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/easy-pie-chart@2.1.7/dist/jquery.easypiechart.min.js"></script>
</head>
<body>

<div class="chart" data-percent="20"></div>
<button id="updateButton">Update Chart</button>

<script>
  let chart = $('.chart').easyPieChart();
  $('#updateButton').click(function() {
    let currentPercent = parseInt($('.chart').attr('data-percent'));
    let newPercent = (currentPercent + 10) % 101; //Keep it within 0-100
    $('.chart').data('easyPieChart').update(newPercent);
    $('.chart').attr('data-percent', newPercent);
  });
</script>

</body>
</html>

This creates a chart and a button. Clicking the button increments the chart’s value by 10% (wrapping around at 100%).

Example 4: Integration with Other Libraries

This example is conceptual, as it depends on the choice of other libraries. To integrate with another library, you would typically use the library’s features to generate or manipulate data and then use Easy Pie Chart to display this data as a pie chart.

For instance, if you are using a library to fetch data from an API, once you have the percentage value, you can update an Easy Pie Chart instance as shown in Example 3. The key is to treat Easy Pie Chart as a visualization component that uses data from other parts of your application. There is no specific integration needed beyond proper data handling and the standard use of the update() method.