Click here to Skip to main content
Click here to Skip to main content
Go to top

Creating a Code 39 Barcode using HTML, CSS and Javascript

, 14 Jan 2011
Rate this:
Please Sign up or sign in to vote.
Creating a Code 39 Barcode using HTML, CSS and Javascript

Introduction

This article explores the use of Javascript, HyperText Markup Language (HTML) and Cascading Style Sheets (CSS) for the creation of a Code 39 barcode. This solution described does not employ the use of graphical image and overcomes the problems associated with the limited support of the Data URI feature in some browsers. Server-side scripts are also not required as the steps for creating the barcode e.g. data validation, check character generation and generation of the HTML barcode are performed in Javascript.

Background

One of the objectives of this article is to have a solution to generate a barcode using pure browser (client-side) technology. The first thing that comes into mind is to make use of graphical images, especially considering that a barcode comprises of a sequence of black and white bars. Many modern browsers also support the data Uniform Resource Locators (URI) capability. This capability allows a web page to include in-line data such as images as if they are external resources.

However, one of the most commonly-used browsers, the Internet Explorer (as of current v8.0) does not fully support data URI. In IE8, data URIs must be smaller than 32KB. This poses a problem when we require a barcode image bigger than 32KB.

Another solution is to generate barcode images on the server side. However there are many server technologies in use today including but not limited to Java, .Net, PHP, Perl, Python and Ruby. We hope to have a solution that works on all server platforms. This means that our solution has to be implemented on the browser (client) side without using graphics images.

The Solution

The simplest and easiest way to render a barcode on a web page is to make use of background colors in HTML tables. Each of the black and white bars of the barcode can be represented by the different columns of the tables using different colors. However, upon further investigation, this implementation is proned to problems. Modern browsers e.g. Internet Explorer, implement features to enable and disable the printing of background colors and images. By default, this option is set to "disabled", i.e. when a barcode (generated using HTML tables) is printed, the barcode may not appear as the browser chooses not to print the background. To print such barcodes, users need to follow instructions to enable the "Print Background Colors and Images" option.

After much thought and analysis, we employ a solution to make use of the HTML span element. An example as follows :

			
<SPAN style="BORDER-LEFT: black 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: white 0.06in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: black 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: white 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>

The barcode is represented by a series of span elements each with a different width representing a bar of the barcodes. The span elements also have alternating black and white colors without any space between them. The Javascript code, included in the source zip file, basically converts an input data to a series of alternating black and white bars as shown below. The Human Readable Text portion of the barcode is also rendered using HTML text.

htmlbarcode1.png

Using the Code

Create a HTML file (or you can use the Code39Barcode.html file provided in the source zip file). In the file, include the Code 39 barcode creation script.

			
<script type="text/javascript" src="code39.js"></script>

The script enables the generation of a Code 39 barcode. The first parameter is the input data and the second parameter is to indicate whether to generate the check chracter.

			
DrawCode39Barcode("123456",1);

To make use of the above function, include the following section into the body of the HTML file.

			
<div id="externalbox" style="width:4in">
<div id="inputdata">123456</div>
</div>
 
<br />
 
<script type="text/javascript">
/* <![CDATA[ */
  function get_object(id) {
   var object = null;
   if (document.layers) {
    object = document.layers[id];
   } else if (document.all) {
    object = document.all[id];
   } else if (document.getElementById) {
    object = document.getElementById(id);
   }
   return object;
  }
get_object("inputdata").innerHTML=DrawCode39Barcode(get_object("inputdata").innerHTML,1);
/* ]]> */
</script>

The main action is in the line:

			
get_object("inputdata").innerHTML=DrawCode39Barcode(get_object("inputdata").innerHTML,1);

This line of code gets the div element of id="inputdata" and replaces it with the output of the Javascript function DrawCode39Barcode. The output of the function is the series of span elements as described above.

The output of the HTML file is as shown below:

htmlbarcode2.png

Understanding the Code

The Javascript code translates the input data characters to a series of barcode patterns and then convert the patterns to a series of HTML span elements. For example, the character "1" is translated to the pattern "wttwttttwt". 't' is known as the thin bar of the barcode while 'w' is known the thick bar of the barcode. Under the Code 39 specifications, the thick bar can be from 2-3x the width of the thin bar. So the first step to create a Code 39 barcode means translating the input data to a series of thick and thin bar patterns. For example, the input "123" can be translated to the following patterns:

"wttwttttwtttwwttttwtwtwwtttttt"

The "EncodeCode39" Javascript function performs the task of what is described above.

  function EncodeCode39(data,checkDigit)
            {
                var fontOutput = ConnectCode_Encode_Code39(data,checkDigit);
                var output = "";
                var pattern = "";
                for (x = 0; x < fontOutput.length; x++)
                {
                    switch (fontOutput.substr(x,1))
                    {
                        case '1':
                            pattern = "wttwttttwt";
                            break;
                        case '2':
                            pattern = "ttwwttttwt";
                            break;
                        case '3':
                            pattern = "wtwwtttttt";
				.
				.
				.
				.
				.
                        case 'Z':
                            pattern = "twwtwttttt";
                            break;
				default : break;
                    }
                    output=output+pattern;
                }
                return output;
            }

The next step involves translating the barcode patterns to a series of HTML span elements.

"wttwttttwtttwwttttwtwtwwtttttt"

The series of patterns above gets translated to the following :

			
<SPAN style="BORDER-LEFT: black 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: white 0.06in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: black 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: white 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: black 0.06in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: white 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: black 0.06in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
<SPAN style="BORDER-LEFT: white 0.02in solid; DISPLAY: inline-block; HEIGHT: 1in"></SPAN>
.
.
.

The code for performing this task is found in the function "DrawBarcode_Code39". Other functions worth mentioning is the code for generating the Check Character. This can be found in the "generateCheckDigit" function.

Points of Interest

The solution has been tested to work on the following browsers:

  • IE 6, 7 and 8
  • Firefox 3.5+
  • Chrome 5,6
  • Opera 10+
  • Safari 5

When the barcodes are printed, they can be easily scanned by various brands of barcode scanners. On top of that, most newer browsers also tend to respect the width settings of the HTML span element very accurately. This allows very precise barcodes to be created. Moreover, it is important to remember that this solution is interesting as it does not make use of server-side programming or graphical image technology.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

ConnectCode

Singapore Singapore
No Biography provided

Comments and Discussions

 
QuestionBrowser compatability PinmemberDnyaneshwar@Pune7-Jul-14 23:49 
QuestionChrome PinmemberMember 1069597224-Mar-14 10:11 
Questionhow to use this in asp.net Pinmembervbmon20-Jan-14 9:58 
QuestionCode 39 PinmemberMember 1052920616-Jan-14 15:42 
QuestionProblem using this code PinmemberNorman Berger15-Jan-14 6:57 
QuestionDo I have to display the check digit. [modified] PinmemberMarçau2-Oct-13 5:36 
GeneralIncredible, Amazing solution PinmemberCleveland Mark Blakemore1-Oct-13 15:38 
QuestionMessage Automatically Removed Pinmembercathyhill2-Jul-13 15:48 
QuestionIE rendering problem PinmemberMember 1005511315-May-13 9:41 
QuestionIs it possible to change the Pattern Pinmemberjeswinjoy21-Nov-12 1:33 
Questionmorethan50Characters Pinmemberamish01017-Oct-12 0:39 
QuestionMultiple codes to a code39 barcoe [modified] PinmemberMember 944775626-Sep-12 23:06 
AnswerRe: Multiple codes to a code39 barcoe PinmemberMarçau2-Oct-13 7:41 
I'm working with several codes as well, would you please tell me how you made "inputdata"variable?
GeneralRe: Multiple codes to a code39 barcoe PinmemberMember 106488349-Jul-14 8:30 
Questionno lee el lector la impresion del codigo de barras Pinmemberdeyberth6-Aug-12 10:41 
GeneralMy vote of 5 PinmemberOlanrewaju Sideeq17-Jan-12 1:05 
GeneralMy vote of 5 PinmemberStoelpascal21-Dec-11 3:03 
GeneralGPL? Pinmemberjoeyjoejoejoe24-May-11 11:07 
GeneralMy vote of 5 PinmemberMihai Maerean17-Jan-11 3:43 
Generalhave 5 PinmemberPranay Rana16-Jan-11 20:07 
GeneralHTML Barcode Project PinmemberConnectCode16-Jan-11 15:08 
GeneralRe: HTML Barcode Project Pinmemberfinesite9-Jul-11 14:20 
GeneralVery good PinmemberLloyd Atkinson14-Jan-11 9:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 14 Jan 2011
Article Copyright 2011 by ConnectCode
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid