5 Reasons Why You Need To Learn To Use JavaScript Before jQuery

TOPIC: Coding Best Practices /////Be The First To Comment
 

A project came up at work involving Node, the software system that allows JavaScript to run server-side instead of client-side. I wasn’t involved in the project but wanted to play with the code once it landed in production and wanted to be ready if ever asked to support it. So I set Node up on my Mac laptop, read parts of its documentation and found some beginning Node learning resources online.

Server-side code is definitely not my thing so Node has always made me nervous. I can talk about how it works in the abstract, but actually using it has intimidated me. I delayed learning Node until the last minute.

But as I started playing with Node, something funny happened: understanding it turned out to be easy!

I’m not saying that it was so easy that I’m now a Node guru. I had to grasp Node’s event loop, its handling of server modules and gain a basic understanding of the how servers work in general. And I still have more to learn.

But in terms of the JavaScript needed to run Node, I picked it up in about two days. Knowing some basic JS things, that functions are first class objects, that these functions can be passed, that callbacks are powerful; knowing all that made my Node learning process much easier than expected.

I suppose the point is, I don’t know all the answers to Node (and still don’t), but thanks to my JavaScript knowledge, I understand all the questions.

None of this would have happened had I not made a conscious decision a year-and-a-half ago to focus on getting better at JavaScript instead of mastering jQuery. I’m may not be a JavaScript ninja but I’m comfortable putting it on my resume, something I was unsure about 18 months ago.

I need to be clear about something before I go on: I AM NOT BAD-MOUTHING JQUERY!!!! jQuery is awesome! I think you should use it and don’t see myself doing any future web projects without it.

jQuery effectively deals with a lot of cross-browser JavaScript issues, making overall web development an easier process. Its power as a DOM selection engine is so strong, that it doesn’t make sense to not use it. Furthermore, jQuery lets developers write quality JavaScript faster, so a case can be made that a developer using jQuery is, at times, more productive than one that doesn’t. Also, key JavaScript things like adding data to objects and function parameters are what’s needed to make jQuery work, meaning you can pick up some key JS skills by writing JQ. And a web designer with no coding experience whose main job is to work in PhotoShop eight hours a day shouldn’t be faulted for using jQuery to whip out a quick effect. At least I don’t think so.

While learning jQuery has lots of positives, the focus of your learning should mostly be on JavaScript: doing so makes you a better developer.

Here’s the list:

1. Because understanding JavaScript makes it easier to understand all the JavaScript-related stuff

Already implied in this post but it bears a deeper examination. Let’s look at this list:

What You Know After Learning Just jQuery

And in terms of jQuery UI and jQuery Mobile, I’m being nice here. While you can apply raw JavaScript and jQuery to your UI and Mobile projects, setting UI and Mobile up is mostly done by adding attributes, IDs and classes to HTML elements. Things are made easy, an excellent goal that the jQuery team has achieved above and beyond all expectations.

Now, let’s look at this list:

What You Know After Learning JavaScript Before jQuery

…you get the idea.

While some of these things are so well-documented that a six-year old can use them, most of them are documented in a way that assumes the reader has pre-existing JavaScript knowledge. Many of these things assume you understand that a main object is loaded into the global namespace (like the jQuery and Modernizr objects) and that these objects have methods (like jQuery’s .ajax() method and Modernizr’s addThis() method). Also, knowing how to work with closures and callbacks is key to using many of these scripts and frameworks to their fullest.

2. Because understanding JavaScript makes it easier for you to learn object-oriented languages

JavaScript is not a full-on object-oriented language, it’s a prototype-based language that can be made to act like an object-oriented language. However, what you learn in JavaScript can cascade down to other languages. Case in point: PHP associative arrays are easy to pick up once you know how JavaScript’s module pattern works. And JavaScript closures introduce the idea of private, public and protected variables…major building blocks of C#, C++, Java and ActionScript.

3. Because there are many cases when using JavaScript is more efficient

Remember: your jQuery code doesn’t hit the page until it accesses the jQuery object that’s loaded into the browser. Accessing the object does happen fast but it’s faster if you write JavaScript that hits the browser directly.

The most obvious example here is adding, removing and manipulating DOM elements with things like cloneNode and document fragments. jQuery can help with these things but browsers can do them natively and more efficiently.

4. Because potential employers care more about your JavaScript knowledge than your jQuery knowledge

Why? Well for starters, lots of customer projects are created using the stuff in the number 1′s second list above, allowing web shops to charge the customers at a premium cost. And a good JavaScripter can figure out many things on that list over time, making them a very valuable employee. Second, employers want employees that can figure out coding problems on their own. They want an employee that can fix a Spine error one minute and a JSON one the next.

5. Because JavaScript is so popular right now, that many excellent, free beginning learning resources are now readily available

I’ll toot my own horn here and mention my last post on great JavaScript books for beginners but you have to pay for those. Here are some great free ones, two of which are jQuery-related:

Think I left some reasons or resources out? Feel free to comment. AND NO SPAM!! I know what it looks like.

5 Useful JavaScript Books

TOPIC: Books /////Be The First To Comment
 

Disclaimer: because of my affiliate relationships, you will make me money if you click on any of the book links below, then buy a book.

The good news is, there are a lot of JavaScript learning resources online. The bad news is, there are a lot of JavaScript learning resources online. Filtering the bad ones out from the good ones is hard.

This is why whenever I try to learn a new computer skill, I’ll buy a book about it first. Books go through rigid editing processes like fact checking and proofreading, all helping to filter out the bad content.

I have a lynda.com account so lately, I’ve used that as learning resource more than books. But JavaScript is the exception: a lot of great books have come out in the past few years, many of them “thinking books” that seemingly use theory when talking about JS.

Some books are better than others. I’ve read a lot of JavaScript books in the year before this article’s publish date. So as far as those books go, I’ve created a list of JS books which, I think, helps with the filtering process and lists only the best ones…so far. Here they are:

1. JavaScript: Visual QuickStart Guide (8th Edition) by Dori Smith & Tom Negrino

The best book for the JavaScript newbie. Every new edition migrates with the JavaScript trends: from image rollovers and cookie baking to DOM scripting to AJAX to object literals. The 8th addition keeps the tradition.

While the book does cover the trends, it also provides detailed step-by-step instructions on things that the JavaScript beginner needs to know: what a variable is, how to create an array, why are external JS files the right way to go, and so on. And it moves on from the basics to tutorials on more advanced topics such as reading data from a web server with AJAX and a few jQuery techniques. It ends with a great list of other learning resources in its “Where to Learn More” appendix.

If you know absolutely nothing about JavaScript and you pick this book up, I suggest that you treat it like a textbook. It covers JavaScript in the broadest sense, explaining the “hows” and “whys” of the code samples.

Personally, I think Visual QuickStart Guide should spend a bit more time covering the things that make JavaScript act more like an object-oriented programming language. One of its tutorials does mentions JSON, but not in great detail. Its object chapter does cover advance DOM manipulation techniques like cloneNode(), but aside from the object literal, there no mention of design patterns.

A beginner’s JS book doesn’t need to cover every single thing about objects, but should leave the reader with a basic understanding of JavaScript’s OOP potential. The book doesn’t fail at this, but doesn’t exactly hit a home run here.

Regardless of its limited coverage of JavaScript’s OOP possibilities, Visual QuickStart Guide is still the first book I recommend to someone who wants to learn JavaScript, but knows absolutely nothing about it.

2. Object-Oriented JavaScript by Stoyan Stefanov

I’ll get straight to the point: this is an excellent book!

Embellishing a bit more, Yahoo developer Stefanov does an awesome job of teaching the reader how to treat JavaScript as a full-on object-oriented language. He also does an awesome job of explaining the “hows” and “whys” job of the code exercises.

OOJ does cover JavaScript basics like variables and arrays, but not as in-depth as Visual QuickStart Guide. And it doesn’t matter because every topic he discusses, inheritance, closures, prototypes, getters, setters-all of it is useful in today’s JavaScript environment and are discussed in-depth.

A few things: OOJ was published by Packt Publishing who is notorious for releasing books with grammatical and spelling errors-this book is no exception. If you buy it, go to Packt’s Support page, click on the “Title” drop-down menu and find the book title: you’ll see the errors.

Also, Stefanov is working on the 2nd Edition of this book. He’ll be tackling ECMAScript5 and will have a new chapter on JS testing and documentation.

Despite the spelling errors and imminent updated version, any beginning developer with a little-better-than basic understanding of JS has to read the first edition of Object-Oriented JavaScript. That’s it…no more, no less.

3. JavaScript Patterns by Stoyan Stefanov

Another Stoyan Stefanov book, this one explains some excellent best practices such as the right way to structure for loops, when to use hasOwnProperty, and yes, proper JavaScript patterns. Stefanov did apply a few of these best practices in his OOJ coding samples but in Patterns, he explains the meaning behind them.

This book also drives home the importance of keeping the global space as clean as possible. Stefanov’s tips on namespacing patterns, inheritance and encapsulation are must-learns.

This is not a book for beginners and the author says so in the Preface. Except for the first two chapters, reading this book without frustration requires an intermediate understanding of JavaScript, particularly objects.

4. JavaScript: The Good Parts by Douglas Crockford

This article is slightly implying that Object-Oriented JavaScript is the best JavaScript book, which is subjective to other’s opinions. But no one can deny that JavaScript: The Good Parts is the most important book.

Written by Douglas Crockford, the creator of JSON who also works at Yahoo, this book has had tremendous influence on the JavaScript community since it’s 2008 publication. Dig thru the core files of jQuery and Modernizr and you’ll see that they’re chocked full of best practices mentioned in the The Good Parts or, as many refer to it, “the Crockford Book.”

