http://sitepointstatic.comhttp://sitepointstatic.com SitePoint Tech Times
SitePoint Tech
TimesJune 22nd, 2007 
Issue 167 

Newsletter Archives | Advertising | Contact us  
Tips, Tricks, News and Reviews for Web Coders

In This Issue...

Introduction

by Kevin YankIt's aliiiiiiiiiive! The first copies of Simply JavaScript—SitePoint's latest book, co-written by me and Cameron Adams—have arrived! And if you'll forgive my obvious bias, it looks awesome.

Simply JavaScript
product shotI'm so proud of what Cameron and I have achieved with this book. We knew from the beginning that it wasn't worthwhile writing another beginner's JavaScript book unless we could produce something really special, and we definitely have.

Simply JavaScript teaches the technology with unprecedented clarity, featuring loads of color illustrations and advice on how to use JavaScript the right way in the real world.

It's also a surprisingly entertaining read, although I'll admit our sense of humor is a little odd at times. On one occasion, we had to fight to keep a joke in when the proofreader had crossed it out with the note "not funny" in the margin. All the same, I daresay it's the funniest book SitePoint has published to date, which is saying a lot!

I'm especially excited to share this news with you, the readers of the SitePoint Tech Times, because you helped to make it possible. Here's what I had to say about you in my acknowledgments at the front of the book:

"And to the more than 150,000 readers of the SitePoint Tech Times newsletter, with whom I shared many of the ideas that made their way into this book, and who provided valuable and challenging feedback in return, my gratitude."

For this reason, I'm pleased to offer the faithful readers of this newsletter a $10 discount on the book. Just click here to order and benefit from this exclusive deal.

Top


JavaScript: How Simple Is Too Simple?

When we first sat down to write Simply JavaScript, Cameron and I had to decide how complicated we wanted to make things. On the one hand, this was to be a beginner's book, so we wanted to keep things simple (it is called "Simply JavaScript", after all).

On the other hand, JavaScript isn't all that simple in the real world, and we felt too many other books were guilty of not giving their readers the tools they needed to understand and write real-world code. We didn't want to make the same mistake of "dumbing down" the language to produce an easy-to-read book.

To show you what I mean, let's throw together the same JavaScript example using code at several levels of complexity. The example will be a simple one: we'll prompt the user to ask whether links to external sites should be opened in a new window. As we'll see, however, even a simple example like this can get very complicated if you let it!

If code simplicity were the ultimate goal, this example could be very simple indeed:

<a href="http://example.com/" onclick="
    if (confirm('Open this link in a new window?')) {
      open('http://example.com/');
      return false;
    }
">external link</a>

Let's pause briefly while all the JavaScript veterans in the audience gouge their eyes out.

While this code will certainly work, and would be exceedingly easy to explain in a beginner's JavaScript book, it's a very messy solution to the problem. The code is sitting in the middle of the HTML content, and will have to be repeated for every link of this type on the page. Additionally, the URL of the link is repeated in the JavaScript code, which runs the risk of the two getting out of sync.

After the ad, we'll see some better ways to do this...

Top


Greener is ... tapping into the leading network of global advertisers.
Greener is ... partnering with the world's top advertisers.
Greener is ... accessing worldwide advertiser links and offers.
The grass is greener with Commission Junction.

Commission Junction is the global leader in affiliate marketing, driving quality results, delivering superior service, and developing sustainable relationships for advertisers and publishers through our performance-based solutions.

Publishers join now! Visit cj.com to learn more.

Top


The code snippet we saw above would have been considered cutting-edge sometime around 1997. Let's see a more modern alternative that still attempts to keep things simple:

<a href="http://example.com/" class="ext">external link</a>
<script type="text/javascript">
  var links = document.getElementsByTagName("a");
  for (var i = 0; i < links.length; i++) {
    var link = links[i];
    if (link.className == "ext") {
      link.onclick = clickHandler;
    }
  }

  function clickHandler() {
    if (confirm("Open this link in a new window?")) {
      open(this.href);
      return false;
    }
  }
</script>

Rather than adding JavaScript code directly to every external link in the document, this version uses a single chunk of JavaScript code that detects all of the external links in the document (those with class="ext") and assigns the same JavaScript function (clickHandler) to handle the click event for each. This function can be shared between all the external links, because it uses this.href to fetch the URL to be opened from the link that has been clicked.

Many JavaScript books released in the past few years are content with the improvements that we made in this version of the script. The code is tidy enough, and it behaves as advertised. What more could a beginner ask for?

