Not your usual article - this was actually written as a research paper for school but I thought the subject matter would interest some of my readers :) I’m no pro at JavaScript though - this is just me wetting my feet, so feel free to correct me if I’m wrong, or add any ideas
JavaScript is a web scripting language, often used to add effects and functionality to websites (Keith 5). It is a very important part of interface and interactive design, as it deals directly with user inputs and actions like clicking, mouseovers and dragging. It can also be used by designers for functions like setting font sizes or special effects like fading in or sliding around. JavaScript used to be an unwieldy language, full of quirks and incompatibilities. Over the years, it has been standardized and now there are a myriad of possibilities to be explored. JavaScript was originally created by Netscape and Sun Microsystems in 1995, and has absolutely nothing to do with the similarly named programming language Java. In response to Netscape’s new language, Microsoft released its own languages called VBScript and Jscript. After many attempts to standardize and improve the languages, in 1996 JavaScript and the Document Object Model (DOM) was created. The DOM is a standardized set of conventions – a webpage equivalent of Morse code or the periodic table – and is used by different parts of a document, the styles, scripts, etc., to interact with each other with descriptions such as “the third paragraph” or “any pictures in this box”. Though it sounds simple, there were many issues in the early days of JavaScript and the DOM, and until around 1998 compatibility between different browsers was a nightmare. In 1998, the World Wide Web Consortium (W3C) drafted the DOM Level 1 and JavaScript was on its way to becoming a great language. Over time, groups like the Web Standards Project (WaSP) have helped create an internet that is standardized and has great support. Now, “as long as we follow the DOM standards, we can be sure that our scripts will work almost universally” (Keith 9). JavaScript – especially as a library like jQuery – can greatly enhance the design and usability of a webpage, and is a great tool for any web developer.
JavaScript has many applications and limitless potential. It is very powerful, “but with great power comes great responsibility” (Spiderman 1). Used properly, it can greatly improve a site; many sites rely on JavaScript for great effects and unique features. However, used irresponsibly or improperly, it can become a nuisance and a failure; everyone hates popups or sites that don’t always work properly. There are three critical guidelines that JavaScript developers should adhere to: progressive enhancements, unobtrusive scripting and consistent structure. Combined with common sense, they should help create great code and prevent fundamental architectural problems. First and foremost, functionality should be added using progressive enhancements. The principle behind this is that functionality should be added on to the basic content. This results in pages that will gracefully degrade, or work adequately even if JavaScript is disabled. Badly written programs that don’t follow this would be totally unusable if the user didn’t have JavaScript enabled (Keith 82). Considering that many users don’t have JavaScript enabled, or, in the case of mobile devices, older browsers and search engine spiders, have JavaScript capabilities at all, a lack of progressive enhancements and graceful degradation can be problematic indeed. Some real world examples of this are using popup windows or functions embedded in hyperlinks, which rely on JavaScript and result in inaccessible content without it (Edwards 7).
Another important principle is unobtrusive scripting, or behavioral separation, which basically means that the main content (the actual text paragraphs, images, etc.), marked up by XHTML should be separate from the CSS (Cascading StyleSheets – with colors, layout, fonts, etc.) and the behavior (found in JavaScript files.) Not only is this far more efficient, but it leads to easier maintenance and makes it much easier to modify things (Keith 87). Inline event handlers, when the JavaScript is mixed into the actual XHTML content, should be avoided at all costs. Instead, the code should be called using the basic DOM actions such as onclick, onmouseover, etc. from a JavaScript function in a separate JavaScript file (Keith “Behavioral Separation” 2). This same principle applies to Cascading Stylesheets (CSS) and the styling of documents using modern web standards (Edwards 10).
The third guideline for coding JavaScript, and one that applies for nearly any programming language, is the use of common conventions and a consistent style. Though often optional, semicolons and braces should be used wherever possible. Spacing and line breaks should also be used in order to create code that is more readable. This is especially important when working on a team, where developers will need to share and collaborate on code. The following two snippets of code are both valid:
if (something) alert(‘something’)
else alert(‘nothing)
and
if (something) {
alert(‘something’);
}
else {
alert(‘nothing’);
}
However, the latter is much more understandable, and is less prone to break if the structure is changed (Edwards 12). Another common convention is toUse “camelCase” for functionNames, where capital letters are used afterTheFirstWord. Underscores should_be_used for variable_names (Keith 35). Other great suggestions are to write many // comments as notes in the code, if not a whole documentation. Choosing good function and variable names is also crucial. Variables like ‘navigation’ and ‘main_content’ are much more useful and descriptive than ‘thing’ and ‘box’ (Heilmann 2).
Many of the best websites use JavaScript to add functionality, accessibility and enhance design. JavaScript has been a key ingredient in the recent “Web 2.0” movement. Within the last few years, many new sites and web applications have made use of a revolutionary combination of JavaScript and XML – known as AJAX, which stands for Asynchronous JavaScript and XML (not to be confused with the sink cleaner).
AJAX makes it possible to submit and obtain information to a website without having to reload the page. This allows for a myriad of possibilities and functions that previous generations of web developers could only dream of, such as spell-checking, auto-suggestion, on-the-fly searching, logging in without reloading, etc. Some famous and very successful websites that depend on AJAX for their functionality and livelihood are Flickr.com (a very successful social gallery), A9.com (Amazon’s search engine) and of course, Google. “Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year — Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps — are Ajax applications” (Garrett 4). AJAX is now an essential ingredient in any major website, adding a layer of features and richness that transform it from a mere page of text to an actual usable application.
Typography is a key aspect of web design, and JavaScript is often used in setting optimal font sizes and advanced typographical enhancements. All over the web, one can see controls to make a site larger or smaller. These operate using a combination of JavaScript and cookies (small files that stores a setting) – yummy. It is possible to use JavaScript to automatically set font sizes and line widths, or modify a layout as fonts are resized. A great example of using JavaScript to enhance typography is jQWidon’t, a simple plugin that repairs widow – when the last word falls into a line of it’s own (Cardwell 1). It is impossible to accomplish such things without using JavaScript.
Using JavaScript, one can write functions that can practically do anything imaginable; creating bulletproof and highly optimized site layouts becomes easy and practical (Carvalho 5). It is even possible to have different styles and settings based on how wide the browser, using a different layout for small screens, is or what type of device is being used, such as a cellphone or a computer (Adams 1).
The power of JavaScript isn’t reserved for boring things like text. It can also be used for many exciting effects that were previously reserved only for flash experts. It can be used for many special effects and motion graphics such as fading, sliding, motion and dragging. It can also be used in conjunction with Flash. For example, SiFR, a freely available script, uses a combination of JavaScript and Flash to create headings with embedded fonts and smooth anti-aliasing.
JavaScript, like coffee, comes in many flavors and sizes. First, there is the pure stuff, the real deal – DOM scripting – like coffee without any fancy caramel or sugar. Then there are also JavaScript libraries, freely available, created by individuals and organizations, which take the basic DOM functions and create something more feature-rich and easy to use – much like blended coffee with all kinds of sprinkles and whipped cream.
Though both plain DOM scripting and using pre-made libraries are valid and proper, libraries like jQuery, Yahoo!UI, Prototype or Scriptaculous are ideal for beginner programmers or designers. Many JavaScript libraries are great because they kill two birds with one stone. First, they eliminate many cross browser compatibility issues (“Ajax/DHTML Scorecard” 7). They also make it much easier to create scripts, adding commonly used functions and effects. Some are more featured and robust than others, but most have many special effects and basic functions that make it especially easy for non-programmers to delve into the language with a very low barrier of entry. Admittedly, pure DOM Scripting will be marginally faster and more efficient than using a whole library full of functions that may or may not be used. The difference is similar to that between a compiled or machine level language; often the slight improvement in performance is not worth the extra time and effort.
There are, however, hundreds of different JavaScript libraries available, so choosing one can be a tough decision. Each will have its own diehard fans and benefits. The following snippets of code demonstrate creating alternating rows in a table – a very commonly used function.
Plain DOM Scripting:
var tables = document.getElementsByTagName("table");
for ( var t = 0; t < tables.length; t++ ) {
var rows = tables[t].getElementsByTagName("tr");
for ( var i = 1; i < rows.length; i += 2 )
if ( !/(^|s)odd(s|$)/.test( rows[i].className ) )
rows[i].className += " odd";
}
Yahoo UI:
var tables = document.getElementsByTagName("table");
for ( var t = 0; t < tables.length; t++ ) {
var rows = tables[t].getElementsByTagName("tr");
for ( var i = 1; i < rows.length; i += 2 )
YAHOO.util.Dom.addClass( rows[i], "odd" );
}
Prototype:
$A(document.getElementsByTagName("table")).each(function(table){
$A(table.getElementsByTagName("tr")).each(function(row,i){
if ( i % 2 == 1 )
Element.addClassName( row, "odd" );
});
});
jQuery:
$("tr:nth-child(odd)").addClass("odd"); (Resig 1).
Based on this example, it is apparent that jQuery is one of the more elegant and simple solutions. One of the reasons that jQuery is so powerful is that it includes many cutting edge features like CSS2, CSS3 and XPath selectors, which basically make it easier to target and work with elements. jQuery’s intuitiveness and robust functions make it an ideal choice for beginners or anyone interested in producing quality scripts without worrying too much about technical aspects (Batchelder 1).
A basic knowledge of JavaScript is essential in today’s web world. Using JavaScript, anyone from programmers to designers can enhance their work and create feature-rich and impressive websites.
Works Cited
Adams, Cameron. “Resolution Dependent Layout.” The Man In Blue. 21 Sep 2004.
5 Dec 2006.
“AJAX/DHTML Library Scorecard.” Musings from Mars. 4 March 2006. 23 Jan 2007.
Batchelder, Matthew. “jQuery Toolkit.” Borkweb. 1 November 2006.14 January 2007.
Cardwell, Dave. “jQWidon’t – Suppress Typographic Widows.” 26 August 2006.
13 January 2007.
Carvalho, Lawrence. “Text Resize Detection.” A List Apart. 12 Sep 2006. 5 Dec 2006.
Edwards, James. The JavaScript Anthology: 101 Essential Tips, Tricks & Hacks.
Australia: Sitepoint, 2006.
Garrett, Jesse. “Ajax: A New Approach to Web Applications.” Adaptive Path.
18 Feb 2005. 03 Jan 2007
Heilmann, Christian. “The importance of maintainable JavaScript.” Think Vitamin.
17 July 2006. 1 Dec 2006.
Keith, Jeremy. “Behavioral Separation.” A List Apart. 20 Jun 2006. 1 Dec 2006.
Keith, Jeremy. Dom Scripting: Web design with Javascript and the Document Object
Model. New York: Friends of Ed, 2006.
Resig, John. “Zebra Table Showdown.” jQuery. 18 October 2006. 11 January 2007.
Comments
This place isn't ALL about me — just mostly.
Ash Haque
1 year, 5 months ago
Good article, may require some formatting for readability (spacing between paragraphs, code separation).
Anyways, I’m doing a lot of C++ coding for university right now, and I definitely agree with you about the already made libraries making everything easier (especially if you’re just starting off).
abdul
1 year, 5 months ago
Could use alot of paragraph and sentence structure to this article, right now it makes people not want to read it because it looks so long, add some spaces bro.
Other than that, overall good article.
Cheers,
Mark
1 year, 3 months ago
Thank You
Those were all the comments. But don't be shy — Add your own!