Simply JavaScript

By | | JavaScript

8

Simply JavaScript product shot

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

I’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.

Full color illustrations throughout

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!

The first chapter of the book, The Three Layers of the Web, is currently the feature article on sitepoint.com. The first three chapters of the book are available to download in PDF format for free.

Happy reading! I look forward to hearing what you think in SitePoint’s new book feedback forum.

The Ultimate JavaScript Bundle: 2 books + 1 course

Buy now $39 Normally $117 - save 66%

Or get access to all SitePoint's Premium Content with a Learnable membership

Kevin Yank

Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote Build your own Database Driven Website using PHP and MySQL, a practical step-by-step guide published by SitePoint, and he's co-author of the SitePoint Tech Times, a bi-weekly newsletter for technically-minded web developers. Kev believes that any good webmaster should have seen at least one episode of MacGyver.

More Posts - Website

{ 8 comments }

Petr Antos November 5, 2011 at 5:45 am

Kevin and Cameron,
I know its 4 years ago, but this is exactly why I am here. I like very much your approach to describe DOM scripting in this book, where you are slowly building your Core wrapper around browsers differences to show in fact, whats inside of big profi libraries as jQuery etc.But whats changed in browser compatibility till now in context of your book? Will be fine to see few update pages to whole content, what is simplified today in current browsers. I like to know internals, how things works inside to learn about pertable possibilities – sure I will scan web for this, but your book is so good, that something like “Simply Javascript – 2012 update sheet” will be nice to have :-) …. to be honest, for every IT book as mandatory scenario. Although I understand Sitepoint wants to sell new books too ;-)
Thanks for great work again,
Petr

nateklaiber July 5, 2007 at 1:46 pm

Just received my copy yesterday, halfway finished with it. It is tough to put down. The book, so far, is very well written and the code samples are awesome. You guys did a great job with the book – congrats on getting it out.

spinmaster June 30, 2007 at 9:45 pm

Great job Kev! I ordered already my copy… ;-)

Kevin Yank June 28, 2007 at 10:55 am

Question for ya, Kevin. [...] I’m one of those people who hates working in JS because it’s such an awkward language [...]. Will this book help me become quite fluent in JS, do you think [...]?

Cameron and I thought long and hard about how we would present the JavaScript language in this book. Many other beginner’s JavaScript books present it as a hodge-podge of unrelated features, which leads to that impression of it being “such an awkward language”.

As longtime JavaScript developers, Cameron and I have discovered that JavaScript can be a really beautiful and elegant language if you structure your code properly, so we set out to present the language in a cohesive, structured way that would get beginners writing the kind of code we love to read.

In short, yes, I believe Simply JavaScript will not only give you the fluency with the language that you’re craving, but it will also (we hope) give you new appreciation for how nice a language JavaScript can be.

Adam A Flynn June 28, 2007 at 7:03 am

Thanks for the tip; I’ll be sure to check those videos out!

lubos June 28, 2007 at 4:26 am

Adam, JS is not an awkward language, it’s the world’s most misunderstood programming language. I recommend you to look at Douglas Crockford’s training session videos at Yahoo Video

Adam A Flynn June 28, 2007 at 1:35 am

Question for ya, Kevin. I consider myself to be decent JS programmer (been working with it lightly for years, have enough of an understanding of it that with Google and a good reference guide in hand I can usually piece things together), but I’m one of those people who hates working in JS because it’s such an awkward language when compared to something like PHP (in which I am quite fluent). Will this book help me become quite fluent in JS, do you think, or is it too basic to be of great use to someone who is familiar with the language already?

Sojan80 June 27, 2007 at 11:19 pm

Kevin and Cameron,
Just got my PDF Version this past weekend and am awaiting the arrival of my printed copy any day now. So far so good, and by the way, 2 points for the Dr. Who joke in the intro… and 3 points the Star Trek examples =)

From what I’ve read so far I like the approach the book is taking and the tone isn’t as stodgy (read formal) as some books I’ve read. As of right now, on a scale of 1 to 5 where 5 is excellent I’d give the book a solid 4, but I’ll reserve judgement until after I’ve finished it.

Comments on this entry are closed.

Simply JavaScript: The Three Layers of the Web

By | | JavaScript

2

"Once upon a time, there was … ‘A king!’ my little readers will say right away. No, children, you are wrong. Once upon a time there was a piece of wood …"
The Adventures of Pinocchio

You can do a lot without JavaScript. Using Hypertext Markup Language (HTML — throughout this article, we’ll refer to HTML and XHTML as just HTML. Which you choose is up to you, and doesn’t have a much to do with JavaScript. In case it matters to you, the HTML code we’ll present in this article will be valid XHTML 1.0 Strict), you can produce complex documents that intricately describe the content of a page — and that content’s meaning — to the minutest detail. In this chapter from the new Simply Javascript (you can also download this article, along with two others, as a PDF), I’ll show you that by using Cascading Style Sheets (CSS), you can present that content in myriad ways, with variations as subtle as a single color, as striking as replacing text with an image.

No matter how you dress it up, though, HTML and CSS can only achieve an animatronic monstrosity that wobbles precariously when something moves nearby. It’s when you wheel in the JavaScript that you really can breathe life into your Pinocchio, lifting you as its creator from humble shop clerk to web design mastery!

But whether your new creation has the graceful stride of a runway model, or the shuffling gait of Dr. Frankenstein’s monster, depends as much on the quality of its HTML and CSS origins as it does on the JavaScript code that brought it to life.

Before we learn to work miracles, therefore, let’s take a little time to review how to build web sites that look good both inside and out, and see how JavaScript fits into the picture.

Keep ‘em Separated

Not so long ago, professional web designers would gleefully pile HTML, CSS, and JavaScript code into a single file, name it index.html (or default.htm, if they had been brainwashed by Microsoft), and call it a web page. I’ve conceptualized this as something like Figure 1. You can still do this today, but be prepared for your peers to call it something rather less polite.

Figure 1. A single-file mess

Somewhere along the way, web designers realized that the code they write when putting together a web page does three fundamental things:

  • It describes the content of the page.
  • It specifies the presentation of that content.
  • It controls the behavior of that content.

They also realized that keeping these three types of code separate, as depicted in Figure 2, “Separation of concerns," made their jobs easier, and helped them to make web pages that work better under adverse conditions, such as when users have JavaScript disabled in their browsers.

Computer geeks have known about this for years, and have even given this principle a geeky name: the separation of concerns.

Figure 2. The separation of concerns

Now, realizing this is one thing, but actually doing it is another — especially if you’re not a computer geek. I am a computer geek, and I’m tempted to do the wrong thing all the time.

I’ll be happily editing the HTML code that describes a web page’s content, when suddenly I’ll find myself thinking how nice that text would look if it were in a slightly different shade of gray, if it were nudged a little to the left, and if it had that hee-larious photocopy of my face I made at the last SitePoint office party in the background. Prone to distraction as I am, I want to make those changes right away. Now which is easier: opening up a separate CSS file to modify the page’s style sheet, or just typing those style properties into the HTML code I’m already editing?

Like behaving yourself at work functions, keeping the types of code you write separate from one another takes discipline. But once you understand the benefits, you too will be able to summon the willpower it takes to stay on the straight and narrow.

Three Layers

Keeping different kinds of code as separate as possible is a good idea in any kind of programming. It makes it easier to reuse portions of that code in future projects, it reduces the amount of duplicate code you end up writing, and it makes it easier to find and fix problems months and years later.

When it comes to the Web, there’s one more reason to keep your code separate: it lets you cater for the many different ways in which people access web pages.

Depending on your audience, the majority of your visitors may use well-appointed desktop browsers with cutting-edge CSS and JavaScript support, but many might be subject to corporate IT policies that force them to use older browsers, or to browse with certain features (like JavaScript) disabled.

Visually impaired users often browse using screen reader or screen magnifier software, and for these users your slick visual design can be more of a hindrance than a help.

