20
Sat, Apr
5 New Articles

Learn How JavaScript Can Help Create Dynamic Web Browser Interfaces

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Today's JavaScript is a richly expressive, powerful language that's indispensable for developing modern, Web 2.0 applications.

 

JavaScript is the ugly duckling of the Web development world. It doesn't seem to get the respect it deserves. There are probably a few reasons for this:

•·        The name is confusing. Although it has the word "Java" in it, JavaScript bears no relation to Java. It is completely different in philosophy, design, use, and implementation.

•·        The word "Script" makes it sound like a toy language. It conjures up images of "script kiddies" plugging in plagiarized pieces of badly formed code to play pranks on Web sites, or hearkens one's mind back to the days of Visual Basic, when it was a primitive script language.

•·        Up until the last two or three years, JavaScript has been associated with cute but essentially useless Web page features such as scrolling news tickers, rotating banners, flashing images, annoying pop-up windows, or other gimmicks that make Web pages look and feel "oh so nineties!" 

•·        It's easy to write bad code.

•·        Good development tools and debuggers for JavaScript are scarce.

 

In reality, JavaScript is a full-blown, serious language that is an essential component of modern (read: last three years) Web applications. It acts as the glue between server-side code (business logic, database access, etc.) and client-side presentation code using HTML and CSS.

 

JavaScript has made possible the existence of a plethora of UI components for Web applications, often referred to as "patterns." Here's a list of some typical patterns in widespread use:

 

•·        Folder trees 

•·        Drop-down menus

•·        Breadcrumbs

•·        Tabs

•·        Fieldsets (related forms elements)

•·        Autocomplete boxes (like Google's "Suggest")

•·        Show/Hide columns/areas of page

•·        AJAX partial-page updates

•·        Help text

•·        Calendar pop-ups

•·        Draggable pop-up divs

•·        Data grids

•·        Right-click (or Contextmenu) menus

 

Besides being a procedural language, JavaScript has object-oriented features such as limited polymorphism and inheritance. It is also a functional language, meaning it is possible to dynamically create functions and treat them as data. This feature is extremely powerful and crucial for scaleable implementation of Web apps using AJAX. It makes it possible to instantiate a single AJAX object that can serve multiple conversations (requests and responses), making efficient use of memory. Understanding JavaScript as a functional language has really only become prevalent in the last couple of years. Technical leaders like Doug Crockford (senior JavaScript architect at Yahoo!) and John Resig (author of JQuery) have written authoritatively about the topic.

 

JavaScript has a lot of strengths that are also subject to abuse as a result of poor development methodologies. Because JavaScript is a loosely typed, interpreted language that runs directly in a Web page, it is often programmed or used in an ad hoc fashion. That is, developers may write a piece of experimental script for a proof of concept, get it running in their browser, and then deploy it. Or they may view the source of someone else's Web site and "borrow" the script from that page. In addition, lots of free JavaScript-written scripts are available for anyone to download and use, much of questionable quality. The ready availability of JavaScript code and the ease with which you can start writing it can lead to several problems:

 

•·        Inconsistent and/or poorly written code

•·        Lack of code documentation (generally, JavaScript code consists only of source, which anyone looking at your Web page can see, so developers often do not document their code)

•·        Lack of standards in code (variable names, declarations, scope, etc.)

•·        Inconsistent behavior of the code in different browsers

•·        Maintenance problems (if the code originated as open source, the developer who borrows it may never really understand what he has incorporated in his pages, making it difficult to maintain)

 

Here's how you can address these problems:

1.      Consider using a JavaScript library of code. A "library" is a set of functions and APIs that are written to conform to a defined set of coding standards. Such libraries are coded to provide cross-browser compliance. There are several open-source libraries to choose from, including Yahoo!'s User Interface JavaScript library (YUI), Prototype, Scriptaculous (an add-on to Prototype), Google APIs (this is not really a complete coding library, but it does provide a lot of AJAX functions), and JQuery (I'll discuss this, my personal favorite, later in this article).

2.      Draft a set of coding standards and best practices for your development team. These should include naming conventions, coding style, places to use global versus local variables, conventions for accessing the Web page's Document Object Model (DOM), rules for defining object constructors, and so on. If you use a library such as JQuery, you will also need to clearly define standards for writing JQuery code.

3.      Mandate that all JavaScript code be cross-browser compliant. As I mentioned, most of the JavaScript libraries are programmed to be so. JQuery does a really good job of this.

