Jul 16 2012

Add Shadows with CSS box-shadow Property

Over the last few years web browsers have made a lot of progress to add new features based on what is shaping up to be HTML5 and CSS3. I’ve already demonstrated what can be done with new CSS properties such as the CSS border-radius property. Now, I’ll cover the CSS box-shadow property.

Using box-shadow
This tutorial will demonstrate how to add shadows to a div HTML element using the CSS box-shadow property. For the purpose of this tutorial, we’ll the following CSS class that defines our div box.

.box {
    width: 100px;
    height: 100px;
    float:left;
}

As you can figure out by the property name, the box-shadow property can be used to create a shadow outside, or inside of your div box. In the simplest forms, you can add a drop shadow on the lower right of a div tag by adding the following CSS on the style attribute of the div.

<div class='box' style='box-shadow: 20px 20px 50px blue;'></div>

The first numeric value in the box-shadow property is the length of the shadow on the horizontal side of the div box, the second numeric value is the length of the shadow on the vertical side. The third value is the length of the blur. Additionally, you can add a blur color.

By default, having positive values for the horizontal and vertical blur length will produce a blue on the lower right of the div tag. Negative values are allowed which will mirror the blur on the other side. For example, to create a blue on the lower left side of the div tag change the box-shadow to the following.

<div class='box' style='box-shadow: -20px 20px 50px blue;'></div>

Using box-shadow with inset
You can add an additional value, inset, to force the shadow to be inside of the div tag. By default, by adding the inset value the shadow will be on the top left of the div but inside of the box.

<div class='box' style='box-shadow: 20px 20px 50px blue inset;'></div>

To change the direction of the box shadow, just switch the horizontal and vertical blur length values from positive values to negative.

Even blur
In addition to negative or positive values, you can enter 0 for the horizontal and vertical blur length. When you enter 0, the blur will be on both top-bottom for the horizontal and left-right for the vertical directions.

<div class='box' style='box-shadow: 0px 0px 50px blue;'></div>
Examples of box-shadow CSS property

Examples of box-shadow CSS property

To see some more examples of the box-shadow property in action see the the following gist.

Modern browsers
The CSS box-shadow works on modern browsers, which include the latest version of Safari, Chrome, and Firefox. As of this writing, it does not work in Internet Explorer.


Jul 5 2012

Disable Right Click Menu in HTML

When browsing a webpage, you typically can click the right button on the mouse to reveal a context menu. The right click context menu usually has options such as Back, Forward, Reload, Stop, and View Page Source. When right clicking on an image, you have have the option to save the image or even set it as the desktop background. It’s rare but sometimes you want to disable the right click context menu. To disable the right click context menu you can set the oncontextmenu event to return false.

<body oncontextmenu="return false;">

If you only want to disable the right click context menu on a small part of your site, for example an image you don’t want your visitors to easily download or save you can add the oncontextmenu property to any div or img tag and disable the context menu only in that HTML tag.


Jul 4 2012

Rounded Corners with CSS border-radius Property

Modern browsers have come a lone way since 2006. Back in 2006, Web 2.0 and AJAX was the hottest technologies for web developers (just like HTML5 and CSS3 is now) and rounded corners was one the coolest things you could do to a web page. Unfortunately, in 2006 the easiest way to have rounded corners in a HTML tag such as a div was to use JavaScript and images and all other sorts of hacks. Thankfully, most modern browsers (all but IE) support the CSS border-radius style which can be used to curve and round a corner.

Using border-radius
For the following examples, I’ll using the following CSS classes, which I hope are self explanatory.

.box {
    width: 100px;
    height: 100px;
    float:left;
}

.red {
    background: red;
}

.orange {
    background: orange;
}

.green {
    background: green;
}

.purple{
    background: purple;
}

The easiest use of border-radius is where all four corners have the same border curve radius. If all corners have the same curve radius all you need to supply is one px radius value.

<div class='box orange' style='border-radius: 20px;'></div>