Some users won’t even visit your site, preferring to read content feeds in RSS or similar formats if you offer them. When it comes time to build these feeds, you’ll want to be able to send your HTML content to these users without any JavaScript or CSS junk.

The key to accommodating the broadest possible range of visitors to your site is to think of the Web in terms of three layers, which conveniently correspond to the three kinds of code I mentioned earlier. These layers are illustrated in Figure 3, “The three layers of the Web."

Figure 3. The three layers of the Web

When building a site, we work through these layers from the bottom up:

  1. We start by producing the content in HTML format. This is the base layer, which any visitor using any kind of browser should be able to view.
  2. With that done, we can focus on making the site look better, by adding a layer of presentation information using CSS. The site will now look good to users able to display CSS styles.
  3. Lastly, we can use JavaScript to introduce an added layer of interactivity and dynamic behavior, which will make the site easier to use in browsers equipped with JavaScript.

If we keep the HTML, CSS, and JavaScript code separate, we’ll find it much easier to make sure that the content layer remains readable in browsing environments where the presentation and/or behavior layers are unable to operate. This “start at the bottom" approach to web design is known in the trade as progressive enhancement.

Let’s look at each of these layers in isolation to see how we can best maintain this separation of code.

HTML for Content

Everything that’s needed to read and understand the content of a web page belongs in the HTML code for that page — nothing more, nothing less. It’s that simple. Web designers get into trouble when they forget the K.I.S.S. principle (Keep It Simple, Stupid) and cram non-content information into their HTML code, or alternatively move some of the page’s content into the CSS or JavaScript code for the page.

A common example of non-content information that’s crammed into pages is presentational HTML — HTML code that describes how the content should look when it’s displayed in the browser. This can include old-fashioned HTML tags like <b>, <i>, <u>, <tt>, and <font>:

<p>Whatever you do, <a href="666.html"><font color="red">don't
click this link</font></a>!</p>

It can take the form of inline CSS applied with the style attribute:

<p>Whatever you do, <a href="666.html" style="color: red;">don't
click this link</a>!</p>

It can also include the secret shame of many well-intentioned web designers: CSS styles applied with presentational class names:

<p>Whatever you do, <a href="666.html" class="red">don't click
this link</a>!</p>

Presentational Class Names? If that last example looks okay to you, you’re not alone, but it’s definitely bad mojo. If you later decide you want that link to be yellow, you’re either stuck updating both the class name and the CSS styles that apply to it, or living with the embarrassment of a class named “red" that is actually styled yellow. That’ll turn your face yellow — er, red!

Rather than embedding presentation information in your HTML code, you should focus on the reason for the action — for example, you want a link to be displayed in a different color. Is the link especially important? Consider surrounding it with a tag that describes the emphasis you want to give it:

<p>Whatever you do, <em><a href="evil.html">don't click this
link</a></em>!</p>

Is the link a warning? HTML doesn’t have a tag to describe a warning, but you could choose a CSS class name that conveys this information:

<p>Whatever you do, <a href="evil.html" class="warning">don't
click this link</a>!</p>

You can take this approach too far, of course. Some designers mistake tags like <h1> as presentational, and attempt to remove this presentational code from their HTML:

<p class="heading">A heading with an identity crisis</p>

Really, the presentational information that you should keep out of your document is the font, size, and color in which a heading is to be displayed. The fact that a piece of text is a heading is part of the content, and as such should be reflected in the HTML code. So this code is perfectly fine:

<h1>A heading at peace with itself</h1>

In short, your HTML should do everything it can to convey the meaning, or semantics of the content in the page, while steering clear of describing how it should look. Web standards geeks call HTML code that does this semantic markup.

Writing semantic markup allows your HTML files to stand on their own as meaningful documents. People who, for whatever reason, cannot read these documents by viewing them in a typical desktop web browser will be better able to make sense of them this way. Visually impaired users, for example, will be able to use assistive software like screen readers to listen to the page as it’s read aloud, and the more clearly your HTML code describes the content’s meaning, the more sense tools like these will be able to make of it.