The problem with this thinking is that beginners who learn from examples like these go out into the wilds of the Web and find examples written using much more advanced JavaScript coding structures, and feel lost.

The main differences between the script we've just seen and the sort of code that web professionals are producing in the real world can be summed up in two words: unobtrusive scripting.

Unobtrusive scripting is the name given to a range of techniques that developers use to bundle up their JavaScript code so that it will not interfere with other scripts that may be in play on the same page. The script we have just seen, for example, would interfere with any other script that defined a function named clickHandler, or that registered a click event handler on the links of the page.

Because JavaScript is such a flexible language, there are many tricky ways to achieve unobtrusive scripting. Some popular methods add greatly to the complexity of writing even simple scripts, with references to variables and functions changing dramatically depending on where in the code they occur.

The challenge, when you're writing a book like Simply JavaScript, is to show beginners how to write unobtrusive scripts without making the code too difficult for the novice programmer to grasp. Here's what we came up with:

var ExternalLinks = {

  init: function() {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
      var link = links[i];
      if (link.className == "ext") {
        Core.addEventListener(
          link, "click", ExternalLinks.clickHandler);
      }
    }
  },

  clickHandler: function(event) {
    if (confirm("Open this link in a new window?")) {
      open(this.href);
      Core.preventDefault(event);
    }
  }

};

Core.start(ExternalLinks);

The entire script is bundled up inside a JavaScript object called ExternalLinks, which is the only element of the script that could possibly clash with another script, and is consequently chosen to be rather unique. The script is made up of a collection of functions, which are defined as methods of this object.

This structure enables these functions to be called by the same name (e.g. ExternalLinks.clickHandler) wherever they may occur in your code.

Once the script is defined, the whole thing is kicked off by a call to its init method, which is triggered by the final line of the above code, Core.start(ExternalLinks);.

The problem of clashing event handlers is solved by the Core library of functions (Core.start, Core.addEventListener, Core.preventDefault, etc.), the inner workings of which are explained at appropriate points in the book.

While this approach lacks a few of the features of more sophisticated alternatives, it's simple enough that beginners can grasp it and feel confident writing their own scripts following the same pattern. It also exposes them to more advanced language features like objects, so when the time comes that they need to adopt one of the more advanced coding styles, they stand a good chance of understanding the sample code they will find online.

By using this coding structure from the very first page, Simply JavaScript avoids teaching beginners bad habits. You also don't get that awkward chapter that occurs around page 100 of several other recent JavaScript titles, where the author explains that the style of code presented up to that point in the book is flawed, and should be avoided.

Top


If a lot of the intricacies of JavaScript syntax discussed in this issue went over your head, I apologize. I do hope, however, that you'll consider picking up a copy of Simply JavaScript so that you can learn what you've been missing!

For those of you that know your JavaScript, I'd love to hear your thoughts on the approach to the language we took. That, along with coverage of the major JavaScript libraries and our wacky sense of humor, is what makes this book so unique.

Kevin Yank
techtimes@sitepoint.com
Editor, The SitePoint Tech Times

Top


Help Your Friends Out

People you care about can benefit from the wealth of information on new and maturing technologies available on the Internet. Help them learn how to do it by forwarding them this issue of the SitePoint Tech Times!

Send this to a friend
 New Technical Articles

Fancy Form Design Using CSS

Cameron
Adams
By Cameron Adams

Form design is the necessary evil of web development. Don't you wish you had a wizard's wand to create accessible yet attractive forms? We have found such a wizard! Here, Cameron Adams shows you how to use CSS to create forms that are both great-looking and usable, and gives you the code you need to make the job easy.

 Techy Forum Threads
 More Techy Blog Entries

Design Blog:
Pixel Perfect

Web Tech Blog:
Technically Speaking

Usability Blog:
Usability 2.0

Daily Links Blog:
SitePoint News Wire

Manage Your Subscription Here.

!You are currently subscribed as to the HTML edition of the Tech Times.


CHANGE your email address here

UNSUBSCRIBE from the Tech Times here.

SUBSCRIBE to the Tech Times here.

SWAP to the 'Text-Only' version of the Tech Times here.


SitePoint Pty. Ltd.
424 Smith St
Collingwood, VIC 3066
AUSTRALIA


Thanks for reading!

 © SitePoint 1998-2007. All Rights Reserved.

Back to the archives

Newsletter signup

Design, coding, community or marketing? Select the right newsletters right for your needs...