Many, many things that you first learn in JavaScript will need to be unlearned after reading The Good Parts. Iterators, the new keyword, switch/case statements…be prepared to throw some of these away.

As with JavaScript Patterns, the Crockford book is not for beginners…REALLY not for beginners. Those that can’t do anything dynamic with JS outside of making a few alerts will find this book a tough read.

5. Pro JavaScript Techniques by John Resig

I’ll be completely upfront here: I’ve read most of this book, but not all of it. Plus, I haven’t implemented a lot of the new stuff I learned from it.

But this first book by jQuery creator John Resig stands out because it takes key JavaScript concepts, like AJAX and DOM manipulation, and expands on them with step-by-step exercises. It also covers JavaScript testing which is Resig’s most underrated skill.

Techniques isn’t as difficult a read as JavaScript Patterns or the Crockford book, but it won’t explain what a variable is like Visual QuickStart Guide will. But the fact that it offers detailed tutorials on important JS stuff makes it a must-read.

A suggestion on how to read these books

If you understand variables, arrays, functions, try/catch statements and for loops in JavaScript, you MIGHT want to skip Visual QuickStart Guide and go straight to Object-Oriented JavaScript. And as mentioned above, some of the best practices discussed in both JavaScript Patterns and the Crockford Book are discussed in the OOJ book, but none of the others.

To be honest, I suggest that you read Patterns and The Good Parts in parallel with the first two books. For example: when you start to read about for loops in Visual QuickStart Guide, take a few minutes and see what both Patterns and the Crockford book say about them. This is a pain, but the sooner you learn these best practices, the better.

After all this, go back and read Patterns and the Crockford book in full.

Happy reading!

TUTORIAL: What NYC Subways Can Teach Us About JavaScript Closures

TOPIC: Tutorials /////Be The First To Comment
 

VIEW THE DEMO FIRST »

JavaScript doesn’t fit the strict definition of an object-oriented programming language, but it fits well enough so that you can use it to do object-oriented stuff. Closures play a big role here so understanding how they work is important.

Encapsulation

First, understand a programming concept called encapsulation and understand that it has two roles:

  • Encapsulation hides your code from the web browser’s global space until the global space actually needs it, a top-notch JavaScript best practice.
  • It organizes your code quite nicely.

You encapsulate variables and functions for the most part, and do so by placing them inside another function. Encapsulated variables are called private variables while encapsulated functions are called methods.

A private variable is not directly visible by the world outside of the encapsulating function. Encapsulated methods, however, act a little differently:

  • An encapsulated method that returns something is called public method because whatever it returns, it returns to the global space. This means that other parts of your code can access it if you tell your code to do so.
  • A public method is also a privileged method. This is because it has “privileged” access to any variables and methods that it’s encapsulated with.
  • An encapsulated method can also be a private method if it doesn’t return anything that doesn’t return a specific value we give it (meaning that it will still return undefined). Despite this, always remember that it’s doing something…that’s the point of functions, isn’t it? Maybe it’s doing something as simple as sending out an alert, but it’s doing something. And if it’s encapsulated with a public method, the public method can take whatever the private method is doing and send out to the global space.

The stricter object-oriented languages like C# and Java have syntax to create private, public and privileged code, but JavaScript does not. JavaScript can still create such code, and it can still be accessed if it’s private.

In JavaScript, accessing private, encapsulated code from the outside is done with closures.

Obviously, closures can be tough to understand at first, but understanding them is a must if you want to master JavaScript. So, I’m going to try to help here.

A little parable about the New York City subway may help…

The Subway Story

Of all the subway systems in the world, New York City’s is the most famous. It averages 10 million rides a week and is made up of 421 subway stations.

The NYC subway has 24 lines, each traveling through four of the city’s five boroughs: Manhattan, Brooklyn, Queens and the Bronx (sorry Staten Island). So for example: the L line travels from 8th Avenue in Manhattan to Canarsie in Brooklyn, the 6 train travels from Pelham Bay Park in the Bronx to Manhattan’s Wall Street neighborhood, and so on.

There is no borough that all of these lines run through: every borough has a line that doesn’t run through it. And in the case of Manhattan, the busiest borough, that line is the G line that, as of this article, runs from Long Island City in Queens to the Kensington neighborhood in Brooklyn.

The only way to get to “the G” from Manhattan is to take another subway line to a connecting station where the G stops, then transfer over. The G has many connecting stations that you can get to from Manhattan. A few options are:

  • Someone catching the E train at its 14th Street Manhattan stop can take it to its Court Square Queens stop and catch the G.
  • Someone catching the F train at its 2nd Avenue Manhattan stop can take it its to Fort Hamilton Parkway Brooklyn stop and catch the G.
  • Someone catching the N train at its 34th Street Manhattan stop can take it to its 4th Avenue Brooklyn stop and catch the G.

A more direct line between Manhattan and the neighborhoods that the G runs along would be great, but impossible. Strictly speaking, Manhattan can’t see the G line so it can’t access it directly.

The Simple Subway Closure Examples

Now…how does all of this subway stuff tie in with closures?

  • Think of the G line as a private variable encapsulated by a function named brooklyn.
  • All those stops along the G, like Court Square? Think of them as both public and privileged methods: they’re public because things outside of the brooklyn function can access them, but they’re also privileged because they’re inside the brooklyn function and have access to the private variable, the G line.
  • Since the only way to get to the G is via one the connecting lines, think of the connecting lines as closures.

Let’s start with small examples that will build up to the big one. I’ll be running these simple examples in Firebug Console for Firefox.

IMPORTANT: Every time you run a new block of code in the Console, you must do it in a new browser tab.

Cut-and-paste the code below in to the Console and run it:

var GLine = "You have connected to the G line!";
 
alert(GLine); //alert popup appears!

All works fine…we get an alert popup that says “You have connected to the G line!”

Now, open up a new tab and plug this code in the console and run it:

function brooklyn() {
 var GLine = "You have connected to the G line!";
}
 
alert(GLine); //Oops! The alert doesn't show!

The console now returns a message that the GLine is not defined. This because GLine is now a private variable wrapped inside the brooklyn function, meaning the outside world can’t see it. And since our alert lives in the outside world, it’s giving us this error.

A closure named connectingLine can help us here. Open up a new tab again and run this code in the console:

function brooklyn() {
 var GLine = "You have connected to the G line!";
 return function() {
  alert(GLine);
 };
}
 
var connectingLine = brooklyn();
connectingLine(); //alert popup appears!

And with that, the alert now pops up…let’s break down why:

The brooklyn function now contains the not only the GLine private variable, but also an inner function. This inner function is a public method that’s also a privileged method.

As a public method, the function returns whatever it does to the world outside of brooklyn, which is our alert from the earlier examples. And as a privileged method, the function has access to the GLine private variable that it’s encapsulated with, which is the alert message.

Our closure, connectingLine, has the power to find what the public/privileged method returns to the world outside of brooklyn. And again, what it returns is an alert that displays the value of GLine.

The Difficult Subway Closure Example

We started with alerts for the sake of easy explanation-now let’s create something more complicated with a private method:

HTML for the difficult closure example

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>The NYC subway can teach you about closures!</title>
</head>
<body>
<ul>
 <li><a href="#" id="eTrain">Catch the G train by taking the E Train</a></li>
 <li><a href="#" id="fTrain">Catch the G train by taking the F Train</a></li>
 <li><a href="#" id="nTrain">Catch the G train by taking the N Train</a></li>
</ul>
 
<div id="myRoute"></div>
 
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script src="scripts.js"></script>
</body>
</html>

Our simple HTML5-formatted page has three links, each with unique page ID. Using jQuery (note the jQuery core library is attached), our links will run the our JavaScript when clicked. Our JavaScript code will go in the scripts.js file.

JavaScript for the difficult closure example (scripts.js)

(function() {
 
var brooklyn,
 connectWithETrain,
 connectWithFTrain,
 connectWithNTrain;
 
brooklyn = function() {
 var GLine = 'G line!';
 function howToGetThere(trainLine,startingStation,endingStation) {
    $('#myRoute').html('Catch the ' + trainLine + ' at the ' + startingStation + ' station. Take it to ' + endingStation + ' station and get off to catch the ' + GLine);
  }
 
  return {
    ETrain: function() {
      howToGetThere('E train','14th Street, Manhattan','Court Square');
    },
    FTrain: function() {
      howToGetThere('F train','2nd Avenue Manhattan','Fort Hamilton Parkway');
    },
    NTrain: function() {
      howToGetThere('N train','34th Street Manhattan','4th Avenue');
    }
  };
};
 
connectWithETrain = brooklyn();
connectWithFTrain = brooklyn();
connectWithNTrain = brooklyn();
 
$('#eTrain').click(function () {
  return connectWithETrain.ETrain();
});
 
$('#fTrain').click(function () {
  return connectWithFTrain.FTrain();
});
 
$('#nTrain').click(function () {
  return connectWithNTrain.NTrain();
});
})();

Let’s break this code down:

(function() {
...
})();

This is a lot of code and we don’t want it in the global space as that can screw things up, so we’re wrapping it in a self-executing anonymous function (it has other names, but I like this one).

This means that we wrap all this code up in an unnamed function: note that there’s no name between function and () on the first line. The code ends with another () on the last line which makes the function run, or “self-execute.”

And a little piece of trivia: the code for the jQuery core library is wrapped up in a self-executing anonymous function. This type of function has been around for a while, but jQuery’s usage of it has increased its popularity with developers.

var brooklyn,
 connectWithETrain,
 connectWithFTrain,
 connectWithNTrain;

These are variables that we’re going to use at some point in our code. We’re naming them but not initializing them by giving them a value (although you should if possible).

We’re creating them using the single var pattern, meaning that we group all of our variables together with one var keyword and comma-separate them. This keeps our variables organized and easy to find, and since JavaScript moves variables to the top of functions anyway, we might as well do it ourselves.

brooklyn = function() {
...
};

Our brooklyn function has returned…only this time, it’s not a function. Remember, we declared it as a variable in the beginning.

This brooklyn variable is now equal to another anonymous function that encapsulates a lot of code.

 var GLine = 'G line!';
 function howToGetThere(trainLine,startingStation,endingStation) {
    $('#myRoute').html('Catch the ' + trainLine + ' at the ' + startingStation + ' station. Take it to ' + endingStation + ' station and get off to catch the ' + GLine);
  }

Our GLine private variable is still here and it’s still a text string, but it’s shorter than the earlier versions. GLine is joined by a private method called howToGetThere().

A reminder: a private method is method that doesn’t return anything that returns no other value than undefined but does something. And as we can see, this describes howToGetThere() perfectly.

And what’s howToGetThere() “doing?” It’s using jQuery to look for the myRoute ID on our HTML page, then load a text string into it with the jQuery’s .html() function (FYI: .html() is actually a jQuery method!)

The howToGetThere method also has parameters that will be passed into the text string: trainLine, startingStation and endingStation. They will represent, respectively, the name of the train line to catch, where in Manhattan to catch it and where to get off to catch the G Line. The GLine variable will be passed to the text string as well.

The howToGetThere private method is going to run when a link is clicked, but we have a few more things to do first, code-wise.

return {
  ETrain: function() {
    howToGetThere('E train','14th Street, Manhattan','Court Square');
  },
  FTrain: function() {
    howToGetThere('F train','2nd Avenue Manhattan','Fort Hamilton Parkway');
  },
  NTrain: function() {
    howToGetThere('N train','34th Street Manhattan','4th Avenue');
  }
}

Here are three public methods: ETrain, FTrain and NTrain. They all have access to the howToGetThere private method and are written out using something called the module pattern.

Each of these methods runs the howToGetThere private method, returning the parameters we discussed earlier. Again, howToGetThere will run when a page link is clicked but before we talk about that, we have to set up our closures first.

connectWithETrain = brooklyn();
connectWithFTrain = brooklyn();
connectWithNTrain = brooklyn();

Here are the closures. They’re actually the variable names we created at the top of our code with the single var pattern-we’ve just now given them a value.

The value of each closure is the brooklyn() function, meaning it can access the public methods. It will do this with links, which we’ll now set up.

$('#eTrain').click(function () {
  return connectWithETrain.ETrain();
});
 
$('#fTrain').click(function () {
  return connectWithFTrain.FTrain();
});
 
$('#nTrain').click(function () {
  return connectWithNTrain.NTrain();
});

Every time one of our three page links is clicked, jQuery’s .click() method runs a callback function. This function then runs one of our three public methods, which in turn, runs the howToGetThere() private method.

This means that a text string will load into the myRoute page ID when a link is clicked. The parameters defined with the public methods decide what the text string will say.

That’s it for the code. I hope it helps but am sure you want to read up more on the subject. These articles may help.

Further Reading

MDN Closure Article »

The Mozilla Developer Network’s excellent post on closures is your first stop. Take note of the potential performance issues mentioned at the end.

Why use “closure”? by Tim Caswell »

Another excellent article by this California-based developer. His closure examples also use factory patterns and Object.prototype.

Stuart Langridge: Secrets of JavaScript Closures (video) »

Hilarious presentation from this UK-based developer.

Excerpt from John Resig’s Upcoming Book, Secrets of the JavaScript Ninja »

jQuery creator John Resig has written extensively on JavaScript closures. This sample content about closures from his upcoming book is, I think, his most in-depth article on the subject. It’s probably the toughest read on this list, but a great read nonetheless. Registration is required.

Conclusion

Closures are tough to understand in the beginning, I don’t deny it. But they’re useful as hell and make your JavaScript super-efficient. Re-read this article if you need to, check out the articles on the reading list and hit me up if you have questions.

A Simple Explanation of HTML5

TOPIC: HTML5 /////Be The First To Comment
 

HTML5 is big news right now. Web developers have been developing sites with it for the past few years, but awareness among the business community and the general public is really just starting up.

This is great! HTML5 is a major step forward in web development. Plus, HTML5 highlights some excellent coding standards that have been around for years, but aren’t as widely practiced as they should be.

As awesome as this is, I’ve had a few conversations with non-developers who think HTML5 is a magic bullet. Most talk about it as something that they should be doing without fully understanding what it actually is.
HTML5 Logo
While some web developers may be frustrated by the misunderstanding, part of their job is to explain to clients and employers what’s good and bad about new technologies, and without a lot of tech terms. So I’m going to take a stab at providing a simple HTML5 explanation.

And for the record: I think we should be using HTML5 when creating sites, but only in a way that helps us carry through our content strategy.

Here are the topics for this article:

What Is HTML5 Exactly?

The 25-word answer is:

“HTML5 is a major update to HTML that brings excellent new features to both websites and web applications, but also highlights an important older feature.”

Expanding on this definition, the four key things to know about HTML5 are:

  • it creates better semantic markup (the important older feature).
  • it allows for the creation of more robust web applications.
  • it allows for top-notch mobile web development.
  • creating websites and web applications with HTML5 is a best practice but, in all honesty, not a requirement.

Where Did HTML5 Come From?

Created in 1990, HTML has always been a programming language that creates a website’s basic structure. To build a website, HTML “frames” it first, then things like copy and images are added to complete the job.

HTML updates are overseen by the World Wide Web Consortium, or, the W3C. When they began work on the next update in 2004, a group of outside companies spoke out against the direction the W3C was taking it.

The update was great for websites, the companies said, but not so great for the new web applications that were starting to appear. Also, the W3C’s suggested update wasn’t backwards-compatible with older versions of HTML, which would cause developers a ton of problems.

The companies felt that the W3C weren’t evolving HTML beyond a structural language, so they formed a separate group called the Web Hypertext Application Technology Working Group, or WHATWG (pronounced “what-wig”) to do just that. Their goal was to build a new HTML that worked well for both websites and web applications and would also be backwards-compatible with the old HTML.

In 2007, the W3C agreed with WHATWG’s point of view. The two groups remained separate but worked together on creating a new version of HTML, naming it “HTML5.”

The two groups are still working together as the HTML5 specification isn’t finalized as of this article, but it’s still possible to use it to create websites and web applications…as many do.

Semantic Markup

Semantic markup is HTML written in a way that gives site content specific meaning. Semantic markup is not a new a concept: it existed well before HTML5.

HTML5 does create excellent semantic markup though…better than earlier HTML versions. Metaphorically speaking, the semantic markup of earlier versions tells the world, “this is some site content” while HTML5 semantic markup tells the world, “this is some site content, now let me give you some detailed information about it.”

Sites written with semantic markup are easier to read on a multitude of devices: desktops, laptops, smartphones, screen-readers for the disabled, gaming consoles, just to name a few. But search engines also like semantic markup…so much so that web designer Jeffrey Zeldman said it best in 2009:

“Client who saves $5,000 buying cut-rate non-semantic HTML will later spend $25,000 on SEO consultant to compensate”

Correct! Site content wrapped in non-semantic markup is tough for search engines to understand; therefore, it’s tough for search engines to rank and list in their search results.

Hiring an SEO company to fix this is costly. If your site is coded with semantic markup at the beginning, this cost can be, at the very least, reduced.

To be clear: semantic markup up will not improve a site’s search engine ranking. It just makes it easier for search engines to understand a site’s content, which in turn, makes it easier to rank in search resullts.

Think of site content as a pirate’s treasure chest full of gold. Semantic markup gives search engines an awesome treasure map.

One last note on the subject: sites written with semantic markup are said to be “following web standards.” Web developers have been coding with web standards for years, but too many haven’t. A push for all developers to use web standards has always existed, but HTML5 has strengthened this push more than ever before.

Web Applications

A website is a site that gives people information, but doesn’t offer a lot in terms of interaction. People may be able to fill out a form of some sort while visiting the site, but the interaction won’t go much beyond that.

A web application is a site that gives people information and offers a lot in terms of interaction. Some interaction examples are:

  • adding copy, images & videos.
  • removing copy, images & videos.
  • editing copy, images & (sometimes) videos.
  • writing product reviews.
  • sending messages to people.
  • letting people know your current location.

Looking at this list, Facebook, Twitter, FourSquare, and Yelp are great examples of web applications.

Other web application examples include: Hotmail, Yahoo Mail, Gmail, Google Docs and Google Maps.

HTML5′s role in web application development is a bit tricky to describe: start with understanding that there’s “HTML5″ and there’s “HTML5-related technology.”

The following is an incomplete list of things that are part of HTML5:

  • Video: playing video on a website without needing things like Flash.
  • Audio: playing audio on a website without the need for plugins.
  • Canvas: using code to automatically draw stuff on a website.
  • Drag & Drop: dragging and dropping stuff on a website.
  • Application Cache: storing website content, such as images, on a device, making the site run faster.

The following is an incomplete list of things that are HTML5-related technologies:

  • WebGL: creates 3D graphics on a website.
  • Web Workers: a method of running and storing website code behind the scenes.
  • Geolocation: lets websites know where site visitors are geographically located.

HTML5 and HTML5-related technologies can be combined with other technologies to create compelling web applications.

For the sake of easy explanations, I called these things “HTML5-related technologies” but I can’t stress enough that they’re not HTML5. They’re “HTML5-related” at best and even that’s a stretch of the terminology.

Many don’t care about this the proper term usage but do not be surprised if a real stickler comments on this article, telling me that calling these things “HTML5-related” is a no-no. If you want the techie details on this, visit MDN’s HTML5 page and take note of the section called “Technologies often called part of HTML5 that aren’t.”

Mobile Web Development

The web browsers pre-installed in the majority of mobile devices released in the past two years support HTML5: both websites and web applications.

First, understand that there are native applications and there are mobile web applications. Native applications are what are commonly called “apps” or “native apps;” small applications that you download from places such as Apple’s App Store or Google’s Android Market. Mobile web applications are applications that run inside a mobile web browser such as Safari Mobile or Opera Mini; they’re called “mobile web apps” nowadays.

So if you’re on an iPhone, you can open the Safari Mobile web browser (a native app) and go to Facebook’s mobile site (a mobile web app). Or, you can open the App Store (another native app) and download the Facebook application (yet, another native app) and use Facebook from there.

The good thing about native apps is they have more functionality than mobile web apps. The good thing about mobile web apps is that they’re less expensive to create than native apps.

A native app that lives on your smartphone can use other native apps to aid in a particular task…the camera, the address book, directional apps like the compass and the maps, etc. Except for very few instances, mobile web apps can’t do any of this as of this article; therefore, native apps have more functionality.

But it’s always a good idea to make your app to work on as many devices as possible, and doing so can be expensive. The current cost for creating an app that works on just iPhones and Androids is in the five-figure range. Mobile web apps are coded to work on mobile web browsers, which practically every mobile device has. So a mobile web app will work on almost any mobile device, and will be cheap to create when compared to the cost for creating a native app for every device.

HTML5 is well-suited for mobile web apps for a lot a reasons, a big one being the above-mentioned application cache.

When combined with certain HTML5-related technologies, application cache allows mobile web apps to work on devices even if the device doesn’t have an internet connection! These apps would probably need a connection to work as fully intended, but they can still do lots of things offline.

Best of all mobile web browsers support many HTML5 features already. Non-mobile browsers are catching up, but the mobile browsers adopted them first and are ahead in the race as a result.

Because of their offline functionality and early adoption rate among mobile devices, lots of web developers are promoting HTML5 mobile web apps as a viable alternative to native apps. Mobile web apps will need to be able access things like the camera if they expect to beat the native guys, but I believe they’ll have access to many of these things eventually.

Making The Site Look Pretty

There are some HTML5 things that can make sites look good, but very little. And again, these things don’t work in many desktop browsers, which are still used more than mobile browsers.

So to make a site look good in as many browsers as possible, these three things are currently the best tools to do so:

  • CSS3: applies pictures, colors and few cool effects to websites.
  • JavaScript: creates interactivity on a website.
  • JavaScript-related technologies: jQuery is the biggest one of these right now.

These things are not HTML5, but you will see them used in both HTML5 websites and web applications.

How Is HTML5 Being Used As of This Article?

In many ways…

  • HTML5 games make up a bulk of the HTML5 web apps being created: Facebook is very committed to HTML5 games.
  • Web designers are excelling at creating sites with semantically correct HTML5 markup and making them look pretty. The Boston Globe is one of the most celebrated of these sites but HTML5 Gallery also provides some nice samples.
  • Web applications are popping up everywhere. One of my favorites is TweetDeck Web.
  • There are a few mobile web apps out there. Some use a lot of HTML5 and its related technologies, some use just a little of it. jQuery Mobile Gallery is site that uses a fair amount of HTML5 stuff; the sites they display use HTML5 to varying degrees.

How Can Businesses Use HTML5 & HTML5 Related-Technologies Right Now?

I can’t stress the importance of web standard semantic markup enough. Businesses that don’t have it in their sites need to get it in there sooner, not later. They should either edit their current site and add the markup, or plan a site redesign that will include such markup.

If businesses go with the redesign, they can also make it look pretty at that point using CSS, JavaScript and JavaScript-related technologies.

As for web applications and mobile web development, I have to refer to a previous statement…creating websites and web applications with HTML5 is a best practice but, in all honesty, not a requirement.

For example: Facebook and Twitter’s desktop browser applications converted to HTML5 only recently, but millions of people were using them as web apps before that. And both have robust mobile web applications, each one created with an older version of HTML. This is also true for CNN, Fox News, Sephora, ESPN, Ford, Dollar General…I can probably go on and on.

So there’s no clear path here: using HTML5 certainly helps but it seems that not using it doesn’t hurt. Regardless of this, I believe that all sites and web apps from here on in, should be created with HTML5.

I also believe that deciding whether to use HTML5 should not be the first task of a business-that should be focusing on delivering high quality content.

I’m basing this opinion on what I learned at the mobile promotion panel during Social Media Week 2011. Over and over again, the panelists stress how the mobile web was a better promoter than the native app and that we should spend more time developing an effective content strategy instead of following tech trends. Not one panelist mentioned HTML5 and there were many developers working with it at that time.

So my HTML5 suggestions for business don’t have that much to do with HTML5. They are:

  • Confirm that your web developer or agency will create your site with HTML5 semantic web standard markup: Most do, but double-check anyway.
  • Remember that HTML5 isn’t the only thing that makes your site look good: The CSS3 and JavaScript stuff is very important here.
  • Develop your content strategy first: doing so will help you decide what parts of your content are the most important.
  • Don’t think you need to create an HTML5 app: You may find that you don’t need it after you devise your content strategy and that a website will do the job just fine.

In closing, HTML5 is a highly discussed and debated subject right now and some may agree or disagree with what’s being said here. So please feel free to comment on this article and post your opinions.

SCREENCAST TUTORIAL: JavaScript for() loop That Creates A jQuery Fade In/Fade Out

TOPIC: Tutorials /////24 Comments
 

VIEW THE DEMO FIRST »

My most visited article (as of this one) is my jQuery fade in/fade out tutorial. Thanks to a clean <title> tag and a click-inducing meta description, this 58-post blog (also, as of this one) gets roughly 300 unique visits a day…all of which, I’m humbled by.

As I saw how people were using the tutorial’s code, a need to make it dynamic became very obvious. I did so with a JavaScript for() loop….here’s the complete code breakdown:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" href="main.css">
	<title>jQuery fade-ins with a JavaScript for() loop</title>
</head>
<body>	
	<div id="elem0" class="toBeFaded">Here's the first message...</div>
	<div id="elem1" class="toBeFaded">We have second one here...</div>
	<div id="elem2" class="toBeFaded">And here's the third message...</div>
	<div id="elem3" class="toBeFaded">OMG!!! Here's the fourth message!</div>
 
 	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 
  	<script src="fadeCode.js" defer="defer"></script>
 
</body>
</html>

CSS (main.css)

.toBeFaded {
	display: none;
	position:absolute;
	font-size:70pt;
}

JavaScript (fadeCode.js)

$(function (){
 
     var yourFade = 1, // the amount of time in seconds that the elements will fade in AND fade out
     yourDelay = 2, // the amount of time in seconds that there will be a delay between the fade ins and fade outs
     fadeTime = yourFade * 1000, //convert fade seconds to milliseconds (1000)
     delayTime = yourDelay * 1000, // convert delay seconds to milliseconds (2000)
     totalTime = fadeTime + delayTime, //3000 milliseconds...needed for all those delays we talked about
     allElems, // find out exactly how many page elements have the 'toBeFaded' class (4)
     elemNoFade, // Will help us find the last element represent the last element (3)
     i,
     fadingElem;
 
     for (i = 0, allElems = $('.toBeFaded').length, elemNoFade = allElems - 1; i < allElems; i+=1) {
	fadingElem = "#elem" + i;
	if (i === 0) {	
		$(fadingElem).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
	} else if (i === elemNoFade) {
		$(fadingElem).delay(totalTime * i).fadeIn(fadeTime);
	} else {
		$(fadingElem).delay(totalTime * i).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
	}
     }
});

What’s happening here:

  • The elements that you want to fade in and out must be placed on your page with a unique ID that starts with “elem” and ends with a number. The numbers must start counting at 0 (ie. 'elem0' first, 'elem1' next, 'elem2' after that, etc…)
  • Each fading page element must have a classname of 'toBeFaded'.
  • The JavaScript uses those IDs and classnames to detect the page elements and, based on this detection, create jQuery code that fades the elements in and out.
  • There will be a delay between each element’s fade in and fade out. The JavaScript dynamically detects the length of the delay.
  • If you want to adjust the seconds of fade in and fade out time, change the number value of the 'yourFade' variable in the JavaScript.
  • If you want to adjust the seconds of the delay, change the number value of the 'yourDelay' variable in the JavaScript.

The code is fully dynamic: all you have to do is layout the HTML and tweak the JavaScript variables as described above; the code does the rest. You can style things however you want as the CSS but you probably want to keep the display:none and position:absolute settings.

As far as teaching people how to do this, I always assume that those reading my code are web design/dev beginners and try to walk them through it. But the JavaScript for() loop is what’s running things here…walking through that isn’t a simple process.

I remember struggling with the JavaScript for() loop and believe that others do so as well. So I’ve created this three-part screencast tutorial that explains the JavaScript for() loop in excruciating detail.

No doubt about it, this screencast tutorial is for the JavaScript beginner. The JavaScript pro may be bored by it; however, if you are a JavaScript pro but have never read either Douglas Crockford’s JavaScript: The Good Parts or Stoyan Stevanov’s JavaScript Patterns, you may want to check out the third video.

Enjoy!!!

Part One

Part Two

Part Three

Page 1 of 1312345...10...Last »