4.      Use FireFox to test your Web applications. This is predicated on following point #3 above: making sure your code is cross-browser compliant. What are the reasons for using FireFox? First, FireFox tends to be more strict than IE in rendering Web pages, so if you have any errors in your HTML syntax (besides JavaScript errors), FireFox will usually find them when IE won't. Second, FireFox has FireBug, a fantastic free debugging tool that's available as a plug-in. IE really does not have an equivalent debugger. It has a "developer tool bar" you can install that has limited functionality (such as DOM inspection), but it has no code execution debugging to speak of. You can get a Microsoft JavaScript debugger, but it comes as part of Microsoft Visual Studio, and it ain't cheap. In contrast, the FireBug debugger lets you set breakpoints, display variable values in real time, step through and over code, inspect the DOM, view CSS (external or inline style sheets), modify CSS on the fly to see immediate changes to presentation, track AJAX conversations (what was called, what was returned, etc.), and much more. And did I mention it's free? Third, you probably need to support FireFox users as well as IE users. FireFox also runs well on Apple computers, so you can provide support for Macs in addition to PCs if your application conforms to FireFox requirements.

5.      Provide a structured, formal training process for your developers. This will help them to appreciate the value of JavaScript, to learn to take it seriously as a language, and to be able to read other people's code (including open-source code downloaded from free sites).

6.      Use Change Management software to manage a "source" versus "production" version of the JavaScript code. This will allow your team to write fully commented code while deploying code that omits those comments on the actual Web site. If you use minifying or obfuscating software, you can produce versions of your JavaScript code that are really analogous to compiled object code. These tools remove extra spaces, tabs, lines, etc. from code, along with comments, and substitute very short, meaningless variable names for the original names. The result is that your production files are smaller in size and less easily stolen by potential competitors (there's no real foolproof way to prevent your scripts from being stolen; someone can always reverse-engineer even minimized and obfuscated code). Google uses minimizing and obfuscating algorithms to try to make their code unreadable. For example here's an excerpt from the Google Suggest page:

           

function sf(){document.f.q.focus()}

 

What do sf, f, and q mean? Good question!

Resources to Learn JavaScript

There are lots of books available that purport to teach you JavaScript, but very few cover topics beyond the very basics. I recommend these three books:

 

JavaScript The Definitive Guide, 5th Edition  by David Flanagan, published by O'Reilly, August 2006. This book is the most comprehensive book on JavaScript available. It not only teaches you the formal constructs of the language, but also provides a detailed reference section that explains the W3C Document Object Model (DOM) and functions available in JavaScript for working with it. It also has a section on AJAX, and it covers object-oriented programming in detail. If you can own only one JavaScript book, this is it.

 

Pro JavaScript Techniques by John Resig, published by APress, 2006. John Resig is also the creator of JQuery. This book explains in detail many of the techniques he used in constructing the JQuery library. It covers object-oriented programming in depth, in addition to separating logic from presentation markup, functional programming, and working with the DOM. He also describes a complete solution for creating an autocomplete Web pattern like the one Google uses in GMail and Google Suggest.

 

ppk on JavaScript by Peter-Paul Koch, published by New Riders, 2006. Peter-Paul Koch ("ppk" to his admirers!) has a very popular Web site called Quirksmode that specializes in pointing out cross-browser compliance issues with JavaScript and solutions to those issues. He is a highly regarded authority on cross-browser compliance and "unobtrusive" JavaScript. His site also has a lot of scripts you can copy and paste for free, and he writes good code. This book covers many of the ideas on his Web site and contains eight real-world scripts you can use in your own Web applications.

JQuery: Condensed JavaScript

JQuery is another confusingly named product. It is not a query tool in terms of querying a database and producing results. It is a free, open-source library of JavaScript functions that make it easy to write consistent, efficient, cross-browser JavaScript that takes advantage of JavaScript's strengths, uses CSS efficiently, and has strong support for AJAX. It is licensed under the MIT and GPL licenses, which allow for almost any kind of use, commercial or otherwise. You can download the latest release at the JQuery Web site. To install it, simply copy the JQuery main script file to a place on the IFS of your System i that is mapped to the appropriate URL. Remember that JavaScript is interpreted, not compiled, so you don't need anything but the source file. You can use either the fully documented version of the source or a minified version. I use the fully documented version during development and the minified one for production, as it is considerably smaller in size (only 14K or so) compared to the fully documented file.

 

The official Web site has lots of material that teaches you how to use JQuery. Click on the Documentation link at the top of the home page to get to a page with links to the API reference, which describes all the core JQuery functions, as well as AJAX , DOM traversal and manipulation, and utility functions. There's also lots of example code on these pages.

 

The real power of JQuery lies in 1) its ability to separate content from logic by allowing the developer to safely register multiple event handlers for parts of a Web page and 2) its ability to aggregate DOM elements and act upon them with simple statements. For example, consider the typical "zebra striping" problem with tables. A zebra stripe applies alternating colors to rows in a table of data to make them easier to read. Usually, odd numbered rows are one color while even numbered rows are another color. The typical JavaScript code to accomplish this will loop through all the rows in a table and assign different colors. Here's some well-written, but still lengthy, code from Matthew Pennel's site that does this:   

 