In the examples provided in this tutorial, we fixed the width and height of the box div to be 100px. If we increase the border radius to 50px we can have a perfect circle.

<div class='box orange' style='border-radius: 50px;'></div>

What makes the border-radius property powerful is that you can set a different radius for each corner. Just enter four values, the first one will set the radius for the top-left corner, the second sets the top-right, then the bottom-right, and the bottom-left corner. If the value 0px is used, that corner will not have any curvature. The following HTML examples sets different border radius values for each corner generating a leaf looking shape.

<div class='box green' style='border-radius: 0px 60px 40px 60px;'></div>

Placing four similar div tags in place, you can create a four leaf clover shape or a circle.

<!-- four leaf clover -->
<div class='box red' style='border-radius: 50px 75px 0px 75px;'></div>
<div class='box orange' style='border-radius: 75px 50px 75px 0px;'></div>
<br style='clear:both' />
<div class='box green' style='border-radius: 75px 0px 75px 50px;'></div>
<div class='box purple' style='border-radius: 0px 75px 50px 75px;'></div>

<br style='clear:both' />

<!-- circle -->
<div class='box red' style='border-radius: 100px 0px 0px 0px;'></div>
<div class='box orange' style='border-radius: 0px 100px 0px 0px;'></div>
<br style='clear:both' />
<div class='box green' style='border-radius: 0px 0px 0px 100px;'></div>
<div class='box purple' style='border-radius: 0px 0px 100px 0px;'></div>

You can even nested rounded div tags to create a bullseye image.

Fun with CSS border-radius

Fun with CSS border-radius

As of this time, Chrome, Safari, and Firefox support border-radius.


Jun 29 2012

Pie Charts with jqPlot JavaScript Charting Library

It’s incredibly easy to generate great looking pie charts with jqPlot. jqPlot is a jQuery plugin that can be use to generate pure HTML5 charts. Create pie charts in jqPlot is as easy as it is to create bar charts, the only difference is how we pack the data.

Getting Started
The code snippets for this example assume you have already downloaded jqPlot and have included the following JavaScript and CSS source files from the distribution.

<link rel="stylesheet" type="text/css" href="jqplot/jquery.jqplot.min.css" />
<script src="jqplot/jquery.min.js" ></script>
<script src="jqplot/jquery.jqplot.min.js" ></script>    
<script src="jqplot/plugins/jqplot.pieRenderer.min.js"></script>

The jqPlot graphs are drawn on a div tag and this example will require the following HTML snippet.

<body onload='drawChart()'>
   <div id="chartDivId" style="margin-top:20px; margin-left:20px; width:600px; height:300px;"></div>
</body>

Pie Chart Data
A single slice of a pie chart is stored in a two element array where the first elemnt contains the string label and the second element stores the slice data value. A single pie series is made up of one ore more slices, and a pie chart may have one or more series. The typical pie chart is made up of one series, but there are some charts that can allow for multiple pie series.

function drawChart() {
  var slice_1 = ['North America', 150];
  var slice_2 = ['Europe', 50];
  var series = [slice_1, slice_2];
  var data = [series];

  var options = {
    title: 'Sales by Region',
    seriesDefaults: {
      renderer: jQuery.jqplot.PieRenderer
    },
    legend: { show:true, location: 'e' }
  };
  
  $.jqplot('chartDivId', data, options);
}

jqPlot will all compute the percent for each slice based on it’s value, so the slice for North America will be 75%, and Europe will be 25% for the the values 150 and 50, respectively. The pie chart generated from the above code will be simple and undecorated.

jqPlot Pie Chart

jqPlot Pie Chart

We can add additional options, for example, maybe we want to display the percent amount for each slice. To do so, we can update the options object with the showDataLabels property such as the in the following JavaScript code snippet.

var options = {
  title: 'Sales by Region',
  seriesDefaults: {
    renderer: jQuery.jqplot.PieRenderer,
    rendererOptions: {
      showDataLabels: true
    }
  },
  legend: { show:true, location: 'e' }
};

By default, the showDataLabels property shows the percent of the slice. To show the slice data value, rather than the percent, set the dataLabels property to ‘value’ such as the following code.

var options = {
  title: 'Sales by Region',
  seriesDefaults: {
    renderer: jQuery.jqplot.PieRenderer,
    rendererOptions: {
      showDataLabels: true,
      dataLabels: 'value'
    }
  },
  legend: { show:true, location: 'e' }
};

You can further change how the pie chart is rendered by setting the fill, sliceMargin, and lineWith rendererOptions object properties. The fill property accepts a boolean value, and you can specify the sliceMargin and lineWith with an interger value. You can also specify the angle from which to start with the startAngle property. Putting all this together, you can create a pie chart like the following.

var options = {
  title: 'Sales by Region',
  seriesDefaults: {
    renderer: jQuery.jqplot.PieRenderer,
    rendererOptions: {
      showDataLabels: true,
      dataLabels: 'value',
      fill: false,
      sliceMargin: 5,
      lineWidth: 5,
      startAngle: 45
    }
  },
  legend: { show:true, location: 'e' }
};
jqPlot_Pie_Chart with No Fill

jqPlot_Pie_Chart with No Fill

Donut Chart
Using the same data and same options object, you can render a pie chart as a donut. To display a donut chart you will need to load int the jqPlot donut renderer.

<script src="jqplot/plugins/jqplot.donutRenderer.min.js"></script>

Once you have loaded the donut renderer, just update the render property in the options object.

var options = {
  title: 'Sales by Region',
  seriesDefaults: {
    renderer: jQuery.jqplot.DonutRenderer,
    rendererOptions: {
      showDataLabels: true,
      dataLabels: 'value',
      fill: false,
      sliceMargin: 5,
      startAngle: 45
    }
  },
  legend: { show:true, location: 'e' }
};
jqPlot Donut Chart

jqPlot Donut Chart


Jun 27 2012

Using JavaScript Charting Library jqPlot with Bar Charts

jqPlot is a plugin for the jQuery JavaScript framework used to generate awesome looking charts and graphs. Even though it has a lot of features and supports many chart types it is incredibly easy to use. To create a simple chart you will use will use something like the following template.

$.jqplot(divId, dataArray, optionsObject);

In the above example, divId is the String object containing the name of the div on which to draw the chart. The dataArray variable will hold the data for the chart and the optionsObject will have configuration properties used to display the chart.

Getting Started
To get started with jqPlot, you will need to download the latest release. Because jqPlot offers a wide selection of chart types, it is broken down into different JavaScript files. You’ll only need to load the JavaScript files for the chart type you will be working with. For example, to display a bar chart you will need to include the following JavaScript source files.

<link rel="stylesheet" type="text/css" href="jqplot/jquery.jqplot.min.css" />
<script src="jqplot/jquery.min.js" ></script>
<script src="jqplot/jquery.jqplot.min.js" ></script>    
<script src="jqplot/plugins/jqplot.barRenderer.min.js"></script>
<script src="jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>

For the purpose of this tutorial, assume that I have a div tag that will be used to draw the chart when the the page loads. On the page load event, a JavaScript function will fire which has the jqPlot code to draw the chart. Here is an example of the what the div tag looks.

<body onload='drawChart()'>
   <div id="chartDivId" style="margin-top:20px; margin-left:20px; width:400px; height:300px;"></div>
</body>

The following code for drawChart will hard code the values for a bar chart with three series for Jan, Feb, and Mar. This could be used to track the sales of three different items over that month or other similar data. Here is the jqPlot JavaScript code to draw a bar chart inside the chartDivId div.

function drawChart() {
  var s1 = [2, 6, 7];
  var s2 = [7, 5, 3];
  var s3 = [2, 3, 5];
  var s4 = [1, 7, 2];
  
  // chart data
  var dataArray = [s1, s2, s3, 24];
  
  // x-axis ticks
  var ticks = ['Jan', 'Feb', 'Mar'];
  
  // chart rendering options
  var options = {
    seriesDefaults: {
      renderer:$.jqplot.BarRenderer
    },
    axes: {
      xaxis: {
        renderer: $.jqplot.CategoryAxisRenderer,
        ticks: ticks
      }
    }
  };

  // draw the chart
  $.jqplot('chartDivId', dataArray, options);
}

For a bar chart, the chart data is an array of nested arrays holding the values each tick along the x-axis. In the above example, we are tracking three points along the x-axis so our we have three data points for each series. The options object is used to configure how the rendering of the chart, it specifies that this should be a bar chart and sets the x-axis.

jqPlot Bar Graph

jqPlot Bar Graph

jqPlot Bar Chart Options
We can easily change this from a bar chart to a bar stacking chart by adding one property to the the options object (stackSeries: true). By adding one line of code we can drastically change the chart we generate. Another options you may want to set is the title, to add a title to your graph setht the title poperty.

// chart rendering options
var options = {
  stackSeries: true,
  title: 'Q1 Sales',
  seriesDefaults: {
    renderer:$.jqplot.BarRenderer
  },
  axes: {
    xaxis: {
      renderer: $.jqplot.CategoryAxisRenderer,
      ticks: ticks
    }
  }
};

Another quick options you might consider enabling is the legend. You can position the location of the legend by using the following compass directions: nw, n, ne, e, se, s, sw, w

// chart rendering options
var options = {
  stackSeries: true,
  title: 'Q1 Sales',
  legend: {
    show: true,
    location: 'ne'
  },
  seriesDefaults: {
    renderer:$.jqplot.BarRenderer
  },
  axes: {
    xaxis: {
      renderer: $.jqplot.CategoryAxisRenderer,
      ticks: ticks
    }
  }
};

You can further customize the label for each of your series by adding the series option object.

// chart rendering options
var options = {
  stackSeries: true,
  title: 'Q1 Sales',
  legend: {
    show: true,
    location: 'ne'
  },
  series: [
    {label: 'Memberships'},
    {label: 'eBooks'},
    {label: 'Conference Tickets'},
    {label: 'Support'}
  ],
  seriesDefaults: {
    renderer:$.jqplot.BarRenderer
  },
  axes: {
    xaxis: {
      renderer: $.jqplot.CategoryAxisRenderer,
      ticks: ticks
    }
  }
};
jqPlot Stacking Bar Graph

jqPlot Stacking Bar Graph

There is a lot more that can be done with jqPlot. As a jQuery plugin, jqPlot will easily fit into any web developer’s toolbox as the go to JavaScript charting library.


Jun 26 2012

Pure JavaScript Charting Library

Most business applications display some amount of data in charts and graphs. If a picture is worth a thousand words, then a clean visual representation of business data is worth a lot more. Business charts can condense a lot of data points into a easy to understand graph.

Recently, I was tasked with updating the graph solution of a financial application with a HTML5 friendly charting tool or library. I looked at about half a dozen JavaScript chart libraries and eventually narrowed the selection down to two based on features and functionality: Google Charts and jQuery chart plugin jqPlot. Both Google Charts and jqPlot support a large number of chart types, from the basic bar and pie to more advance features such as multiple y-axis and and zoom. Both libraries support HTML5 graphics, the legacy chart solution I was to replace generated a pixelated image. Google Charts and jqPlot both draw the graph into div tag instead by using HTML5 graphics and don’t anti-aliasing issues.

For this particular project, we picked jqPlot over Google Charts for the following reasons. Google Charts is not open sourced and it uses a loading mechanism that requires you to be online to load the JavaScript source files from Google’s servers. This is great if you are always online, but the project owners wanted a HTML5 charting solution that works offline. jqPlot is a freely available open source JavaScript library which can be hosted alongside with the other application resources. jqPlot, like Google Charts, has a large number of chart types it supports including line, area, bubble, bar stacked, pyramid, pies, donuts, gauges, and much more.

jqPlot JavaScript Chart Library

jqPlot JavaScript Chart Library