Best of all, however, semantic markup lets you apply new styles (presentation) and interactive features (behavior) without having to make many (or, in some cases, any!) changes to your HTML code.

CSS for Presentation

Obviously, if the content of a page should be entirely contained within its HTML code, its style — or presentation — should be fully described in the CSS code that’s applied to the page.

With all the work you’ve done to keep your HTML free of presentational code and rich with semantics, it would be a shame to mess up that file by filling it with snippets of CSS.

As you probably know, CSS styles can be applied to your pages in three ways:

inline styles:
<a href="evil.html" style="color: red;">
Inline styles are tempting for the reasons I explained earlier: you can apply styles to your content as you create it, without having to switch gears and edit a separate style sheet. But as we saw in the previous section, you’ll want to avoid inline styles like the plague if you want to keep your HTML code meaningful to those who cannot see the styles.

embedded styles:
<style type="text/css">
.warning {
color: red;
}

</style>
&#8942;
<a href="evil.html" class="warning">

Embedded styles keep your markup clean, but tie your styles to a single document. In most cases, you’ll want to share your styles across multiple pages on your site, so it’s best to steer clear of this approach as well.

external styles:
<link rel="stylesheet" href="styles.css" />
&#8942;
<a href="evil.html" class="warning">
Example 1.1. styles.css

.warning {
color: red;
}

External styles are really the way to go, because they let you share your styles between multiple documents, they reduce the amount of code browsers need to download, and they also let you modify the look of your site without having to get your hands dirty editing HTML.

But you knew all that, right? We're dealing with a JavaScript book, after all, so let's talk about the JavaScript that goes into your pages.

JavaScript for Behavior

As with CSS, you can add JavaScript to your web pages in a number of ways.

You can embed JavaScript code directly in your HTML content:
<a href="evil.html" onclick="JavaScript code here">

You can include JavaScript code at the top of your HTML document in a <script> tag:
<script type="text/javascript"><!--//--><![CDATA[//><!--
JavaScript code here
//--><!]]></script>
&#8942;
<a href="evil.html" class="warning">

CDATA? If you're wondering what all that gobbledygook is following the <script> tag and preceding the </script> tag, that's what it takes to legitimately embed JavaScript in an XHTML document without confusing web browsers that don't understand XHTML (like Internet Explorer).

If you write your page with HTML instead of XHTML, you can get away with this much simpler syntax:
<script type="text/javascript">
JavaScript code here
</script>

You can put your JavaScript code in a separate file, then link to that file from as many HTML documents as you like:
<script type="text/javascript" src="script.js"></script>
&#8942;
<a href="evil.html" class="warning">
Example 1.2. script.js (excerpt)
JavaScript code here

Guess which method you should use.

Writing JavaScript that enhances usability without cluttering up the HTML document(s) it is applied to, without locking out users that have JavaScript disabled in their browsers, and without interfering with other JavaScript code that might be applied to the same page, is called unobtrusive scripting.

Unfortunately, while many professional web developers have clued in to the benefits of keeping their CSS code in separate files, there is still a lot of JavaScript code mixed into HTML out there. By showing you the right way to use JavaScript, we hope to help change that.

The Right Way

So, how much does all this stuff really matter? After all, people have been building web sites with HTML, CSS, and JavaScript mixed together for years, and for the majority of people browsing the Web, those sites have worked.

Well, as you come to learn JavaScript, it's arguably more important to get it right than ever before. JavaScript is by far the most powerful of the three languages that you'll use to design web sites, and as such it gives you unprecedented freedom to completely mess things up.

As an example, if you really, really like JavaScript, you could go so far as to put everything -- content, presentation, and behavior -- into your JavaScript code. I've actually seen this done, and it's not pretty -- especially when a browser with JavaScript disabled comes along.

Even more telling is the fact that JavaScript is the only one of these three languages that has the ability to hang the browser, making it unresponsive to the user.

Therefore, we'll do our darnedest to show you the right way to use JavaScript, not just because it keeps your code tidy, but because it helps to keep the Web working the way it's meant to -- by making content accessible to as many people as possible, no matter which web browser they choose to use.

JavaScript Libraries

As I mentioned, one of the benefits of keeping different kinds of code separate is that it makes it easier to take code that you've written for one site and reuse it on another. Certain JavaScript maniacs (to be referred to from this point on as "people") have taken the time to assemble vast libraries of useful, unobtrusive JavaScript code that you can download and use on your own web sites for free.

Throughout Simply Javascript, we build each of the examples from scratch -- all of the JavaScript code you need can be found right there. Since there isn't always time to do this in the real world, however, and because libraries are quickly becoming an important part of the JavaScript landscape, we'll also look at how the popular JavaScript libraries do things whenever the opportunity presents itself.

Here are the libraries that we use in the book:

Not All Libraries are Created Equal Watch out for sites offering snippets of JavaScript code for you to copy and paste into your web pages to achieve a particular effect. There is a lot of free code out there, but not all of it is good. In general, the good libraries come in the form of JavaScript (.js) files that you can link into your pages unobtrusively, instead of pasting JavaScript directly into your HTML code. If you don't feel confident to judge whether a particular JavaScript library is good or bad, ask for some advice in the SitePoint Forums, or just stick with the libraries I just mentioned -- they're all very good.

Let's Get Started!

Enough preaching -- you checked out this article to learn JavaScript, right? Clean HTML and CSS are nice and all, but it's time to take the plunge into the third layer of the Web: behavior. The chapters of Simply Javascript that follow the one from which this article is reproduced deal in greater depth with this topic -- and because we're feeling generous, we've decided to throw them in for your delectation! So don't forget to download this chapter as a PDF, as well as Chapter 2: Programming with JavaScript and Chapter 3: Document Access.

In Chapter 2, you'll learn that as JavaScript is a programming language, you must get your head around the way computer programs work -- which to some extent means learning to think like a computer -- in order to use it most effectively. The simple concepts introduced in this chapter -- statements, variables, expressions, loops, functions, and objects -- are the building blocks for every JavaScript program you'll ever write.

And Chapter 3? While certain people enjoy writing JavaScript code for its own sake, you wouldn't want to run into them in a dark alley at night. As a well-adjusted web developer, you'll probably want to use JavaScript to make changes to the contents of your web pages using the Document Object Model (DOM). Lucky for you, we wrote a whole chapter to show you how!

Then, of course, there's more...

Get ready to start using some cool (and unobtrusive) JavaScript!

The Ultimate JavaScript Bundle: 2 books + 1 course

Buy now $39 Normally $117 - save 66%

Or get access to all SitePoint's Premium Content with a Learnable membership

Kevin Yank

Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote Build your own Database Driven Website using PHP and MySQL, a practical step-by-step guide published by SitePoint, and he's co-author of the SitePoint Tech Times, a bi-weekly newsletter for technically-minded web developers. Kev believes that any good webmaster should have seen at least one episode of MacGyver.

More Posts - Website

{ 2 comments }

Gene Goodreau September 28, 2011 at 7:04 am

Call me crazy but I assumed from scratch meant that I would be learning from scratch… not: ~from scratch but with a helper file called core.js that you won’t understand cause it contains voodoo code but you have to use it cause most of the example functions use it~ kind of approach. I feel like I wasted my money. What if I don’t happen to want to type in or use this five page core.js helper file and would rather learn “javascript from scratch”? Seems I need to buy another book… I feel like I was deceived.

Disclaimer: The book does appear to be pretty good if you don’t care about using a helper file you don’t understand. That just seems at odds with the title of the book to me.

Kevin Yank September 28, 2011 at 7:10 pm

Hi Gene,

For what it’s worth, the contents of Core.js are fully explained at the end of the book, once you have learned everything you need to understand it.

We chose to rely on Core.js to enable you to get into building interesting things with JavaScript sooner, rather than make you slog through a lot of boring and confusing language features at the start of the book.

By the end of the book, you should know everything you need to build Core.js from scratch yourself, or do without it entirely if you really want to.

Comments on this entry are closed.