var ZebraTable = {

bgcolor: '',

classname: '',

stripe: function(el) {

if (!$(el)) return;

var rows = $(el).getElementsByTagName('tr');

for (var i=1,len=rows.length;i<len;i++) {

if (i % 2 == 0) rows[i].className = 'alt';

Event.add(rows[i],'mouseover',function() { ZebraTable.mouseover(this); });

Event.add(rows[i],'mouseout',function() { ZebraTable.mouseout(this); });

}

},

mouseover: function(row) {

this.bgcolor = row.style.backgroundColor;

this.classname = row.className;

addClassName(row,'over');

},

mouseout: function(row) {

removeClassName(row,'over');

addClassName(row,this.classname);

row.style.backgroundColor = this.bgcolor;

}

}

 

window.onload = function() {

ZebraTable.stripe('mytable');

}

 

The code creates an object called ZebraTable that has a method (stripe) that finds all the HTML row elements (TR tags). For each even row, it adds the CSS class "alt," which changes the color of that row. It then adds a mouse-over and mouse-out event to each row so that the user gets a visual cue when hovering over a particular row. The object is created, thus applying this functionality to a table with an id of mytable once the page has loaded (the window.onload event is triggered).

 

Now let's see the equivalent JQuery code: 

 

$(document).ready(function(){
   $("#mytable tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
   $("#mytable tr:even").addClass("alt");
});

 

I've taken this code and slightly modified it from this page.

 

This example is very condensed because it takes advantage of JQuery's "chaining" feature, which allows you to apply consecutive methods to a single JQuery object (denoted by the somewhat cryptic $+). You might want to break out the code into one more line for improved readability. Note that all our code runs inside the  $(document).ready()event handler. This event is actually better than the window.onload() event in traditional JavaScript programming because it occurs immediately after the DOM is built, while the latter occurs only once; not only is the DOM built, but also all related external image or CSS files are loaded. Using this syntax, JQuery can make your pages appear to react faster when initially loading or when refreshed. Note also that we did not have to collect all the TR elements in an array and process them with a loop. JQuery's powerful selector syntax does that automatically. In this case,  $("#mytable tr) means "return an array of DOM elements whose HTML tag is tr and that are in the context of (or ancestors of) an HTML element with an id of mytable." The expression  $("#mytable tr:even")  further qualifies our selection to choose only the even rows in that table. Not surprisingly, JQuery also supports $("#mytable tr:odd") to return odd rows. While I referenced an ID in this selector, you can also specify a CSS class ID. For example, consider the selector used in this statement:  

$('.postview').prepend('<img src="expand.gif" border="0" alt="Expand post">');

 

This attaches an image to the front of some HTML in every blog posting (for example) on a page that has a style of postview associated with it, something like this:   

 

<div class="postview">This is the title of a blog posting on Jan 31 2008</div>

<div class="postview">And this is a blog posting on Feb 5 2008</div>  etc.

 

Again, you can see that, with a single line of JQuery code, we can change many elements on our page.

 

This is just a small sample of the power of JQuery. AJAX calls are just as easy and powerful.

 

Another wonderful feature of JQuery is that many high-quality UI plug-ins are available. These are designed to conform to standard JQuery programming syntax, so they are object-oriented and easy to use in your applications. For example, I recently used a data grid plug-in. With eight lines of code, I was able to add column sorting, resizable columns, zebra striping, hover-over, and paging to a customer list. Plus, it looks really professional right out of the box.

Feel the Power

JavaScript is indispensable for creating modern, Web 2.0 applications. It's a richly expressive, powerful language that needs to be taken seriously. With the right training and use of libraries like JQuery, your development team can leverage its benefits for both the short and long term.

Duncan Kenzie
Duncan Kenzie is President and CTO of ExcelSystems Software Development Inc. Duncan’s company is responsible for product development and technical support for BCD International Inc.’s (www.bcdsoftware.com) product line. Duncan has a BA in English Literature from the University of Waterloo, Ontario, and enjoys writing on a variety of subjects. Duncan is a frequent public speaker and has been writing articles about the midrange platform since 1985. He has also been involved in producing programmer productivity and business intelligence tools for 25 years and is the technical lead on products such as WebSmart, WebSmart PHP, and Nexus, leading System i Web tools.  Duncan still enjoys programming, and studies in leadership and self-improvement. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..
BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: