planet.jquery.com

RSS Feed
$('.blog[tag=jquery]').read();

Asm.js: The JavaScript Compile Target

Posted April 03, 2013 by John Resig

Like many developers I’ve been excited by the promise of Asm.js . Reading the recent news that Asm.js is now in Firefox nightly is what got my interest going. There’s also been a massive surge in interest after Mozilla and Epic announced (mirror ) that they had ported Unreal Engine 3 to Asm.js – and that it ran really well.

Getting a C++ game engine running in JavaScript, using WebGL for rendering, is a massive feat and is largely due to the toolchain that Mozilla has developed to make it all possible.

Since the release of the Unreal Engine 3 port to Asm.js I’ve been watching the response on Twitter, blogs, and elsewhere and while some developers are grasping the interesting confluence of open technologies that’ve made this advancement happen I’ve also seen a lot of confusion: Is Asm.js a plugin? Does Asm.js make my regular JavaScript fast? Does this work in all browsers? I feel that Asm.js, and related technologies, are incredibly important and I want to try and explain the technology so that developers know what’s happened and how they will benefit. In addition to my brief exploration into this subject I’ve also asked David Herman (Senior Researcher at Mozilla Research) a number of questions regarding Asm.js and how all the pieces fit together.

What is Asm.js?

In order to understand Asm.js and where it fits into the browser you need to know where it came from and why it exists.

Asm.js comes from a new category of JavaScript application: C/C++ applications that’ve been compiled into JavaScript. It’s a whole new genre of JavaScript application that’s been spawned by Mozilla’s Emscripten project .

Emscripten takes in C/C++ code, passes it through LLVM, and converts the LLVM-generated bytecode into JavaScript (specifically, Asm.js, a subset of JavaScript).

If the compiled Asm.js code is doing some rendering then it is most likely being handled by WebGL (and rendered using OpenGL). In this way the entire pipeline is technically making use of JavaScript and the browser but is almost entirely skirting the actual, normal, code execution and rendering path that JavaScript-in-a-webpage takes.

Asm.js is a subset of JavaScript that is heavily restricted in what it can do and how it can operate. This is done so that the compiled Asm.js code can run as fast as possible making as few assumptions as it can, converting the Asm.js code directly into assembly. It’s important to note that Asm.js is just JavaScript – there is no special browser plugin or feature needed in order to make it work (although a browser that is able to detect and optimize Asm.js code will certainly run faster). It’s a specialized subset of JavaScript that’s optimized for performance, especially for this use case of applications compiled to JavaScript.

The best way to understand how Asm.js works, and its limitations, is to look at some Asm.js-compiled code. Let’s look at a function extracted from a real-world Asm.js-compiled module (from the BananaBread demo ). I formatted this code so that it’d be a little bit saner to digest – it’s normally just a giant blob of heavily-minimized JavaScript:

.gist-data { max-height: 400px; }

Technically this is JavaScript code but we can already see that this looks nothing like most DOM-using JavaScript that we normally see. A few things we can notice just by looking at the code:

  • This particular code only deals with numbers. In fact this is the case of all Asm.js code. Asm.js is only capable of handling a selection of different number types and no other data structure (this includes strings, booleans, or objects).
  • All external data is stored and referenced from a single object, called the heap. Essentially this heap is a massive array (intended to be a typed array , which is highly optimized for performance). All data is stored within this array – effectively replacing global variables, data structures, closures, and any other forms of data storage.
  • When accessing and setting variables the results are consistently coerced into a specific type. For example f = e | 0; sets the variable f to equal the value of e but it also ensures that the result will be an integer (| 0 does this, converting an value into an integer). We also see this happening with floats – note the use of 0.0 and g[...] = +(...); .
  • Looking at the values coming in and out of the data structures it appears as if the data structured represented by the variable c is an Int32Array (storing 32-bit integers, the values are always converted from or to an integer using | 0 ) and g is a Float32Array (storing 32-bit floats, the values always converted to a float by wrapping the value with +(...) ).

By doing this the result is highly optimized and can be converted directly from this Asm.js syntax directly into assembly without having to interpret it, as one would normally have to do with JavaScript. It effectively shaves off a whole bunch of things that can make a dynamic language, like JavaScript, slow: Like the need for garbage collection and dynamic types.

As an example of some more-explanatory Asm.js code let’s take a look at an example from the Asm.js specification :

function DiagModule(stdlib, foreign, heap) {
    "use asm";

    // Variable Declarations
    var sqrt = stdlib.Math.sqrt;

    // Function Declarations
    function square(x) {
        x = +x;
        return +(x*x);
    }

    function diag(x, y) {
        x = +x;
        y = +y;
        return +sqrt(square(x) + square(y));
    }

    return { diag: diag };
}


Looking at this module it seems downright understandable! Looking at this code we can better understand the structure of an Asm.js module. A module is contained within a function and starts with the "use asm"; directive at the top. This gives the interpreter the hint that everything inside the function should be handled as Asm.js and be compiled to assembly directly.

Note, at the top of the function, the three arguments: stdlib , foreign , and heap . The stdlib object contains references to a number of built-in math functions . foreign provides access to custom user-defined functionality (such as drawing a shape in WebGL). And finally heap gives you an ArrayBuffer which can be viewed through a number of different lenses , such as Int32Array and Float32Array.

The rest of the module is broken up into three parts: variable declarations, function declarations, and finally an object exporting the functions to expose to the user.

The export is an especially important point to understand as it allows all of the code within the module to be handled as Asm.js but still be made usable to other, normal, JavaScript code. Thus you could, theoretically, have some code that looks like the following, using the above DiagModule code:

document.body.onclick = function() {
    function DiagModule(stdlib){"use asm"; ... return { ... };}

    var diag = DiagModule({ Math: Math }).diag;
    alert(diag(10, 100));
};


This would result in an Asm.js DiagModule that’s handled special by the JavaScript interpreter but still made available to other JavaScript code (thus we could still access it and use it within a click handler, for example).

What is the performance like?

Right now the only implementation that exists is in nightly versions of Firefox (and even then, for only a couple platforms). That being said early numbers show the performance being really, really good. For complex applications (such as the above games) performance is only around 2x slower than normally-compiled C++ (which is comparable to other languages like Java or C#). This is substantially faster than current browser runtimes, yielding performance that’s about 4-10x faster than the latest Firefox and Chrome builds.

This is a substantial improvement over the current best case. Considering how early on in the development of Asm.js is it’s very likely that there could be even greater performance improvements coming.

It is interesting to see such a large performance chasm appearing between Asm.js and the current engines in Firefox and Chrome. A 4-10x performance difference is substantial (this is in the realm of comparing these browsers to the performance of IE 6). Interestingly even with this performance difference many of these Asm.js demos are still usable on Chrome and Firefox, which is a good indicator for the current state of JavaScript engines. That being said their performance is simply not as good as the performance offered by a browser that is capable of optimizing Asm.js code.

Use Cases

It should be noted that almost all of the applications that are targeting Asm.js right now are C/C++ applications compiled to Asm.js using Emscripten. With that in mind the kind of applications that are going to target Asm.js, in the near future, are those that will benefit from the portability of running in a browser but which have a level of complexity in which a direct port to JavaScript would be infeasible.

So far most of the use cases have centered around code bases where performance is of the utmost importance: Such as in running games, graphics, programming language interpreters, and libraries. A quick look through the Emscripten project list shows many projects which will be of instant use to many developers.

Asm.js Support

As mentioned before the nightly version of Firefox is currently the only browser that supports optimizing Asm.js code.

However it’s important to emphasize that Asm.js-formatted JavaScript code is still just JavaScript code, albeit with an important set of restrictions. For this reason Asm.js-compiled code can still run in other browsers as normal JavaScript code, even if that browser doesn’t support it.

The critical puzzle piece is the performance of that code: If a browser doesn’t support typed arrays or doesn’t specially-compile the Asm.js code then the performance is going to be much worse off. Of course this isn’t special to Asm.js, likely any browser that doesn’t have those features is also suffering in other ways.

Asm.js and Web Development

As you can probably see from the code above Asm.js isn’t designed to be written by hand. It’s going to require some sort of tooling to write and it’s going to require some rather drastic changes from how one would normally write JavaScript, in order to use. The most common use case for Asm.js right now is in applications complied from C/C++ to JavaScript. Almost none of these applications interact with the DOM in a meaningful way, beyond using WebGL and the like.

In order for it to be usable by regular developers there are going to have to be some intermediary languages that are more user-accessible that can compile to Asm.js. The best candidate, at the moment, is LLJS in which work is starting to get it compiling to Asm.js . It should be noted that a language like LLJS is still going to be quite different from regular JavaScript and will likely confuse many JavaScript users. Even with a nice more-user-accessible language like LLJS it’s likely that it’ll still only be used by hardcore developers who want to optimize extremely complex pieces of code.

Even with LLJS, or some other language, that could allow for more hand-written Asm.js code we still wouldn’t have an equally-optimized DOM to work with. The ideal environment would be one where we could compile LLJS code and the DOM together to create a single Asm.js blob which could be executed simultaneously. It’s not clear to me what the performance of that would look like but I would love to find out!

Q&A with David Herman

I sent some questions to David Herman (Senior Researcher at Mozilla Research) to try and get some clarification on how all the pieces of Asm.js fit together and how they expect users to benefit from it. He graciously took the time to answer the questions in-depth and provided some excellent responses. I hope you find them to be as illuminating as I did.

What is the goal of Asm.js? Who do you see as the target audience for the project?

Our goal is to make the open web a compelling virtual machine, a target for compiling other languages and platforms. In this first release, we’re focused on compiling low-level code like C and C++. In the longer run we hope to add support for higher-level constructs like structured objects and garbage collection. So eventually we’d like to support applications from platforms like the JVM and .NET.

Since asm.js is really about expanding the foundations of the web, there’s a wide range of potential audiences. One of the audiences we feel we can reach now is game programmers who want access to as much raw computational power as they can. But web developers are inventive and they always find ways to use all the tools at their disposal in ways no one predicts, so I have high hopes that asm.js will become an enabling technology for all sorts of innovative applications I can’t even imagine.

Does it make sense to create a more user-accessible version of Asm.js, like an updated version of LLJS? What about expanding the scope of the project beyond just a compiler target?

Absolutely. In fact, my colleague James Long recently announced that he’s done an initial fork of LLJS that compiles to asm.js . My team at Mozilla Research intends to incorporate James’s work and officially evolve LLJS to support asm.js.

In my opinion, you generally only want to write asm.js by hand in a very narrow set of instances, like any assembly language. More often, you want to use more expressive languages that compile efficiently to it. Of course, when languages get extremely expressive like JavaScript, you lose predictability of performance. (My friend Slava Egorov wrote a nice post describing the challenges of writing high-performance code in high-level languages .) LLJS aims for a middle ground — like a C to asm.js’s assembly — that’s easier to write than raw asm.js but has more predictable performance than regular JS. But unlike C, it still has smooth interoperability with regular JS. That way you can write most of your app in dynamic, flexible JS, and focus on only writing the hottest parts of your code in LLJS.

There is talk of a renewed performance divide between browsers that support Asm.js and browsers that don’t, similar to what happened during the last JavaScript performance race in 2008/2009. Even though technically Asm.js code can run everywhere in reality the performance difference will simply be too crippling for many cases. Given this divide, and the highly restricted subset of JavaScript, why did you choose JavaScript as a compilation target? Why JavaScript instead of a custom language or plugin?

First of all, I don’t think the divide is as stark as you’re characterizing it: we’ve built impressive demos that work well in existing browsers but will benefit from killer performance with asm.js.

It’s certainly true that you can create applications that will depend on the increased performance of asm.js to be usable. At the same time, just like any new web platform capability, applications can decide whether to degrade gracefully with some less compute-intensive fallback behavior. There’s a difference in kind between an application that works with degraded performance and an application that doesn’t work at all.

More broadly, keep in mind the browser performance race that started in the late 00′s was great for the web, and applications have evolved along with the browsers. I believe the same thing can and will happen with asm.js.

How would you compare Asm.js with Google’s Native Client? They appear to have similar goals while Asm.js has the advantage of “just working” everywhere that has JavaScript. Have there been any performance comparisons?

Well, Native Client is a bit different, since it involves shipping platform-specific assembly code; I don’t believe Google has advocated for that as a web content technology (as opposed to making it available to Chrome Web Store content or Chrome extensions), or at least not recently.

Portable Native Client (PNaCl) has a closer goal, using platform-independent LLVM bitcode instead of raw assembly. As you say, the first advantage of asm.js is compatibility with existing browsers. We also avoid having to create a system interface and repeat the full surface area of the web API’s as the Pepper API does, since asm.js gets access to the existing API’s by calling directly into JavaScript. Finally, there’s the benefit of ease of implementability: Luke Wagner got our first implementation of OdinMonkey implemented and landed in Firefox in just a few months, working primarily by himself. Because asm.js doesn’t have a big set of syscalls and API’s, and because it’s built off of the JavaScript syntax, you can reuse a whole bunch of the machinery of an existing JavaScript engine and web runtime.

We could do performance comparisons to PNaCl but it would take some work, and we’re more focused on closing the gap to raw native performance. We plan to set up some automated benchmarks so we can chart our progress compared with native C/C++ compilers.

Emscripten, another Mozilla project, appears to be the primary producer of Asm.js-compatible code. How much of Asm.js is being dictated by the needs of the Emscripten project? What benefits has Emscripten received now that improvements are being made at the engine level?

We used Emscripten as our first test case for asm.js as a way to ensure that it’s got the right facilities to accommodate the needs of real native applications. And of course benefiting Emscripten benefits everyone who has native applications they want to port — such as Epic Games , who we teamed up with to port the Unreal Engine 3 to the web in just a few days using Emscripten and asm.js.

But asm.js can benefit anyone who wants to target a low-level subset of JavaScript. For example, we’ve spoken with the folks who build the Mandreel compiler, which works similarly to Emscripten. We believe they could benefit from targeting asm.js just as Emscripten has started doing.

Alon Zakai has been compiling benchmarks that generally run around 2x slower than native, where we were previously seeing results anywhere from 5x to 10x or 20x of native. This is just in our initial release of OdinMonkey , the asm.js backend for Mozilla’s SpiderMonkey JavaScript engine. I expect to see more improvements in coming months.

How fluid is the Asm.js specification? Are you open to adding in additional features (such as more-advanced data structures) as more compiler authors being to target it?

You bet. Luke Wagner has written up an asm.js and OdinMonkey roadmap on the Mozilla wiki, which discusses some of our future plans — I should note that none of these are set in stone but they give you a sense of what we’re working on. I’m really excited about adding support for ES6 structured objects . This would provide garbage-collected but well-typed data structures, which would help compilers like JSIL that compile managed languages like C# and Java to JavaScript. We’re also hoping to use something like the proposed ES7 value types to provide support for 32-bit floats, 64-bit integers, and hopefully even fixed-length vectors for SIMD support.

Is it possible, or even practical, to have a JavaScript-to-Asm.js transpiler?

Possible, yes, but practical? Unclear. Remember in Inception how every time you nested another dream-within-a-dream, time would slow down? The same will almost certainly happen every time you try to run a JS engine within itself. As a back-of-the-envelope calculation, if asm.js runs native code at half native speed, then running a JS engine in asm.js will execute JS code at half that engine’s normal speed.

Of course, you could always try running one JS engine in a different engine, and who knows? Performance in reality is never as clear-cut as it is in theory. I welcome some enterprising hacker to try it! In fact, Stanford student Alex Tatiyants has already compiled Mozilla’s SpiderMonkey engine to JS via Emscripten — all you’d have to do is use Emscripten’s compiler flags to generate asm.js. Someone with more time on their hands than me should give it a try…

At the moment all DOM/browser-specific code is handled outside of Asm.js-land. What about creating an Emscripten-to-Asm.js-compiled version of the DOM (akin to DOM.js)?

This is a neat idea. It may be a little tricky with the preliminary version of asm.js, which doesn’t have any support for objects at all. As we grow asm.js to include support for ES6 typed objects , something like this could become feasible and quite efficient!

A cool application of this would be to see how much of the web platform could be self-hosted with good performance. One of the motivations behind DOM.js was to see if a pure JS implementation of the DOM could beat the traditional, expensive marshaling/unmarshaling and cross-heap memory management between the JS heap and the reference-counted C++ DOM objects. With asm.js support, DOM.js might get those performance wins plus the benefits of highly optimized data structures. It’s worth investigating.

Given that it’s fairly difficult to write Asm.js, compared with normal JavaScript, what sorts of tools would you like to have to help both developers and compiler authors?

First and foremost we’ll need languages like LLJS, as you mentioned, to compile to asm.js. And we’ll have some of the usual challenges of compiling to the web, such as mapping generated code back to the original source in the browser developer tools, using technologies like source maps . I’d love to see source maps developed further to be able to incorporate richer debugging information, although there’s probably a cost/benefit balance to be struck between the pretty minimal source location information of source maps and super-complex debugging metadata formats like DWARF .

For asm.js, I think we’ll focus on LLJS in the near term, but I always welcome ideas from developers about how we can improve their experience.

I assume that you are open to working with other browser vendors, what has collaboration or discussion been like thus far?

Definitely. We’ve had a few informal discussions and they’ve been encouraging so far, and I’m sure we’ll have more. I’m optimistic that we can work with multiple vendors to get asm.js somewhere that we all feel we can realistically implement without too much effort or architectural changes. As I say, the fact that Luke was able to implement OdinMonkey in a matter of just a few months is very encouraging. And I’m happy to see a bug on file for asm.js support in V8 .

More importantly, I hope that developers will check out asm.js and see what they think, and provide their feedback both to us and other browser vendors.

Release: Validation Plugin 1.11.1

Posted March 22, 2013 by Jörn

A new version of the jQuery Validation Plugin is available. This is a bugfix release, mostly addressing regressions from the 1.11.0 release. The biggest one was related to the min/max methods, which would compare numbers to strings, in an attempt to make these methods work for date inputs as well. That’s now fixed. More details in the changelog below.

You can also find this plugin on the jQuery Plugins site .

Download this release.

If you use the plugin, please donate or ask your boss to make a donation !

Click here to lend your support to: jQuery Validation Plugin and make a donation at www.pledgie.com !

Eleven people contributed code to this release . A big thank you to: Bogdan Litescu, Burkhard Reffeling, DexterPark, Erik van Konijnenburg, James Thompson, Nick Schonning, Niklas Nilsson, Paul Cichonski, Robbert Wethmar, g1smd and jcbowman. Also thank you to everyone who reported issues on GitHub or commented on them.

The full changelog:

  • Revert to also converting parameters of range method to numbers. Closes gh-702
  • Replace most usage of PHP with mockjax handlers. Do some demo cleanup as well, update to newer masked-input plugin. Keep captcha demo in PHP. Fixes #662
  • Remove inline code highlighting from milk demo. View source works fine.
  • Fix dynamic-totals demo by trimming whitespace from template content before passing to jQuery constructor
  • Fix min/max validation. Closes gh-666. Fixes #648
  • Fixed ‘messages’ coming up as a rule and causing an exception after being updated through rules(“add”). Closes gh-670, fixes #624
  • Add Korean (ko) localization. Closes gh-671
  • Improved the UK postcode method to filter out more invalid postcodes. Closes #682
  • Update messages_sv.js. Closes #683
  • Change grunt link to the project website. Closes #684
  • Move remote method down the list to run last, after all other methods applied to a field. Fixes #679
  • Update plugin.json description, should include the word ‘validate’
  • Fix typos
  • Fix jQuery loader to use path of itself. Fixes nested demos.
  • Update grunt-contrib-qunit to make use of PhantomJS 1.8, when installed through node module ‘phantomjs’
  • Make valid() return a boolean instead of 0 or 1. Fixes #109 – valid() does not return boolean value
As usual:
  • Please post questions to the official Using jQuery Plugins Forum , tagging your question with (at least) “validate”. Keep your question short and succinct and provide code; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

WebKit is the jQuery of Browser Engines

Posted February 13, 2013 by John Resig

The news has just come out that Opera is switching all of their browsers (both mobile and desktop) to use WebKit (specifically, Chromium). I’ve seen a lot of gnashing of teeth on Twitter and I feel like I can respond because I use to feel the same way back in 2008-2009. However this is 2013 and the Chrome/Chromium team has made it obvious that any form of stagnation or lack of innovation does not need to occur when using WebKit. In fact it possibly gives you the ability to accelerate your development, spending less time worrying about implementing common standards. I would argue that WebKit (a common framework for implementing the standards-compatible portion of a web browser) is exactly like jQuery (a common framework for implementing a DOM standards-compatible experience in a web page) at this point.

These are a few arguments against the switch that I’ve seen so far:

A browser switching to WebKit will result in stagnation

That is demonstrably not true. KDE created KHTML, Apple created WebKit based upon that, Google created WebKit/Chromium based upon that. I don’t think anyone can successfully argue that Chome/Chromium isn’t a better browser than Safari which isn’t a better browser than Konqueror. The Chrome team has proved that stagnation when using WebKit is merely a choice, as a contributor to WebKit you have the complete ability to drive it in a direction you wish (often for the better). I see no reason why the highly-skilled development team at Opera won’t be able to do the same. They can implement a number of their Opera-specific features into WebKit and it’s likely that those features will start to trickle back into other WebKit-using browsers as well.

This is helping to making WebKit a de facto standard, bugs-and-all

I don’t see this argument as being relevant any more, WebKit is already a de facto standard. I mean, everyone remembers when the browsers decided to implement -webkit vendor prefixes ? It’s obvious that the “WebKit is an de facto standard” horse has already left the gate. As to the bugs: WebKit is a common code base that a number of browsers contribute to, however every browser vendor has the ability to make changes to their own fork of the code base. I see no reason why these “now-standard” WebKit bugs wouldn’t be fixed by any single vendor. Having a bug in the engine does not mean that a single browser vendor is incapable of fixing it — they would just be willfully not fixing it (as the browser vendors currently willfully clone -webkit prefixes).

In the case of JavaScript libraries virtually everyone has standardized upon jQuery at this point. This didn’t result in stagnation, which was a major concern, instead it’s resulted in a number of interesting and hyper-popular second-tier frameworks which build upon jQuery, such as: Twitter Bootstrap , HTML5 Boilerplate , and Backbone.js .

This will affect Opera’s ability to influence standards

I don’t see the switch to WebKit causing this. I do see Anne van Kesteren ‘s move to Mozilla as being a massive blow to Opera’s ability to push standards though. I don’t know anything about the situation but if his moving was caused by the switch to WebKit then yes, Opera’s move to WebKit has affected their ability to influence standards.

Opera switching to WebKit is a slippery slope and/or Opera is a small player, Firefox or IE switching to WebKit would be a bigger problem

I think one this is clear already: WebKit has completely and unequivocally won mobile at this point. They are nearly the only rendering engine used on the vast majority of mobile browsers, including the soon-to-switch Opera Mini/Mobile browsers too. There is no reason to worry about a slippery slope, the slope has already been slid down. In order for any other browser to remain relevant in the world of mobile (which, you must admit, is quickly becoming the only world we live in) they must keep feature parity with WebKit. Let’s follow this to its logical conclusion: In a world in which WebKit is now virtually the only mobile browser vendor Mozilla and Microsoft will feel increased pressure to switch their browser engines over to WebKit in order to keep pace. Google has proved that with Chrome that WebKit stagnation is simply a choice so there’s no reason why these other companies shouldn’t be able to build off of WebKit (and possibly create WebKit hybrids, such as WebKit + IonMonkey).

The big question becomes: Should they switch?

At this point it’s honestly a business/engineering decision for Mozilla and Microsoft (as it always has been). If some percentage of your developer force is spending all of their time implementing the same standards that everyone else is implementing then switching to a common code base will give you the ability to free up some of your developers to work on something else. You saw what happened in the case of Chrome: They used their extra developer time to completely crush the competition on performance. This resulted in the everyone-wins race to become the fastest browser.

Ultimately it’s important to remember that WebKit is not a monolithic entity. It’s a shared codebase that a number of corporations contribute to. (In this respect it’s different from jQuery: Almost all contributions to jQuery comes back into the main codebase, whereas with WebKit some come back to the main codebase and some stay in a fork.) There is a lot of code sharing going on but it isn’t the be-all and end-all of browser development. Innovation can clearly still occur when working on a shared codebase and performance will almost certainly continue to improve.

Fixing Google Analytics for Ghostery

Posted February 08, 2013 by John Resig

As an avid user of Ghostery , which blocks all sorts of tracking scripts, pixels, and other web bugs I frequently run across a surprising issue: The case in which the Google Analytics ga.js script has been blocked from loading (which is intended) but then some critical piece of functionality on the site is broken. The most common place I see this is when a site adds some event tracking to a signup or purchase form. Clicking the submit button will result in a JavaScript error, thus making it impossible to submit the form.

I’ve found that this occurs when people are doing inline event tracking and are assuming that the Google Analytics functionality will always exist. Ghostery-or-not this is generally not a good practice to have: Assuming that some external, 3rd-party, script will always correctly load will result in many a broken web page.

You see cases where people work around this issue, for example in the HTML5 Boilerplate project:

  1. <script src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></ script >
  2. <script > window.jQuery || document.write('<script src = "js/vendor/jquery-1.9.1.min.js" ><\/ script> ')</ script >

This attempts to load the jQuery library directly from Google’s CDN and if it fails (for whatever reason — Google’s down, bad Internet connection, or some other weird reason) then it falls back to attempting to load a local version of jQuery. One question that comes of this is: Why not just always load jQuery from your local source rather than rely upon a third party? In this case it makes a lot of sense to pull jQuery from a CDN as you’ll benefit from the performance and caching benefits that a CDN provides, all while reducing the total bandwidth that you’ll have to expend on your end.

In the case of Google Analytics you typically don’t have that luxury: Google recommends that you load the ga.js library directly from their site (which can make sense as then they can push out seamless API changes and bug fixes). However this still causes issues for when Google Analytics simply doesn’t load, wether due to network conditions or due to Ghostery or some other browser extension.

For this reason, in a site I recently built, I added in the following code as a light wrapper around Google’s event tracking API:

  1. // Add in Google Analytics tracking
  2. var track = function(category, name, value) {
  3.     if (window._gaq) {
  4.         window._gaq.push(["_trackEvent", category, name, value]);
  5.     }
  6. };

and then when I wanted to track an actual event I would do something like this:

  1. track("Source", "Visit", this.href);

If Google Analytics has failed to load for some reason then the track() call just silently does nothing – and for users who have Google Analytics installed it tracks the event. I should note that this same technique applies for other event tracking APIs as well, such as Mixpanel or KISSmetrics (they’re blocked the same as Google Analytics).

Even libraries like Segment.io , which act as a unified wrapper around tracking, are prone to the same issue. Even though they’ve gone through all the hard work of creating a unified API for event tracking they are still blocked by Ghostery, which will likely still result in errors in your application. In that case you would just write a similar track(...) wrapper around their analytics.track('Name', properties) call.

Update: The current version of the Google Analytics script always exposes the _gaq object, even if the code isn’t loaded, so this may be a non-issue for Google Analytics (although the principles here hold true for any third-party-included libraries). I’ve gotten word from the Ghostery team that Ghostery now handles this case, automatically exposing missing global objects for cases like this (see below in the comments). I’ve also gotten word from the Segment.io team that, as of now, Ghostery does not block their analytics tracking so you may not need a wrapper there. Additionally Segment.io does check to make sure that the potentially-blocked global objects are actually there before attempting to use them. In general though, and this goes for all third-party script, you’ll probably want to have a wrapper (or an alternative script) if you’re loading code from a third-party domain name.

Secrets of the JavaScript Ninja Released

Posted February 07, 2013 by John Resig

Happy news! My book, Secrets of the JavaScript Ninja is finally in stock on Amazon ! It’s been available on Manning.com for over a month now but I think Amazon has been struggling to keep the books consistently in stock.

You can get an ePub or Kindle version of the book at Manning.com .

I’ve written about the writing process for this book previously (and why it’s taken so long to get out). I especially want to thank my co-author Bear Bibeault who worked hard to get this book out the door.

One question that I’ve been asked recently: “How relevant is this book to writing JavaScript in 2012?” I think it’s still exceedingly relevant. This book has two major focuses:

  1. Teaching aspects of the JavaScript language that are under-served or poorly explained. (For example I’ve been getting a number of messages from people saying how much they appreciated the explanation of closures in the book and that it finally helped them to understand that feature of the language.)
  2. Helping people understand the internal workings of cross-browser DOM-centric JavaScript libraries (such as jQuery). Considering how popular jQuery is (64% of the top 10,000 web sites use jQuery ) and, relatively, how few people truly understand what the library does or is trying to do – there is still a huge market for people to learn what exactly jQuery is and how it works.

I’m really happy that this book is finally out and to celebrate I’ve been trying to blog more (as you may have noticed). Are there any particular topics that you’d like me to write about? Let me know!

Keeping Passwords in Source Control

Posted February 06, 2013 by John Resig

I learned a neat tip from my co-worker, Craig Silverstein (more on Craig joining Khan Academy ), recently and I thought others might find it to be useful.

It has to deal with the eternal question: How do you store sensitive configuration options (such as usernames, passwords, etc.) in source control? Typically what I’ve done is to just punt on the problem entirely. I create a dummy configuration file, such as conf/sample-settings.json which has the basic structure but none of the details filled out. For example:

conf/sample-settings.json

  1. // Copy to conf/settings.json
  2. // and fill these in with your login details!
  3. {
  4.   "db": {
  5.     "username": "",
  6.     "password": ""
  7.   }
  8. }

If someone else needed the details I would just email it to them, or some such (not ideal). Especially when it came time to add additional information to the file or make other changes.

The technique I picked up from Craig was to, instead, keep an encrypted version of the configuration file in source control and then provide a means through which the user can encrypt and decrypt that data.

In this case you can still have the a dummy config file, if you wish.

To start you’ll want to make sure you have your source control ignore the configuration file — just to make super-sure that no one ever accidentally commits it. In Git you’d add a line like this to your .gitignore file:

.gitignore

  1. conf/settings.json

Next you’ll want to create your actual config file and populate it with the real values.

conf/settings.json (* Do not check this in to source control!!)

  1. {
  2.   "db": {
  3.     "username": "cool_guy",
  4.     "password": "A1B2C3!"
  5.   }
  6. }

Finally you’ll want to create a script (I’m using a Makefile ) that the user can run to encrypt and decrypt the file. This script uses OpenSSL, and specifically CAST5 , to encrypt/decrypt the file. OpenSSL was chosen in particular as it worked out-of-the-box on both Linux and Mac machines.

OpenSSL reads in the appropriate files (depending upon if you’re encrypting or decrypting) then will prompt you for a password to encrypt/decrypt the file. (You’re free to use any encryption scheme that OpenSSL supports, of course.)

Makefile

  1. .PHONY: _pwd_prompt decrypt_conf encrypt_conf
  2.  
  3. CONF_FILE =conf/ settings.json
  4.  
  5. # 'private' task for echoing instructions
  6. _pwd_prompt:
  7.     @ echo "Contact jeresig@gmail.com for the password."
  8.  
  9. # to create conf/settings.json
  10. decrypt_conf: _pwd_prompt
  11.     openssl cast5-cbc -d -in ${CONF_FILE} .cast5 -out ${CONF_FILE}
  12.     chmod 600 ${CONF_FILE}
  13.  
  14. # for updating conf/settings.json
  15. encrypt_conf: _pwd_prompt
  16.     openssl cast5-cbc -e -in ${CONF_FILE} -out ${CONF_FILE} .cast5

With all this in place the next step is simple, you’ll run:

  1. make encrypt_conf

and you’ll enter in a password with which to encrypt the config file:

  1. Contact jeresig@gmail.com for the password.
  2. enter cast5-cbc decryption password:

Make sure you write this down and don’t forget it — it’ll be very hard (if not impossible) to get your config file back if you forget the password.

At this point you’ll have a conf/settings.json.cast5 file and you can commit all the changes, using something like:

  1. git add .gitignore Makefile conf/ settings.json.cast5
  2. git commit -m "Adding in an encrypted config file."

Now whenever someone downloads the code from source control they’ll need to either fill in their own values into the config file or they’ll need to get the password from you (the one you entered when you ran make encrypt_conf — or even better, use a shared password safe to manage this). Once they have the password they just run the following and enter it:

  1. make decrypt_conf

If you ever need to update the values in the config file, it’s really straight-forward. Just update the config file, run make encrypt_conf again, and commit the new conf/settings.json.cast5 file.

One extra bit that you can add to your application, to make this process more intuitive, is a check for a missing config file and output with instructions for using the Makefile .

For example if you were using Node.js you could do:

  1. if (!fs.existsSync("conf/settings.json")) {
  2.   console.error("Config file [conf/settings.json] missing!");
  3.   console.error("Did you forget to run `make decrypt_conf`?");
  4.   process.exit(1);
  5. }

Also, you may want to consider having a check to see if the decrypted file is out of date (which can happen if some changes were made in the source control, then were checked out, but you didn’t also run make decrypt_conf ). Perhaps something like the following:

  1. (function() {
  2.   var conf_time = fs.statSync("conf/settings.json").mtime.getTime();
  3.   var cast5_time = fs.statSync("conf/settings.json.cast5").mtime.getTime();
  4.  
  5.   if (conf_time < cast5_time) {
  6.     console.error("Your config file is out of date!");
  7.     console.error("You need to run `make decrypt_conf` to update it.");
  8.     process.exit(1);
  9.   }
  10. })();

And that’s it! Simpler than passing around config files manually and you still get all the benefit of using revision control to manage the file and changes.

Release: Validation Plugin 1.11.0

Posted February 04, 2013 by Jörn

A new version of the jQuery Validation Plugin is available. Once again this release brings more stability (bug fixes!), better localization (new: Malay) and improved html5 compability (min/max attributes on type=”date” now work with the min/max methods). More details on the code and feature changes in the changelog below.

Backwards compatibility is still going strong: The plugin should work with anything from jQuery 1.4.x to 1.9.x.

This is the first release to make it to the new jQuery Plugins site .

Download this release.

If you use the plugin, please donate or ask your boss to make a donation !

Click here to lend your support to: jQuery Validation Plugin and make a donation at www.pledgie.com !

The full changelog:

  • Remove clearing as numbers of `min`, `max` and `range` rules. Fixes #455. Closes gh-528.
  • Update pre-existing labels – fixes #430 closes gh-436
  • Fix $.validator.format to avoid group interpolation, where at least IE8/9 replaces -bash with the match. Fixes #614
  • Fix mimetype regex
  • Add plugin manifest and update headers to just MIT license, drop unnecessary dual-licensing (like jQuery).
  • Hebrew messages: Removed dots at end of sentences – Fixes gh-568
  • French translation for require_from_group validation. Fixes gh-573.
  • Allow groups to be an array or a string – Fixes #479
  • Removed spaces with multiple MIME types
  • Fix some date validations, JS syntax errors.
  • Remove support for metadata plugin, replace with data-rule- and data-msg- (added in 907467e8) properties.
  • Added sftp as a valid url-pattern
  • Add Malay (my) localization
  • Update localization/messages_hu.js
  • Remove focusin/focusout polyfill. Fixes #542 – Inclusion of jquery.validate interfers with focusin and focusout events in IE9
  • Localization: Fixed typo in finnish translation
  • Fix RTM demo to show invalid icon when going from valid back to invalid
  • Fixed premature return in remote function which prevented ajax call from being made in case an input was entered too quickly. Ensures remote validation always validates the newest value.
  • Undo fix for #244. Fixes #521 – E-mail validation fires immediately when text is in the field.
As usual:
  • Please post questions to the official Using jQuery Plugins Forum , tagging your question with (at least) “validate”. Keep your question short and succinct and provide code; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

Enjoy!

i18n Module for Node and Express.js

Posted January 15, 2013 by John Resig

As a follow-up to my post from last week on a strategy for i18n and Node.js I’ve published my module for handling internationalization in Node and, specifically, Express.js.

The module is now available on NPM and can be installed by running:

npm install i18n-2

The code and documentation for the module is available on Github here:

https://github.com/jeresig/i18n-node-2

I’ve designed the API to work as simply as possible with Express.js – while still supporting a simple Node.js usage or usage with another web framework.

The module includes a number of features built-in:

  • Automatic integration with Express as middleware and integration with templating solutions.
  • Support for handling the setting of locale based upon query strings and/or subdomain.
  • Dynamic reading and updating of translation files during development mode.
  • Automatic caching of translation files in production mode.

Usage is simple, in your Express app.js:

  1. // load modules
  2. var express = require('express'),
  3.     I18n = require('i18n-2');
  4.  
  5. // Express Configuration
  6. app.configure(function() {
  7.     // ...
  8.  
  9.     // Attach the i18n property to the express request object
  10.     // And attach helper methods for use in templates
  11.     I18n.expressBind(app, {
  12.         // setup some locales - other locales default to en silently
  13.         locales: ['en', 'de']
  14.     }));
  15.  
  16.     // Set up the rest of the Express middleware
  17.     app.use(app.router);
  18.     app.use(express.static(__dirname + '/public'));
  19. });

Inside your Express view:

  1. module.exports = {
  2.     index: function(req, res) {
  3.         req.render("index", {
  4.             title: req.i18n.__("My Site Title"),
  5.             desc: req.i18n.__("My Site Description")
  6.         });
  7.     }
  8. };

Inside your templates (this example uses the Swig templating system ).

{% extends "page.swig" %}
{% block content %}
<h1>{{ __("Welcome to: %s", title) }}</h1>
<p>{{ desc }}</p>
{% endblock %}

My module is based off of the i18n-node module by Marcus Spiegel .

I used the original i18n-node module as a basis for further work as it provided the closest solution to full Express.js integration that I needed. After some initial usage though I saw that it was very much lacking. As I described in my previous post there is potential for severe problems to occur in an asynchronous environment like Node.js.

The problem that I was having was rather severe and, unfortunately, required a complete rewrite of the module. The original i18n-node module stored the locale information in a closure. Calling setLocale changed the locale but did so for every instance that was currently active, resulting in templates being rendered in the wrong language.

Here is the issue that is especially surprising (but not so much once you know how modules work in Node.js): Since the state was stored in a closure repeated calls to require('i18n') resulted in the current locale state being held the entire time, not reset. This meant that when a new request came in, the locale was set, changing the locale for all other active requests.

The only way to fix this particular problem is to simply encapsulate all state into a single object — I did this by making an object that you instantiate: new I18n(options) .

I looked at other JavaScript translation solutions, including the excellent Jed and messageformat and while their translation capabilities are top-notch what they provided was overkill for my particular application and did not provide the Express.js integration that I needed.

I hope others will find this module to be useful, especially when used in conjunction with my strategy for i18n and Node.js .

A Strategy for i18n and Node.js

Posted January 11, 2013 by John Resig

Recently I internationalized a Node/Express web application that I’ve been working on and it seems to have gone fairly well (users in multiple languages are using it happily and I’m seeing a marked increase in traffic because of it!). Not much of what I’m writing up here is particular to Node, per se, just a general strategy for internationalizing a web application.

I’ve used enough internationalized web sites, and travelled to enough foreign countries and attempted to use English language sites back in the US, that I knew what kind of features I wanted:

  • Full parity between languages. Wherever possible the same content should be available to everyone.
  • Use sub-domains to contain different language versions. It’s overkill/expensive to use different TLDs and it’s annoying to have to twiddle query strings or paths to match a language.
  • No automatic translations of content to the user’s native language. There is nothing worse than arriving at a site and being forced into a version that you can’t read either because it’s poorly translated, or you’re being GeoIP detected, or you’re on a computer whose language settings don’t match your own. If you visit a URL it should always be in the same language
  • No automatic redirects to a site with the user’s native language. Same as the last one. If I visit “foo.com” I should not be automatically routed to “es.foo.com” because it thinks that I speak Spanish. Instead, give the user a notification in their native language and allow them to visit the page themselves.

The end result would be a simple URL system that works like so:

  • domain.com – Main site (English)
  • ja.domain.com – Japanese Site
  • XX.domain.com – Other languages

and due to the full translation parity and the lack of URL modification it meant that for every page that you visited you could visit the same page in another language just by changing the sub-domain.

For example:

   domain.com/search?q=mountain
ja.domain.com/search?q=mountain

Both work identically, just the second one is presented in Japanese.

This has the benefit that in the header of the page I can link the user to the same exact page but in their native language.

Additionally I can use the rel=”alternate” hreflang=”x” technique to help Google understand the structure of my site better. I can put this in the header of my page and Google will show the language-preferred version of the site in the Google results.

<link rel="alternate" hreflang="ja"
    href="http://ja.domain.com/" />

Server

Encouraging users to find the correct content is a key implementation detail, considering that the content is not translated automatically nor is the user redirected to content in their native language. While the links in the header are a good start I also wanted to show a message at the top of the page encouraging the user to view the content (with the message being written in their native language).

As it turns out this can be particularly tricky to implement. The easiest way to do it is to simply check the user’s request headers and look at what’s listed in their “Accept Language ” and then display the message based upon that. This really only works if your content is always dynamic and is never being cached.

If that’s not the case for your application, how and where you do your caching matters.

In my particular application I’m using nginx in front of a proxied collection of Node/Express servers. This means that everything coming from the Node server is cached (including any messages to the user telling them to visit another page).

As a result, in order to display this message to the user we’re going to need to manage the logic for this on the client. Unfortunately this is where we hit another stumbling block: It’s not possible to reliably determine the desired language of the user using just JavaScript/the DOM.

Thus we’ll need to get the server to pass us some extra information on what the user’s desired language is.

To do this I used the nginx AcceptLanguage Module and then set a cookie with the desired language and passed it to the client. This is the relevant nginx configuration to make that happen.

set_from_accept_language $lang en ja;
add_header Set-Cookie lang=$lang;

And now on the client-side all the needs to happen is reading the cookie for the desired language and displaying the redirect message if the current language and the desired language don’t match.

This gives the best of all worlds: nginx continues to aggressively cache the results from my Node servers and the client displays a message in the user’s native language encouraging them to visit the appropriate sub-domain.

i18n Logic

I’ve written a new Node i18n module which follows the makes the following strategy possible.

None of the i18n logic is particularly out of the ordinary but there are a few strategies I took that helped to simplify things.

  • All translations are stored in named JSON files.
  • Those files are loaded and used for in-place translation in the application.
  • Translations are done using the typical __("Some string.") technique (wherein “Some string.” is replaced with the translated string, if it exists, otherwise “Some string.” is returned instead).

Since all requests to the server are handled by a single set of servers this means that translation logic cannot be shared – it must be initialized and used on a request-by-request basis. I’ve seen other i18n solutions, like i18n-node that assume that the server will only ever be serving up pages in a single language, and this tends to fail in practice – especially in the shared-state, asynchronous, realm of Node. For example:

Since whenever a request comes in and set the current language, it sets the current language for the shared i18n object – and given the asynchronous nature of Node it’s possible that other requests may be happening at the same time, and thus changing the displayed language of another request as a result.

You’ll want to make sure that, at minimum, your current language state is stored relative to the current request to avoid this problem. (My new i18n node module fixes this, for example.)

In practice it means that you’ll be adding a i18n property to the request object, likely as a piece of Express middleware, like so:

app.use(function(req, res, next) {
	req.i18n = new i18n(/* options... */);
	next();
});

Workflow

I have it so that the i18n logic behaves differently depending upon if the server is in development mode or in production mode.

When in development mode:

  • Translation JSON files are read on every request.
  • Translation files are updated automatically any time a new string is detected.
  • Warnings and debug messages are shown.

In production mode:

  • All JSON translation files are cached the first time they’re read.
  • Translation files are never updated dynamically.
  • No warnings or debug messages are shown.

The two major differences here are the caching and the auto-updating of the JSON files. When in development it’s quite useful to have the translation files reload on every request, in case a change has been made to their contents. Whereas in production they really should be considered static files.

Additionally, the workflow of having the translation files update every time a new string is found is actually quite useful: It helps you to catch strings that you may have forgotten to translate. Naturally doing this in production (frequently hitting the disk) is not a good idea.

Marking Up Strings

Strings that need to be translated can be found in a number of locations: Inside your application source, inside templates, inside JavaScript files, and even (god forbid) inside CSS files.

In the case of my application I had no strings inside my JavaScript or CSS files. This worked out nicely because I had already written my application in such a way that content is never being dynamically constructed from strings inside my client-side JavaScript. If I were to do that I would use a template and put the template directly into the HTML of my page, using something like my JavaScript Micro-Templating solution.

I consider it to be especially important that you try to avoid having any translatable strings in your JavaScript or CSS files as those files you’ll want to heavily cache and likely put onto a CDN. Naturally, you could dynamically replace those strings as part of your build process and just generate a number of script/css files, one for each language you support, but that is likely up to you and how much extra work you want to introduce into your build.

Inside my application I made sure that the only time I ever attempted to translate a string it was inside of a Express view handler (meaning that I had access to the request object, which is where I bound my i18n object).

An example of using the i18n object inside a view:

  1. module.exports = {
  2.     index: function(req, res) {
  3.         req.render("index", {
  4.             title: req.i18n.__("My Site Title"),
  5.             desc: req.i18n.__("My Site Description")
  6.         });
  7.     }
  8. };

For my templates I use the confusingly-named swig , but the technique for actually using the i18n methods will be roughly the same for most templating systems:

  1. {% extends "page.swig" %}
  2.  
  3. {% block content %}
  4. <h1 > {{ __("Welcome to:") }} {{ title }}</ h1 >
  5. <p > {{ desc }}</ p >
  6. {% endblock %}

A string is wrapped with a __(...) call and the string is replace with the translated string, as it is called.

Translation

So far the actual translation process has been relatively simple. It’s just me doing the translation and I’m not out-sourcing anything (at least not yet). Additionally my site is relatively simple, only a couple dozen strings at the moment.

I’ve been able to temporarily “cheat” in a few ways (at least until I hire a real translator):

  • Use Open Source Translations. There are already massive Open Source projects out there that have done a lot of hard work in translating their UIs. For example Drupal has all of their translations online in easy-to-download formats. I was able to find a number of strings that I needed by going through their files.
  • Look at already-localized sites. This is another cheat but look for other sites that have some of the same features of your site and have already gone through the hard work of localizing into multiple languages, like Google. (In my case I was working on a search engine so a number of Google’s strings directly matched strings on my site.)
  • Google Translate. I know, I know – but I was really surprised at how much better Google Translate has gotten as of late, especially for translating single words or concepts. It’s able to tell you the exact meanings for different possible translations, which is really impressive.

Conclusion

I’m only a couple weeks in to having implemented this process on my site, so I’m sure some things are likely to change as I start to scale up more. I’ve already substantially increased traffic to my site, especially as Google has started to index the newly-translated site. As I mentioned before I have a new Node i18n module that complements the above process and hopefully make it easier for others to follow, as well.

Talk: Khan Academy Computer Science

Posted October 26, 2012 by John Resig

This past weekend I gave a talk at EmpireJS on the Computer Science platform that I’ve been developing at Khan Academy. The talk explores that platform and then goes into deeper technical details about how the real-time execution on the site was achieved.

I recorded the talk on my laptop (so please excuse the echo as it wasn’t properly mic’ed up) and you can watch it here :

A slightly older (stats are slightly out of date) version of the slides can be found here:

jQuery.LocalScroll 1.2.7 released

Posted September 19, 2012 by Ariel Flesler
In this release I cleaned up the code a little and added some features. Also removed a few old (aka deprecated) stuff that were still hanging around.

Enhancements

  • Added some misc enhancements and cleanup the code.
  • Updated the plugin to take advantage of recent scrollTo additions.

Changes

  • The element that triggered the scroll cannot be accessed anymore from within the onBefore, you can bind your own click (or w/e) to them in order to add a class or things like that.
  • settings.persistent is no longer supported (was deprecated).

Features

  • The set of settings can be accessed from within the onBefore as the 'this'.
  • The hash (#foo) is set to the URL before scrolling, so the back button works accurately (when scrolling the window).
  • The option 'hash' doesn't make the window jump when scrolling overflown elements
  • $.localScroll.hash now resets the element scroll to (0,0) by default. You can set the setting 'reset' to false to avoid this.
Enjoy!

Links

Downloads

jQuery.SerialScroll

Posted September 13, 2012 by Ariel Flesler

Introduction

This plugin allows you to easily animate any series of elements, by sequentially scrolling them. It uses jQuery.ScrollTo to achieve the scrolling animation. It is a very unrestricted plugin, that lets you customize pretty much everything from outside. You can use horizontal or vertical scroll, also combined.



What's it for ?

jQuery.SerialScroll doesn't have one definite purpose. It's generic and adaptable. You can certainly use it as a screen slider . That is, to sequentially navigate a group of screens.

This plugin can also animate a text scroller in no time.

It can definitely handle slideshows , the high customizability of the scrolling effect lets you create beautiful animations.

You can even build an automatic news ticker !

Three of these uses are exemplified in the demo.

Remember, it's not restricted to these situations. It will take care of any collection of html elements that you want to scroll consecutively.



Settings and customization

jQuery.SerialScroll gives you access to a lot of options.

These are:
  • target
    The element to scroll, it's relative to the matched element.

    If you don't specify this option, the scrolled element is the one you called serialScroll on.
  • event
    on which event to react (click by default).
  • start
    first element of the series (zero-based index, 0 by default).
  • step
    how many elements to scroll each time. Use a negative number to go on the other way.
  • lock
    if true(default), the plugin will ignore events if already animating. Then animations can't be queued.
  • cycle
    if true, the first element will be shown after going over the last, and the other way around.
  • stop
    if true, the plugin will stop any previous animations of the element, to avoid queuing.
  • force
    if true, an initial scroll will be forced on start.
  • jump
    if true, the specified event can be triggered on the items, and the container will scroll to them.
  • items
    selector to the items(relative to the scrolled element).
  • prev
    (optional)selector to the 'previous' button.
  • next
    (optional)selector to the 'next' button.
  • lazy
    if true, the items are collected each time, allowing dynamic content(AJAX, AHAH, jQuery manipulation, etc).
  • interval
    If you specify a number, the plugin will add auto scrolling with that interval.
  • constant
    Should the speed remain constant, no matter how many items we scroll at once ? (true by default).
  • navigation
    Optionally, a selector to a group of elements, that allow scrolling to specific elements by index. Can be less than the amount of items.
  • excludenew
    If you want the plugin, to stop scrolling before the actual last element, set this to a number, and that amount of items is ignored counting from the end.

    This is useful if you show many items simultaneously, in that case, you probably want to set this option to the amount of visible items - 1.
  • onBefore
    A function to be called before each scrolling. It receives the following arguments: event object, targeted element, element to be scrolled, collection of items and position of the targeted element in the collection.

    The scope(this) will point to the element that got the event. If the function returns false, the event is ignored.
Also, you can use jQuery.ScrollTo's settings!

Check its demo to see all of them.



The option 'target'
This option is a new addition, included since 1.2.0.

Before, you needed to call the plugin once for each scrolled element.

When this option is specified, the matched elements are no longer the scrolled elements, but a container.

In this case, the selectors of prev, next, navigation and target will be relative to this container, allowing you to call SerialScroll on many elements at once.



External manipulation, event triggering

jQuery.SerialScroll automatically binds 3 events to the containers.

These are:
  • prev.serialScroll
    Scrolls to the previous element.
  • next.serialScroll
    Scrolls to the next element.
  • goto.serialScroll
    Scrolls to the specified index, starts with 0.
  • start.serialScroll
    (Re)starts autoscrolling.
  • stop.serialScroll
    Stops the autoscrolling.
  • notify.serialScroll
    Updates the active item.
This looks confusing, but it's not. You use it like this:
$
(container).trigger( 'prev'
 );
$
(container).trigger( 'next'
 );
$
(container).trigger( 'goto'
, [
 3
 ]
 );
$
(container).trigger( 'start'
 );
$
(container).trigger( 'stop'
 );
$
(container).trigger( 'notify'
, [
 4
 ]
 );
'notify' also accepts a DOM element(item), or any of its descendants.

$(container) is the element that gets scrolled each time. If you specified a 'target', then that element, else, the element you called the plugin on.

Note that to use 'start' and 'stop' you need to use the option 'interval' first.

If your container element already has any of these event names bound(odd!), then just add the namespace when you trigger.

You probably won't need to deal with these events, but if so, this is how.



What makes jQuery.SerialScroll so special ?

This plugin has many positive features, of course, it won't fit everyone's needs. That's impossible.
  • Small Footprint
    This plugin is tiny, as said before, it requires jQuery.ScrollTo. Both plugins together, take less than 3.5kb minified .

    If by chance, you decide to include jQuery.LocalScroll , the 3 of them require less than 5kb . Including this plugin is not a bad idea, it can be used, instead of the option 'navigation' to build a widget with sequential and random scrolling.
  • Highly customizable
    This plugin has many settings to customize, in addition, it can use jQuery.ScrollTo's settings. That makes 27 different options!

    If you take a while to analyze them all, you can make your work really unique.
  • Accessible, degrades gracefully
    Probably many will automatically skip this part, shame on you!

    If you make sure non-javascript users will see the scrollbars, then they can perfectly navigate your content. You can show the scrollbars only for these few users, easily, using css/js.

    This is one of the main differences with many similar scripts, they generate the content and the styling using javascript.
  • Adaptable
    jQuery.SerialScroll won't alter the html or styles at all .

    You are in control of the styles and content of your collections. You don't need the plugin to decide what html to use, or how many items to show simultaneously, and you can safely change that yourself, the plugin will always work.

    The items don't need to have fixed size, nor to be aligned . SerialScroll will scroll from one to the other, no matter what.

    If you want a plugin with premade styles or automatic generation of html, then you should consider any of jQuery carousels.
  • Generic and reusable
    Finally, as mentioned before, this plugin can be used for many different situations and doesn't have one specific application.

Links

Downloads

I really advice using the minified versions. The code is optimized to those releases. Source versions should only serve to learn.



3/07/08
Added 1.1.2, start and stop events. Allows negative step.

3/10/08
Added 1.2.0, major release, updated everything.

3/20/08
Added 1.2.1, added 'exclude' and enhancements.

4/28/08
Added a link to "Doctorate on jQuery.SerialScroll".

jQuery.SerialScroll 1.1 released

Posted September 13, 2012 by Ariel Flesler
I added a major release of jQuery.SerialScroll. It doesn't have that many changes, but I really feel it made one step ahead.

Optimizations

  • The animation is skipped if a bad position was received or it's the same as the actual. Saving some overhead.

Changes

  • Changed the licensing from GPL to GPL+MIT.

Features

  • The plugin binds 3 events to the container to allow external manipulation. They are clearly explained in the main post, please check it.
  • Added 2 more arguments to the onBefore callback: actual item collection, index of the actual item in the collection.
  • Added option 'interval', can be a number specifying the amount of milliseconds for autoscrolling.
I upgraded the main post and it has extensive and detailed documentation. Also added some more text and options to the demo.

Links

Downloads

I really advice using the minified versions. The code is optimized for those releases. Source versions should only serve to learn.

jQuery.SerialScroll 1.2 released

Posted September 13, 2012 by Ariel Flesler
I added a major release of jQuery.SerialScroll. It includes a ton of new features and allows close integration with jQuery.LocalScroll .



Fixes

  • If you call the plugin on the same (scrollable)element more than once, the custom events get bound only on the first call.

Changes

  • The event 'start' no longer receives the interval, you must set it at start, stop/start only pause/restart.

Features

  • You can notify SerialScroll that the active item changed, by using the event notify.serialScroll.
  • Thanks to the event notify, this plugin can be now closely integrated with LocalScroll(1.2.5 or higher).
  • Also, thanks to notify, you can call SerialScroll on the same element more than once, and they interact nicely.
  • You can specify the option 'target', and then the matched elements become the context of all the selectors, and target matches the element to be scrolled. This allows you to call SerialScroll on many element at the same time.
  • You can combine the options 'jump' and 'lazy' (not adviced if no target is specified).
  • LocalScroll and SerialScroll are so compatible, that they can use the same hash of settings.
  • Added option 'constant'(true by default), specifies whether the speed must be constant or not.
  • Added option 'navigation' to add a group of element to jump to the items.

Links

Downloads

I really advice using the minified versions. The code is optimized for those releases. Source versions should only serve to learn.

jQuery.SerialScroll 1.2.2 released

Posted September 13, 2012 by Ariel Flesler

Enhancements

  • Removed the check that avoids re-scrolling to the same index, this might be desirable sometimes.
  • The settings object is exposed in the onBefore as the this.

Links

Downloads

Release: Validation Plugin 1.10.0

Posted September 07, 2012 by Jörn

Wow, 11 months. It really has been 11 months since the 1.9.0 release. Interesting freelance times!

Anyway, the jQuery validation plugin 1.10.0 is here! While the very recently launched Pledige.org campaign is just at the start, I hope this release helps convince you that the project isn’t dead. On the contrary, this release brings you all the improvements that were built during those 11 months. A big chunk was contributed by Max Lynch , kudos to him!

What changed? One cool new feature is the ability to specify messages with data- attributes. The next release should bring more html5y support like that, but for now you can put data-msg="Please please fill out this field!" into your markup, or specify one message per method: data-msg-required="Really need this" data-msg-minlength="Moar characters please" (please don’t use these messages in your application…).

Apart from that we’ve got a ton of updates on the outskirts: Localized messages now use their correct ISO codes, a lot of language files got added or improved. Additional methods got a few new citizens and updates to existing methods.

Backwards compatibility is still going strong: The plugin should work with anything from jQuery 1.3.x to 1.8.x.

Download this release.

Don’t forget to donate and spread the word!

Click here to lend your support to: jQuery Validation Plugin and make a donation at www.pledgie.com !

The full changelog:

  • Corrected French strings for nowhitespace, phoneUS, phoneUK and mobileUK based upon community feedback.
  • rename files for language_REGION according to the standard ISO_3166-1 (http://en.wikipedia.org/wiki/ISO_3166-1), for Taiwan tha language is Chinese (zh) and the region is Taiwan (TW)
  • Optimise RegEx patterns, especially for UK phone numbers.
  • Add Language Name for each file, rename the language code according to the standard ISO 639 for Estonian, Georgian, Ukrainian and Chinese (http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
  • Added croatian (HR) localization
  • Existing French translations were edited and French translations for the additional methods were added.
  • Merged in changes for specifying custom error messages in data attributes
  • Updated UK Mobile phone number regex for new numbers. Fixes #154
  • Add element to success call with test. Fixes #60
  • Fixed regex for time additional method. Fixes #131
  • resetForm now clears old previousValue on form elements. Fixes #312
  • Added checkbox test to require_from_group and changed require_from_group to use elementValue. Fixes #359
  • Fixed dataFilter response issues in jQuery 1.5.2+. Fixes #405
  • Added jQuery Mobile demo. Fixes #249
  • Deoptimize findByName for correctness. Fixes #82 – $.validator.prototype.findByName breaks in IE7
  • Added US zip code support and test. Fixes #90
  • Changed lastElement to lastActive in keyup, skip validation on tab or empty element. Fixes #244
  • Removed number stripping from stripHtml. Fixes #2
  • Fixed invalid count on invalid to valid remote validation. Fixes #286
  • Add link to file_input to demo index
  • Moved old accept method to extension additional-method, added new accept method to handle standard browser mimetype filtering. Fixes #287 and supersedes #369
  • Disables blur event when onfocusout is set to false. Test added.
  • Fixed value issue for radio buttons and checkboxes. Fixes #363
  • Added test for rangeWords and fixed regex and bounds in method. Fixes #308
  • Fixed TinyMCE Demo and added link on demo page. Fixes #382
  • Changed localization message for min/max. Fixes #273
  • Added pseudo selector for text input types to fix issue with default empty type attribute. Added tests and some test markup. Fixes #217
  • Fixed delegate bug for dynamic-totals demo. Fixes #51
  • Fix incorrect message for alphanumeric validator
  • Removed incorrect false check on required attribute
  • required attribute fix for non-html5 browsers. Fixes #301
  • Added methods “require_from_group” and “skip_or_fill_minimum”
  • Use correct iso code for swedish
  • Updated demo HTML files to use HTML5 doctype
  • Fixed regex issue for decimals without leading zeroes. Added new methods test. Fixes #41
  • Introduce a elementValue method that normalizes only string values (don’t touch array value of multi-select). Fixes #116
  • Support for dynamically added submit buttons, and updated test case. Uses validateDelegate. Code from PR #9
  • Fix bad double quote in test fixtures
  • Fix maxWords method to include the upper bound, not exclude it. Fixes #284
  • Fixed grammar error in german range validator message. Fixes #315
  • Fixed handling of multiple class names for errorClass option. Test by Max Lynch. Fixes #280
  • Fix jQuery.format usage, should be $.validator.format. Fixes #329
  • Methods for ‘all’ UK phone numbers + UK postcodes
  • Pattern method: Convert string param to RegExp. Fixes issue #223
  • grammar error in german localization file
  • Added Estonian localization for messages
  • Improve tooltip handling on themerollered demo
  • Add type=”text” to input fields without type attribute to please qSA
  • Update themerollered demo to use tooltip to show errors as overlay.
  • Update themerollered demo to use latest jQuery UI (along with newer jQuery version). Move code around to speed up page load.
  • Fixed min error message broken in Japanese.
  • Update form plugin to latest version. Enhance the ajaxSubmit demo.
  • Drop dateDE and numberDE methods from classRuleSettings, leftover from moving those to localized methods
  • Passing submit event to submitHandler callback
  • Fixed #219 – Fix valid() on elements with dependency-callback or dependency-expression.
  • Improve build to remove dist dir to ensure only the current release gets zipped up
  • Bumping version to 2.0.0pre
As usual:
  • Please post questions to the official Using jQuery Plugins Forum , tagging your question with (at least) “validate”. Keep your question short and succinct and provide code; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

Enjoy!

Support the jQuery Validation Plugin

Posted September 05, 2012 by Jörn

Validate forms like you’ve never been validating before!

Click here to lend your support to: jQuery Validation Plugin and make a donation at www.pledgie.com !

This has been the, a tad silly, tag line for the jQuery Validation Plugin for a few years now. Back in 2006, when Jörn Zaefferer started that plugin, he was still employed as a Java developer, contributing to jQuery mostly in his free time. Of the half-dozens plugins he started then, the Validation Plugin became the most succesful and is still quite popular today (builtwith.com knows about more than 300.000 websites using the plugin).

Since late 2010, when Jörn went freelance to focus on just JavaScript projects (no more Java!), maintenance of the plugin didn’t go as well as planned. Early 2012, appendTo was generous to support the project, namely with Max Lynch work through dozens of pull requests and issues, landing a total of 28 commits . Since Max went on to create his own startup, the project went rather quiet again.

This is going to change! And you can be a part of that!

Jörn is looking for donations to spend quality time on the project. The roadmap below outlines a lot of work, probably a lot more than than can be covered by the 4000€ he’s currently asking for.

But that also depends on how much people will contribute in other ways. One part of this effort is to build a community around the plugin.

How can you help?

There’s a few things you can do:

  • You can directly donate to the campaign, any amount helps.
  • You ask your friends, coworkers, boss, spouse and whoever else, to help. If you’re part of a local JavaScript meetup, ask people there.
  • You can also help with the project itself: Look at the roadmap below and see if there’s something you can help with directly or indirectly. Know a good designer who could help with logo and website design? See if you can get them in touch with me. Know a technical writer who could help with website copy and documentation? Also very welcome!

The campaign also provides a detailed roadmap for what I’m planning to do with the plugin.

Spread the word

Help us get enough donations to get this project the attention it deserves. Share it on Twitter, Facebook, G+, Orkut, in your office, local newspaper, train station, airport, parliament! Call your senator!

jQuery.ScrollTo 1.4.1 released

Posted September 04, 2012 by Ariel Flesler

Fixes

  • The plugin accepts floating numbers.
  • Using jQuery.nodeName where neccessary so that this works on xml+xhtml.
  • The max() internal function wasn't completely accurrate, now it is 98% (except for IE on quirks mode but it's not too noticeable).

Features

  • The target can be 'max' to scroll to the end while keeping it elegant.
  • The plugin works on quirks mode.

Enhancements

  • Default duration is 0 for jquery +1.3. Means sync animations.
  • Rewrote $.fn.scrollable() again. The plugin works on all major browsers (FF, IE, Safari, Opera, Chrome), on all versions, compat & quirks modes, even for iframes.
  • In addition to window/document, if html or body are received, the plugin will choose the right one.

Links

Downloads

jQuery.ScrollTo 1.4.2 released

Posted September 04, 2012 by Ariel Flesler

Fixes

  • Fixing max calculations for regular DOM elements.

Features

  • The plugin support percentages as target ('50%' or {top:'50%', left:'45%'}).
  • Exposed the max() calculation as $.scrollTo.max.

Enhancements

  • Renamed $.fn.scrollable to $.fn._scrollable to avoid conflicts with other plugins.

Links

Downloads

jQuery.ScrollTo 1.4 released!

Posted September 04, 2012 by Ariel Flesler

Fixes

  • Fixed the problem when scrolling the window to absolute positioned elements on Safari.
  • Fixed the problem on Opera 9.5 when scrolling the window. That it always scrolls to 0.

Features

  • Added the settings object as 2nd argument to the onAfter callback.
  • The 3rd argument of scrollTo can be just a function and it's used as the onAfter.
  • Added full support for iframes (even max scroll calculation).
  • Instead of $.scrollTo, $(window).scrollTo() and $(document).scrollTo() can be used(even for iframes).
  • Added $().scrollable() that returns the real element to scroll, f.e: $(window).scrollable() == [body|html], works for iframes too.

I rewrote the scroll limit calculations part, in order to fix the 2 bugs. If you notice any problem, please report.

This version should be perfectly compatible with the latest versions of SerialScroll and LocalScroll .

I tested this only with jQuery 1.2.6 (from trunk) but it should work well even with pretty old versions of jQuery.

Tested my demos and some iframe experiments on IE 6/7, FF 2/3, Safari 3 and Opera 9.2/5. All worked as expected. Enjoy!

Links

Downloads

Redefining the Introduction to Computer Science

Posted August 14, 2012 by John Resig

I’m incredibly excited to take this opportunity to announce a new project that I’ve been leading here at Khan Academy: Khan Academy Computer Science .

We’re releasing a completely new platform that targets people with no programming knowledge and gives them an engaging and fun environment to learn in.

Over everything else we wanted to emphasize creativity and exploration and make it approachable for people of all ages, including young kids.

Sal Khan and I recorded a video giving a good introduction to what we’re releasing:

To get started feel free to visit the Khan Academy Computer Science site:

http://www.khanacademy.org/cs

Explore, play around, and build something!

Jamie Wong, who worked on the CS platform this summer, has also written up a blog post on his experience developing the platform.

Methodology

Earlier this year I was working on an iteration of the CS platform which was heavily focused on structured curriculum leading towards exploratory projects.

Until I saw Bret Victor ‘s mind-blowing talk on using a responsive programming environment .

After watching that video I couldn’t shake the feeling that what he presented was a fundamentally different way of approaching how to interact with, and learn how to, code.

In an environment that is truly responsive you can completely change the model of how a student learns: rather than following the typical write -> compile -> guess it works -> run tests to see if it worked model you can now immediately see the result and intuit how underlying systems inherently work without ever following an explicit explanation.

When code is so interactive, and the actual process of interacting with code is in-and-of-itself a learning process, it becomes very important to put code front-and-center to the learning experience.

Rather than starting Computer Science education off by explicitly teaching how a computer works or fundamental programming concepts (like variables, logic, control structures, etc.) you put the student into code of graduated complexity and encourage them to manipulate, explore, and write their own programs.

Once they start to explore and figure out things for themselves then they can begin to dig into all the explanatory tutorials and documentation that are provided to clarify how things work.

The desire to learn and understand can be a powerful accelerant for students and it’s something that is completely missing from almost all Computer Science education .

When I look back at how I became interested in programming, or ask other programmers about how they started to program, the answer is very frequently: “I was given a [Basic/QBasic/Python] compiler and a bunch of programs and I wanted to understand how it all worked so I could write my own!” It was only after digging in to the code that the student wanted to understand how to tackle certain programmatic challenges – but they then did so with great gusto!

The Khan Academy Computer Science program is a distillation of this process into it’s purest form: Directly encouraging experimentation, exploration, and creativity as a direct gateway to deeper learning.

How do we teach?

On the site we provide dozens of programs, at a variety of skill levels, across a number of disciplines (including art, mathematics, and science). We wanted students to find the niche programs that could capture their excitement while also being able to provide a direct line from normally theoretical concepts (such as algebra, geometry, or physics) towards direct evidence of their utility in a tangible medium that the student can control.

We provide a number of tutorials that cover concepts that come up frequently in the programs that we’ve developed (from programming concepts like variables and conditionals to other concepts inherent to the medium such as drawing and animation). These tutorials should cover most of the questions that students have when they’re just beginning to program and can be accessed at a student’s leisure.

I’ve talked before about how I think that JavaScript, and specifically learning how to code in-browser, is inherently a better way of learning. Reducing the complexity of getting started down to zero will result in more people learning. Additionally the ubiquity of JavaScript only serves to educate people in a language that will be generally useful.

I also feel that learning how to code in an environment where the output is visual and highly enticing can better excite the student towards wanting to produce, and thus learn, more. I feel that purely textual coding environments (or coding environments that favor textual output over visual output) serve as a highly uninteresting introduction to programming.

At a fundamental level we want the students using the platform to be self-directed learners, choosing to drive the direction of their education in a way that best suits their interests.

We’ve taken some steps to provides students with some level of possible direction which they could follow, if interested. For example when viewing an introductory program that only does basic drawing we encourage the student to explore variables or animation — ways of bringing their program “to life” which simultaneously getting them excited about attempting to learn those, comparatively, complex subjects.

We already have a number of programs for students to explore, and we will be adding many more (highlighting some of the best from the community as well). With that being said we don’t want to be the sole arbiter of programs that a student might find to be interesting. For this reason we’re working to put community, sharing, and collaboration as pillars of the platform.

We want students to work up to the point at which they feel comfortable writing their own projects. We’ve already seen some pretty phenomenal output from both people here at Khan Academy and from middle-school-aged students who’ve never programmed before.

Over this past summer we held a number of “Discovery Lab ” sessions at Khan Academy in which kids of roughly middle school age did a number of learning activities. We had the opportunity to watch them interact with the Computer Science content and were blown away with what they created. In the first hour they were designing and drawing their own characters, in the second they had added in variables and were starting animations, by the end of the third hour they had functional draw loops and were adding in logic to control the animations.

We’ve never seen students of that age progress so quickly through such challenging concepts. It was noted that they were moving faster than most college age students taking a normal intro Computer Science course.

One project that I particularly enjoyed was made by a student who really loved Minecraft. He designed some characters from the game (drawing them using a number of points and rectangles) and then added in some user interaction. He made it so that you could control the the position of a creeper by moving your mouse, as it came closer to “Steve” he would start to hiss and blink, upon hitting Steve he would explode into a firey cloud. This was done over the course of maybe four hours and two days.

To say that I’m excited to see how people are going to use this platform is an understatement.

Coding Environment

The environment is built around a two-panel view: The left being an Ace editor and the right being a canvas.

All of the user’s code is written using JavaScript and uses Processing.js to generate all the graphics.

All code is executed in real-time. Not only is the code re-run (which is relatively easy to do, just re-evaling the code) but the code that you change is live dynamically injected into the runtime — this gives you the ability to change variables, colors, or even functions on the fly without the program ever restarting.

We did a lot to try and take advantage of the real-time nature of the environment, giving the user all sorts of tools to adjust the code, and thus the state of the program as well.

We have a number picker:

We have a color picker:

and we even have an image picker (using images from the always-excellent Lostgarden.com ):

We’ve also put a lot of work into the error correction. We build off of the existing linting that we do to try and provide extra levels of hinting. We do spelling correction, provide argument suggestions, and try to make suggestions for common beginner mistakes.

In our experience students who’ve never programmed before can be left unattended using this environment and be able to resolve almost all of their issues via the error hints or the tutorials.

As it turns out it’s really, really , hard to build the real-time execution environment that Bret Victor proposed, in practice — even harder in a browser. I plan on writing many posts about the nuts-and-bolts of the implementation when we release the code-and-editor as Open Source (which should be soon).

To make the environment we have to use a lot of features that only the latest browsers support. For this reason we are only actively supporting Chrome, Firefox, Safari, and IE 9+. Chrome, Firefox, and Safari will have the best experience as they also have Web Worker support (which we make extensive use of).

Thankfully we’re able to make this hard call as less than 6% of our user base fails to match the above criteria — and that number is quickly shrinking.

Side note: One area of the implementation that would benefit from an Open Source library is some form of in-browser, pure-JavaScript, ECMAScript 5 linter. We use JSHint right now and we’d really appreciate being able to enforce true strict mode (JSHint’s strict mode support is rather limited in nature).

Collaboration and Community

With the Khan CS platform we wanted to provide an environment that effectively mimicked the best aspects of great programming communities like Github .

Students can always see the code associated with a project and it’s always displayed next to the output. Students can change any code they see and and save it to their own personal account (aka “forking” in the Github parlance).

(Note the authorship details and the “Based on” link with screenshot that shows up below a project that has been “forked” from another project.)

Community feedback and discussion is also large part of the benefit that we hope students will be able to derive from the platform. Students will be able to solicit feedback from others and have discussions within the context of their code. We’re not to the point of having line-level comments yet but we hope the initial discussion functionality will be very useful to everyone using the site.

To a large degree the Khan Computer Science platform is influenced by the Open Source communities that I’ve participated in: All the code is open, experimentation is encouraged, and feedback is easily provided. I feel that this particular environment is highly conducive to learning as you can easily see many ways of tackling a problem. You can also get feedback on your personal attempts, creating a tight feedback loop.

(I should note that we do have versioning baked in to the system as well but we haven’t exposed it yet, though probably will at some point.)

We also really wanted students to feel excited about sharing their work with others. We provide the ability to share it through traditional social media (Facebook, Twitter, and email) but also on the site and through their profile.

On a student’s profile they have the ability to choose some explorations that they wish to explicitly share with others. We want students to take pride in their best work and feel open to sharing it with the world.

Tutorials and Next Steps

While students exploring the content of the platform will certainly learn some things simply by exploring and manipulating code, we wanted to go a step further and provide tutorials and a clear narrative to help students better understand some of the complex subject matter that they’re seeing.

The primary vehicle for learning is through the tutorials on the site. These are unique in that they both behave like a normal code editor but also as a “video” player. All of the tutorials include audio walkthroughs (playing live from Soundcloud using their API ), combined with live playback from the presenter, right in the code editor itself.

We wanted to have the playback take place directly in the editor to try and provide an experience for the student that was more immediate and tangible. Producing hard-coded video explanations or forcing the student to walk through step-by-step written instructions is both tedious and lacks interactivity. With this playback mechanism the student will be able to see the results live, exactly as they would always run in the editor, while also being able to pause the playback and manipulate, or copy, the code that they see. This ability to dig into the meat of a tutorial should serve to deepen, and reinforce, a student’s understanding of the subject matter.

In addition to the tutorials we have a large amount of documentation on Processing.js and JavaScript, all of which is written up and available in a code editor (again, for further exploration). All documentation is available on a dedicated page and beneath every code editor, making it an easy reference for students.

Next to many of the projects that are on the site we also provide some suggested “Next Steps” that the students can follow for some deeper engagement and learning.

We don’t explicitly evaluate the student’s work here and instead we encourage them to share their work with others, providing an external motivator to try and write the best possible code they can. With the active and excited Khan Academy community that already exists students will be able to receive constructive feedback on their work and make a number of improvements thereon.

One question is obviously: How much “Computer Science” do we actually teach? Obviously, right now we’re not teaching very much in the way of traditional Computer Science content, we’ve placed far more focus onto the platform and feel that a lot can be gained from just what we’ve already built. We’re still very early on in the production of content and will be producing much more, of increasing complexity, over the upcoming weeks and months.

We decided that it was much more fruitful for us to tackle the most challenging problem that exists with Computer Science education first: Getting people excited about programming. If we can get people excited about programming, and build (or point them to) the resources they need to learn more then we will have been successful.

Eventually I think we’ll work to effectively replicate the materials one typically finds in a “Computer Science 101″ but in a way that is far more engaging and self-paced than what you would find at a traditional university.

So what’s next? We want to work on providing even more direction and tooling around students writing larger projects. We want to provide easy APIs around storage, network connectivity, and dependencies that will allow for some fascinating projects. Additionally we want to improve peer-to-peer and mentor-student collaboration, finding ways of pairing struggling students with skilled developers. Finally we want to produce a lot more content of a wide range of difficulties and topics.

We’re only just getting started and how the community responds to this release will largely help to drive the direction of the platform as a whole. Feedback is most welcome!

Thank Yous

This is the culmination of a bunch of work by a number of people and I want to take this opportunity to thank them — without them this project would not have happened and would not have come out as well as it did.

Most importantly I want to thank Jamie Wong and Jessica Liu — both of whom worked this summer on the Computer Science platform and have both made tremendous contributions in ways that I couldn’t have even hoped for.

Jamie primarily worked on the Khan CS platform, providing a superb level of quality and scalability that we’ll be enjoying for a long time. He provided contributions above-and-beyond what was needed and even helped to improve some of our development processes at Khan Academy. His expertise has been a massive boon to the project, quickly escalating it to encompass functionality that we didn’t even hope we’d be able to provide. In the short time he’s been with the company he’s already made a tremendous impact upon the organization.

Jessica worked on creating Computer Science tutorials, meticulously researching methodologies and iterating after gathering user feedback. The structure and content of the Computer Science curriculum is largely of her design (if you view some of the CS tutorials you’re sure to enjoy much of her expertise and wit). She also worked on improving the usability of the editor and the curriculum, making it far easier for newbies to get up to speed. Her innate understanding of a new programmer’s mind, combined with her ability to execute on a solution that will aide them has made the platform an incredibly effective tool for self-paced learning.

I strongly hope to have the opportunity to work with both of them in the future.

I also want to thank everyone at Khan Academy for their input into the design process and their help in creating the awesome projects you see on the site. I especially want to thank Sal Khan, Shantanu Sinha, Ben Kamens, Jason Rosoff, Ben Komalo, Ben Alpert, Tom Yedwab, and Mathias Hiron for their help and advice in making the platform what it is today.

I also want to thank the teachers and students at the Khan Academy Discovery Lab for being such willing, and excited, participants in experimenting with the Computer Science platform. Your feedback was instrumental in identifying many issues that we were able to make much better as a result.

And so, on that note, I hope you will all enjoy the new Khan Academy Computer Science platform!

Secret Omens: Book Update

Posted July 11, 2012 by John Resig

Jeff Atwood wrote up a post today on the merits of writing a technical book in this day-and-age and specifically called out my past post on programming book profits and my work-in-progress Secrets of the JavaScript Ninja .

I wanted to give a brief status update on the book and how it’s going. I started the book in early 2008 and was actually quite productive, finishing nearly the entire book that year (with some missing gaps that I fixed up in 2009). There was some work left to do to make it a better book but, honestly, I got caught up in coding and stopped focusing on writing. I had to prioritize my time and I chose to prioritize doing more development and focusing on my personal life. Some time last year Manning brought on a co-author, Bear Bibeault, to finish the book and get it out the door. He’s done a bunch of revision bringing it up-to-date and just the other week I finally wrote the preface. It’s in final revisions now and should be out-the-door very soon . This is a huge relief for me and it’s great that there’s one less thing to worry about.

To the point of Jeff’s post, I would absolutely not write a technical book again. It’s a tedious process and unless you LOVE writing and are really good at it (like Nicholas Zakas or Dave Flanagan ) then I suggest that you stick with the medium that is truly successful: Writing long-form articles/blog posts and possibly spinning them off into purchasable ebooks. (As an example, I’d point to Juriy Zaytsev and Peter-Paul Koch both of whom could get any JavaScript position in the world purely based upon the quality of their articles and sites, without ever having written a book.)

I realized at some point in late 2008 that that’s really what I should’ve done with Secrets of the JavaScript Ninja but I was already neck-deep in the book with most of it complete. Ironically working on the book (or not working on it, however you look at it) actually compelled me to NOT blog more as every time I wanted to write a technical blog post I was forcing myself to make the decision “I’m writing about 1000 words on a technical matter, shouldn’t this just be going towards my uncompleted book?” and would just end up writing nothing as a result.

I do feel bad for, and apologize to, the people that pre-ordered hard copy version of my book over the years only to have to wait on a time scale comparable to George R. R. Martin’s writing schedule. Amusingly the book has been extremely successful as a pre-order e-book at Manning.com – it’s the best-selling MEAP book of all time. I’ve gotten numerous emails from readers who’ve gotten enormous benefit from the book, even in it’s rough form, and this has pleased me greatly.

I’m excited to finally have this book be out in the “wild”, as it were. It’s no longer (as Jeff put it) “permanently unfinished”.

I’ve included the preface from my book below, to give some more detail:

When I started writing Secrets of the JavaScript Ninja four years ago, in early 2008, I saw a real need: There were no books providing in-depth coverage of the most important parts of the JavaScript language (functions, closures, and prototypes) nor were there any books that even attempted to cover writing truly cross-browser code. Unfortunately it appears as if the situation has not improved very well, which is truly surprising.

More and more development energy is being put into new technologies (such as the ones coming out of HTML 5 or the new versions of ECMAScript). There isn’t a point to diving into new technologies, or using the hottest libraries, if you don’t have a proper understanding of the fundamental characteristics of the JavaScript language. While the future for browser development is very bright the reality is that most development needs to make sure that code continues to work in the majority of browsers and for the majority of potential users.

Even though this book has been under development for a long time, thankfully it is not out of date. The book has been given a solid set of revisions by my co-author Bear Bibeault. He’s gone through and made sure that the material will continue to be relevant for a long time to come.

A major reason why this book has taken so long is largely due to the experience that I was drawing upon to write the material for the later chapters on cross-browser code. Much of my understanding of how cross-browser development happens in-the-wild has come from my work on the jQuery JavaScript library. As I was writing the later chapters on cross-browser development I realized that so much of jQuery’s core could be written differently, optimized, and made capable of handling a wider range of browsers.

Perhaps the largest change that came to jQuery, as a result of writing this book, was a complete overhaul from using browser-specific sniffing to using feature detection at the core of the library. This change made it so that jQuery could be used almost indefinitely, without assuming that browsers would always have specific bugs or be missing specific features.

As a result of these changes jQuery directly anticipated many of the improvements to browsers that have come during the past couple years: Google released the Chrome browser, the number of useragents have exploded as mobile computing has increased in popularity, Mozilla, Google, and Apple have gotten into a browser performance war, and Microsoft has finally started making substantial improvements to Internet Explorer. It can no longer be assumed that a single rendering engine (such as WebKit or Trident, in Internet Explorer) will always behave the same way. Substantial changes are occurring rapidly and are spread out to an ever-increasing number of users.

Using the techniques outlined in this book, jQuery’s cross-browser capabilities provide a fairly solid guarantee that code that you write with jQuery will work in a maximal number of browser environments. This guarantee has led to explosive growth in jQuery over the past four years, with it now being used in over 57% of the top 10,000 websites on the Internet, according to Builtwith.com.

The portions of this book that cover features that are relatively un-changing, such as code evaluation, with statements, and timers are continually being used in interesting ways. There are now a number of active programming languages that are built on top of, or compiled to, JavaScript: Such as CoffeeScript or Processing.js. These languages require complex language parsing, code evaluation, and scope manipulation in order to work effectively. While dynamic code evaluation has been maligned due to its complexity and potential for security issues, without it we would not have had the CoffeeScript programming language – which has gone on to influence the upcoming ECMAScript specification itself.

I’m personally making use of all of these features, even today, in my work at Khan Academy. Dynamic code evaluation in the browser is such a powerful feature: You can build in-browser programming environments and do crazy things like inject code into a live runtime. This can result in an extremely compelling way to learn computer programming and provide all sorts of capabilities that wouldn’t be possible in a traditional learning environment.

The future for browser development continues to be very strong and it’s largely due to the features encapsulated in JavaScript and in the browser APIs. Having a solid grasp of the most crucial parts of the JavaScript language, combined with a desire for writing code that’ll work in many browsers, will result in your code being elegant, fast, and ubiquitous.

10 Things More Valuable than Money in my Bootstrapped Startup

Posted May 08, 2012 by mikehostetler

In a startup, resources are required to keep the lights on, pay people, and pursue the vision for why a startup was created in the first place. Recently, I've seen more and more examples of where the pursuit of money becomes the focal point, thus ignoring the reasons why the organization was created in the first place.

When we created appendTo, we started the way many founders do, with just a dream. The path hasn't been easy and along the way we've fought many battles to keep our dream alive, many having to deal with money. As we've grown (we're at 17 full time employees), we've spent long hours discussing the fact that money is important, but it isn't the point.

Figuring out what the "point" actually is can be difficult. It's a process of self-discovery about what matters to the founders and the employees.

The list below is what matters to me, my partner and to appendTo. Your list may be different. The point in sharing our list is simply to encourage you to make a list. You may surprise yourself.

  • Ability to be Patient - Patience is a vastly underrated commodity. Ignore it at your own peril.
  • Ability to say No - Saying "No" drives focus. Focus or Die.
  • Ability to go home at 5 - As a responsible founder, knowing the business operates smoothly without me is invaluable.
  • Ability to nurture relationships - People are valuable but Relationships are even more valuable. Nurturing them takes time and effort.
  • Ability to contribute to OSS at my discretion - We stand on the shoulders of OSS giant and consistently giving back is the right thing to do.
  • Ability to deliver value every day - Knowing I've delivered value every day keeps me going.
  • Ability to keep learning - The world changes too fast to stop learning.
  • Ability to work from anywhere - Geographical constraints are artificial limitations in 2012.
  • Ability to pursue my dream while having a life - I have a family. Startups often require immense cost to family life, which I don't have to pay.
  • Ability to never stop dreaming - I'm a dreamer. I will never stop dreaming and wouldn't last long where dreams were sacrificed to pursue short term revenue goals.

All of this is possible because of the awesome people here at appendTo. This post is dedicated to them!

XMLWriter for Javascript

Posted February 17, 2012 by Ariel Flesler

Introduction

This is a Javascript class, based on .NET's XMLTextWriter .

This is not a port, but a reduced and adapted version.



Constructor

The constructor accepts 2 optional arguments: encoding, and version. You call it like this:
var
 xw = new
 XMLWriter( 'UTF-8'
, '1.0'
 );

Methods

Class instances have the following methods:
  • writeStartDocument([ bool standalone ])
    Opens a new document, must be call on start, if standalone is specified, standalone="true/false" will be added to the header.
  • writeEndDocument()
    Closes the active document, it's not really mandatory to call it.
  • writeDocType( string declarations )
    Adds a doctype to the document, can be called at anytime. If specified, a doctype will be included in the generated xml, in this form:

    <!DOCTYPE root-element declarations>
  • writeStartElement( string name [, string ns ] )
    Creates a new node element with this name, and it becomes the active element. A namespace can be specified.
  • writeEndElement()
    Closes the active element and goes up one level.
  • writeAttributeString( string attr, string value )
    Adds an attribute to the active element.
  • writeString( string text )
    Adds a text node to the active element.
  • writeElementString( string name, string txt [, string ns ] )
    Shortcut method, creates an element, adds the text and closes it.
  • writeCDATA( string text )
    Adds a text node wrapped with CDATA, to the active element.
  • writeComment( string text )
    Adds a comment node to the active element.
  • flush(): string
    Generates the XML string and returns it.
  • close()
    Closes the writer and cleans up.
  • getDocument()
    Generates a real XMLDocument from the writer. This method doesn't belong to the original class.

Formatting

You can choose whether the generated XML is formatted or not, and how. You can modify the following options for each instance or from XMLWriter.prototype to affect them all:
  • encoding
    'ISO-8859-1' by default.
  • version
    '1.0' by default.
  • formatting
    'indented'(default) or 'none'.
  • indentChar
    '\t' by default, char to indent.
  • indentation
    # of chars added per level, 1 by default.
  • newLine
    '\n' by default, char to separate lines.
If you choose formatting = 'none', you don't need to modify indentChar, indentation or newLine.



Links

Downloads

Image Similarity Search Wanted

Posted February 13, 2012 by John Resig

I’ve been working on a few projects in my spare time and one service, in particular, would greatly benefit from a high quality image similarity search.

I’ve been trying a number of the Open (and non-Open) Source tools (a great list of which is on Wikipedia here ). Thus far none of the tools that I’ve found are of high-enough quality to warrant further pursuit. They either do simple color comparison, basic wavelet/outline comparison, or some form of hashing – none of which appears to work very well beyond basic images. Some of the best algorithms are either caught up in University research programs (generally unreleased) or are available as corporate search engines.

In an ideal world I’d like something with the quality of TinEye (I’d even be open to using TinEye’s commercial services but they haven’t gotten back to me as of yet – I suspect that they’re mostly interested in dealing with large corporate clients).

In short: Does anyone have a lead on a high quality image similarity search tool (using Content-Based Image Retrieval )? I’m open to Open Source, closed source, or even paid API service – as long as it works well.

Note: I’m looking to use this on a private collection of images, so a service like Google Image Search (or TinEye’s normal commercial API) are not suitable alternatives – they both search images on the open web.

JavaScript as a First Language

Posted December 21, 2011 by John Resig

At Khan Academy we’ve been investigating teaching Computer Science to students in some new and interesting ways. The most interesting aspect of which is that we’re likely going to be teaching them JavaScript as their first language.

We’re in a very unique position as we’re primarily aiming to teach students who’ve been through our previous math and science-centric curriculum . Because of this we can create some rather compelling exercises and projects that never would’ve been feasible otherwise.

The prospect of teaching the JavaScript language as a first language is actually really exciting. Teaching prototypal inheritance to experienced classical-inheritance-using developers is normally rather frustrating (and results in many libraries springing up attempting to replicate the classical style of inheritance in JavaScript, which is a whole realm of weirdness in-and-of itself). Teaching prototypal inheritance to someone who has never seen any form of inheritance before will decidedly be an easier task. The same goes for learning functional programming. JavaScript is a great language for experiencing functional programming and can be a major focus of our curriculum as a result.

As we’ve begun to look at the prospect of JavaScript-as-a-first-language a number of obvious warts stick out (as is obvious to anyone who has worked with JavaScript for any duration). To make sure that general warts don’t crop up we will be using some form of linting (either JSLint or JSHint or similar) in the code editor to give the users contextual information on what’s happening with their code and why they should be writing their code in a certain way.

We want to go beyond basic syntax tweaks though and find ways of using the language that’ll result in an easier learning experience. In particular there are two changes which will likely result in a much simpler on-ramp to learning.

Note: These particular recommendations really only make sense if you’re teaching JavaScript to someone who has never seen the language before and is really only programming with a set of specific, well-coded, libraries. Obviously more will have to be taught in order bring the students up to the level of “see any random piece of cross-browser JavaScript code and understand what it does.”

Type Coercion

Type coercion is just a complete mess, as many many others have pointed out and as what Douglas Crockford typically teaches, as in JavaScript: The Good Parts .

It might make sense to discuss it far later in the education cycle… like after learning about prototypes, functional programming, and closures. Basically after everything that’s actually important.

  1. name === "John"

The first change that I’m recommending is that the students will only ever see, and use, === (and !== ). While using ‘== ‘ does have the advantage of being syntactically shorter there is so much type coercion baggage attached to it as to make it an exercise in futility to try and teach early on in the learning of programming.

The one exception that might be worthwhile to teach later on is the case in which you wish to see if a variable contains a null or undefined value. This can be done easily with a simple someVar == null check and is likely the one useful case of == . (Another noted exception is the browser bug in IE where === checks against Window objects will always return false, but it’s unlikely that we’ll cover such specific browser issues in our curriculum.)

Falsy Values

For the same reasons that == can be messy, so can falsy values. Enforcing strict boolean checks would result in less edge cases but would certainly result in longer code. Perhaps education of falsy values can be limited to booleans, null, and undefined with number and string falsy values left for a later exercise.

Function Declarations

Perhaps the most interesting change that we can make is a rather subtle one, but it’s eschewing normal function declarations for creating anonymous functions and assigning them to a variable.

  1. // Don't do this:
  2. function getData() { }
  3.  
  4. // Do this instead:
  5. var getData = function() { };

There are a number of good habits that are instilled when you use this particular technique.

  • Makes it easier to understand “functions as an object”. I’ve found that when you show new developers a function being assigned to a variable it suddenly becomes much more obvious that a function is actually an object and can be manipulated as such (and that a function can be passed as an argument to another function). Thus students are advanced along the path towards a better understanding of functional programming.
  • It enforces good semicolon habits. Traditional function declaration is the only situation in which semicolons aren’t needed (save for conditional statements and loops, naturally) and it makes it much more obvious when they’re required all the time.
  • Doesn’t have much of the baggage traditionally associated with functions and scope .

Block Scope

This is the remaining area that’ll certainly be a challenge for any introductory student to understand and yet I don’t see a particularly good solution here. The issue of variables declared within for loops hoisting up is more than enough to make most developers heads spin. I’ll have to see if we can’t come up with some intuitive ways of explaining how variable declaration works (and combining it with vigilant lint enforcement) rather than having a purely technical solution.

(While (function(){ ... })(); is a solution I’m skeptical that we’ll be able to teach that early-enough on as to make it worthwhile.)

JavaScript as a First Language

It should be noted that while we’re starting with JavaScript as a first language – largely due to its ubiquity, desirability in the larger workforce, lack of prior installation requirements, and ability to create something that’s easy to share with friends – we’re not going to be myopic and only focus on JavaScript. There are so many things that can be learned from other languages, not to mention entire skillsets that aren’t terribly relevant to in-browser JavaScript, that it behooves us to try and bring as much of them into our curriculum as possible.

I talk a little bit more about our choice to use JavaScript and some of the browsers that we’ll want to support in our development in the following video :

By all accounts I want to try and avoid any features that would cause cross-browser weirdness to spring up. As a result we’ll be making extensive use of libraries (for drawing to a canvas or manipulating the DOM) and using only JavaScript language features that work consistently in the browsers that we end up supporting.

Using jQuery’s .pushStack() for reusable DOM traversing methods

Posted December 20, 2011 by Karl Swedberg

The .pushStack() method has been in jQuery since before version 1.0, but it hasn't received a whole lot of attention outside of core developers and plugin authors. While its usefulness may not be immediately apparent, it can come in really handy in some situations, so I'd like to take a quick look at what it does, how it works, and how we can use it.

pushStack Basics

At its most basic level, the .pushStack() method accepts an array of DOM elements and "pushes" it onto a "stack" so that later calls to methods like .end() and .andSelf() behave correctly. (Side note: As of jQuery 1.4.2, you can pass in a jQuery object instead of an array, but that isn't documented and jQuery itself always uses an array, so that's what we'll stick to here.)

Internally, jQuery uses .pushStack() to keep track of the previous jQuery collections as you chain traversing methods such as .parents() and .filter() . This lets us traverse through the DOM, do some stuff, "back up" to previous collections within the same chain using .end() , and then do something else. Here is a somewhat contrived example:

JavaScript:

  1. // select some divs
  2. $( 'div.container' )
  3.   // find some spans inside those divs and add a class to them
  4.   .find ( 'span' ) .addClass ( 'baby' )
  5. // pop those spans off the "stack",
  6. // returning to the previous collection (div.container)
  7. .end ( )
  8.   // add a class to the parent of each div.container
  9.   .parent ( ) .addClass ( 'daddy' ) ;


Because .find() returns the result of a .pushStack() call to keep track of the previous collection (as does .parent() ), we can use .end() in the above example to return to the container divs.

Using pushStack for Fun and Profit

So, this is great for jQuery, but what can .pushStack() do for me and my code? Well, it can help me write specialized DOM traversal plugins that act just like jQuery's own traversal methods. In other words, I can stop chaining the same sets of traversal methods together and instead write a reusable function that still works with with .end() and all that. For example, let's say I often have a need to find an element's grandparent. While I could write $('#myElement').parent().parent() every time, it might be nice to just be able to write $('#myElement').grandparent() instead. A naïve way to write a grandparent plugin would look like this (changing the method name to "grandpa" for this example):

JavaScript:

  1. // NOT recommended!
  2. ( function ( $) {
  3.   $.fn .grandpa = function ( ) {
  4.     return this .parents ( ) .parents ( ) ;
  5.   } ;
  6. } ) ( jQuery) ;


The problem here is that two new jQuery object instances are added to the stack. So, let's see what happens when we use it:

JavaScript:

  1. // The DOM looks like this:
  2. // <div class="grandpa">
  3. //  <div class="pa">
  4. //    <div class="child son"></div>
  5. //  </div>
  6. // </div>
  7.  
  8. var elem = $( 'div.son' ) .grandpa ( ) .end ( ) ;
  9. $( 'div.son' ) .text ( elem.attr ( 'class' ) ) ;


Without seeing the plugin, we would expect to see "child son" inserted into <div class="son"> , but "pa" is inserted instead. Each .parent() call in the plugin adds to the stack, so using .end() only pops the second one off.

If we use .pushStack() instead, however, we can achieve the expected behavior:

JavaScript:

  1. ( function ( $) {
  2.   $.fn .grandma = function ( ) {
  3.  
  4.     var els = this .parent ( ) .parent ( ) ;
  5.     return this .pushStack ( els.get ( ) ) ;
  6.   } ;
  7. } ) ( jQuery) ;


Within a plugin function, one that is a method of $.fn , the this keyword refers to the jQuery object; therefore, the els variable refers to a jQuery object, as well. To convert it to an array, we use jQuery's .get() method, and we pass that array to .pushStack() . Let's see if .grandma() works any better than .grandpa() .

JavaScript:

  1. // The DOM looks like this:
  2. // <div class="grandma">
  3. //  <div class="ma">
  4. //    <div class="child daughter"></div>
  5. //  </div>
  6. // </div>
  7.  
  8. var elem = $( 'div.daughter' ) .grandma ( ) .end ( ) ;
  9. $( 'div.daughter' ) .text ( elem.attr ( 'class' ) ) ;


Here, "child daughter" is inserted, which means that .end() works as expected, changing the jQuery collection from the result of .grandma() to the result of $('div.daughter') . So, we've just successfully written a DOM traversal plugin, albeit a very simple one.

The Simplest DOM Traversal Methods

If the plugin only uses one DOM traversal method, then .pushStack() isn't really necessary. The HTML5 data filter plugin written by Elijah Manor illustrates this point nicely:

JavaScript:

  1. ( function ( $) {
  2.   $.fn .filterByData = function ( type, value ) {
  3.     return this .filter ( function ( ) {
  4.       return value != null ?
  5.         $( this ) .data ( type ) === value :
  6.         $( this ) .data ( type ) != null ;
  7.     } ) ;
  8.   } ;
  9. } ) ( jQuery) ;


Only one new jQuery collection is added to the stack, via .filter() , so using .end() simply pops that one off, and our job is done.

Filtering grandparents

For the sake of completeness, it would be nice for this DOM traversal plugin to allow optional "filtering" of the parent and grandparent elements. After all, jQuery's .parent() and .parents() allow filtering. For example, if I were to write $('div.child').parent('.daddy') , the jQuery collection would only contain an element if div.child had a parent element and if that parent had a class of "daddy."

There are plenty of reasonable ways one could include the filters, but for my purposes I'm going to have a .grandparent() method optionally accept two arguments. If only one argument is provided, it will filter the grandparent element only; if two are provided, the first will filter the parent and the second will filter the grandparent. Here is the full plugin plugin:

JavaScript:

  1. ( function ( $) {
  2.   $.fn .grandparent = function ( parentFilter, grandFilter ) {
  3.     if ( ! grandFilter ) {
  4.       grandFilter = parentFilter;
  5.       parentFilter = undefined;
  6.     }
  7.  
  8.     var els = this .parent ( parentFilter ) .parent ( grandFilter ) ;
  9.     return this .pushStack ( els.get ( ) ) ;
  10.   } ;
  11. } ) ( jQuery) ;


Finally, we have a nice .grandparent() plugin that adheres to the contract set by other jQuery DOM traversal methods—one that works with both filters and the .end() method. Here is what it could look like in use.

Vector math basics to animate a bouncing ball in JavaScript

Posted December 09, 2011 by Jörn

Vector math is pretty much essential when you want to do any kind of physics simulation, be it as simple as a bouncing ball. While my goal originally was to implement a flocking simulation (like birds flying close to each other, but not too close), the lack of math skills led me to build a bouncing ball simulation first.

At the same time, I wanted to see what Khan Academy is all about. Turns out they have lessons on vector math, but there’s very little on vectors specifically. There are two lessons on vector basics, where this second one is a lot more practical . There are also two exercises, one for addition of vectors, one for scaling . Both are pretty easy and you should be done within a minute if you watched the video.

With that knowledge under your belt, let’s look at some practical application, the aforementioned bouncing ball. To start, take a look at the demo and play around with it, there are some instructions at the top.

You can find the source code for that demo on GitHub, here is the main file for the bouncing balls demo . I’m not going to discuss the Point and Vector classes that this uses, though you should take a look . They just implement adding and scaling of vectors, and calculating a vector based on two points. Let’s walk through the code:

var GRAVITY = new Vector(0, 9.81);
var FRICTION = 0.85;
var world = {
	x1: 0,
	y1: 0
};
$(window).resize(function() {
	world.x2 = $(window).width();
	world.y2 = $(window).height();
}).trigger("resize");

This defines two constants, GRAVITY and FRICTION, which we’ll use later to affect simulated objects. GRAVITY is a vector pointing downwards, where the second component represents the 9.81 meters per second, while the first component is zero. FRICTION is used in collisions later, and completely arbitrary.

The world object is also used in collision detection, and represents the dimensions of our 2d world. It starts at 0/0 in the left top corner, and ends in the right bottom corner. We bind a resize handler on window to update this calculation, that way collisions happen within the browser window, no matter how big it currently is.

Next up is the definition of our Ball class:

function Ball() {
	this.position = new Point(200, 200);
	this.output = $("<div>").addClass("dot").appendTo("body");
	this.velocity = new Vector(-5, 0);
}
Ball.prototype = {
	remove: function() {
		this.output.remove();
	},
	move: function() {
		// apply gravity
		this.velocity = this.velocity.add(GRAVITY.scale(0.1));

		// collision detection against world
		if (this.position.y > world.y2) {
			this.velocity.x2 = -this.velocity.x2 * FRICTION;
			this.position.y = world.y2;
		} else if (this.position.y < world.y1) {
			this.velocity.x2 = -this.velocity.x2 * FRICTION;
			this.position.y = world.y1;
		}
		if (this.position.x < world.x1) {
			this.velocity.x1 = -this.velocity.x1 * FRICTION;
			this.position.x = world.x1;
		} else {
			if (this.position.x > world.x2) {
				this.velocity.x1 = -this.velocity.x1 * FRICTION;
				this.position.x = world.x2;
			}
		}

		// update position
		this.position.x += this.velocity.x1;
		this.position.y += this.velocity.x2;

		// render
		this.output.css({
			left: this.position.x,
			top: this.position.y
		});
	}
};

This defines a Ball constructor, which initializes a new Ball at some arbitrary position, with some velocity to the left. It also creates a simple DOM element that we use for output.

The prototype of Ball has two methods. The remove method just removes the DOM element, which we use for cleanup. The move method is much more intersting: It gets called for each ‘tick’ of our animation loop, so we use it to update the current velocity, look for collisions, update the current position and render the result. Step by step:

this.velocity = this.velocity.add(GRAVITY.scale(0.1));

This adds GRAVITY to the balls velocity. While GRAVITY has a real world value, we need to adapt it to our pixel-based dimension. Doing this in every tick causes the ball to accelerate downwards, or when moving upwards, to deccelarate. With this alone our ball would start falling, but never stop. That’s where the next block comes in, the collision detection:

if (this.position.y > world.y2) {
	this.velocity.x2 = -this.velocity.x2 * FRICTION;
	this.position.y = world.y2;
} else if (this.position.y < world.y1) {
	this.velocity.x2 = -this.velocity.x2 * FRICTION;
	this.position.y = world.y1;
}
if (this.position.x < world.x1) {
	this.velocity.x1 = -this.velocity.x1 * FRICTION;
	this.position.x = world.x1;
} else {
	if (this.position.x > world.x2) {
		this.velocity.x1 = -this.velocity.x1 * FRICTION;
		this.position.x = world.x2;
	}
}

Here we compare the current position of our ball to the dimensions of the world . For each direction, there’s a check if the call is beyond the limit, if so, it inverts the velocity for that direction, while applying FRICTION . This causes the ball to bounce back slightly slower then it was before, simulating very primitive friction. To avoid glitches, where the ball goes beyond the world dimensions and doesn’t come back, the position gets updated to move it back inside the defined limits.

Now that we’ve updated the velocity (and fixed the position in case of a collision), we can update the resulting position and output it:

// update position
this.position.x += this.velocity.x1;
this.position.y += this.velocity.x2;

// render
this.output.css({
	left: this.position.x,
	top: this.position.y
});

This adds the velocity components to the position of the ball, then uses inline styles to update the position in the DOM.

Next we’ll look at the setup and animation loop:

var balls = [];
balls.push(new Ball());

// animation loop
setInterval(function() {
	balls.forEach(function(ball) {
		ball.move();
	});
}, 25);

Here we create an array of balls and add one initial Ball. Then start an interval to at 25ms, which should give us about 40 frames per second (fps). To get more smooth 60fps, we’d have to go down to 16.5ms, which would also be even more CPU intensive then this becomes with lots of balls.

Inside the interval, we just loop through all balls and call the move method for each. In a proper game engine, this loop would separate the position updates from the rendering to ensure that, when frames get dropped, the game itself doesn’t slow down.

Up next, we’ve got the code to add new balls, with user controlled initial velocity:

var start;
$(document).mousedown(function(event) {
	start = new Point(event.pageX, event.pageY);
}).mouseup(function(event) {
	var end = new Point(event.pageX, event.pageY);
	var ball = new Ball();
	ball.position = end;
	ball.velocity = start.relative(end).scale(0.2);
	ball.move();
	balls.push(ball);
});

Here we bind mousedown and mouseup events, each time creating a Point object from the pageX and pageY event properties. In the mouseup handler, we then use the end point as the starting position for the new Ball object. Using Point’s relative method, we calculate a vector between those two points, scale it down and use it as the velocity for the new ball. That way, you can just click anywhere to add a new ball, or click, drag and let go to create one with intial velocity based on the drag. To get the ball animated along with the others, its added to the balls array.

With that we’re almost at the end. The last piece just clears all balls when pressing Escape:

$(document).keyup(function(event) {
	if (event.keyCode === 27) {
		balls.forEach(function(ball) {
			ball.remove();
		});
		balls.splice(0, balls.length);
	}
});

And that’s it! Thanks to Vector , we’ve got a pretty sane implementation, and a good starting point for further improvements. And there’s lots of potential:

  • Better friction simulation: Currently balls keep bouncing pretty often, they don’t slow down as much as they should after loosing some height.
  • More collision detection: Detecting collisions with other balls, the mouse or other objects would make the whole thing a lot more interesting.
  • Better collision detection: Currently collision detection just happens against a fixed position, not the actual ball’s dimensions. Taking the (rounded) borders into account would make things quite a bit more complicated, but also more realistic.
  • More moving objects with other shapes: Currently there’s just pixels bouncing around, even though they’re rendering as balls. Adding square objects both animated and static could make things a lot more interesting.
  • 3D: Moving from a 2D to a 3D simulation involves adding another component to both the Vecotor and Point class, and would add that third dimensions to each calculation, making especially the collision detection, already the most complex part, even more complex.

With this, I’ll get back to working on the basics for my flocking simulation.

Release: Validation Plugin 1.9.0

Posted October 07, 2011 by Jörn

An update for the jQuery validation plugin  is available. Most notable is heavily improved compability with HTML5 controls: You can apply validation rules to input types like number, email or url, it’ll get picked up by the plugin if the type matches a rule, and a required attribute (with the argument) also works with both jQuery 1.6+ (prop) and previous versions (attr).

Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes).

A few improvements and bug fixes for validation methods landed:

  • Creditcard now accepts spaces between the other valid characters
  • Email doesn’t accept a dot character at the end anymore.
  • The time method (in additionalMethods.js) is now more thorough.
  • A time12h method got added (also in additionalMethods.js), to validate 12-hour times, while the existing time method does 24-hour times.

There also two new localizations, resulting in a total number of 38 localizations. Existing localizations saw various improvements – thanks to everyone who contributed those! Its the only feature where I’m relying completely on contributions, as I can’t verify the correctness of any of the localizations (other then English and German).

Backwards compatibility is still going strong: The plugin should work with anything from jQuery 1.3.x to 1.6.x.

Download this release.

The full changelog:

  • Added Basque (EU) localization
  • Added Slovenian (SL) localization
  • Fixed issue #127 – Finnish translations has one : instead of ;
  • Fixed Russian localization, minor syntax issue
  • Added in support for HTML5 input types, fixes #97
  • Improved HTML5 support by setting novalidate attribute on the form, and reading the type attribute.
  • Fixed showLabel() removing all classes from error element. Remove only settings.validClass. Fixes #151.
  • Added ‘pattern’ to additional-methods to validate against arbitraty regular expressions.
  • Improved email method to not allow the dot at the end (valid by RFC, but unwanted here). Fixes #143
  • Fixed swedish and norwedian translations, min/max messages got switched. Fixes #181
  • Fixed #184 – resetForm: should unset lastElement
  • Fixed #71 – improve existing time method and add time12h method for 12h am/pm time format
  • Fixed #177 – Fix validation of a single radio or checkbox input
  • Fixed #189 – :hidden elements are now ignored by default
  • Fixed #194 – Required as attribute fails if jQuery>=1.6 – Use .prop instead of .attr
  • Fixed #47, #39, #32 – Allowed credit card numbers to contain spaces as well as dashes (spaces are commonly input by users).
As usual:
  • Please post questions to the official Using jQuery Plugins Forum , tagging your question with (at least) “validate”. Keep your question short and succinct and provide code when possible; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

Enjoy!

Using jQuery’s Data APIs

Posted September 02, 2011 by Dave Methvin

In the beginning (well, beginning with jQuery 1.2.3 in early 2008) there was the jQuery.data() API. It offers a way to associate JavaScript data — strings, numbers, or any object — with a DOM element. As long as you manipulate the DOM element with jQuery, the library ensures that when the DOM element goes away, the associated data goes away as well. This is especially important for older versions of IE that tend to leak memory when JavaScript data is mixed with DOM data.

Most jQuery code sets data values using the higher-level .data() API; for example, $("div").data("imaDiv", true) sets a boolean value on every div in the document. This API, in turn, calls down to jQuery.data() with each element to set the value. For completeness, there are also jQuery.removeData() and .removeData() to remove data elements, and jQuery.hasData() to determine if any data is currently set for an element.

So to recap: At the inception of these APIs, they were only about getting and setting values associated with DOM elements in memory. Most importantly, the data was managed to ensure no memory would leak when the DOM elements were removed. Many internal jQuery features such as event handling and toggle state memory use these data APIs and their benefits.

Enter HTML5

A few years later, HTML5 became popular and associated another concept with the word "data" through its data-* attributes and the associated DOM .dataset property. This isn't quite the same as jQuery's original idea of data: It involves values being associated with HTML elements in markup and not DOM elements in memory. But they are logically close enough that we added the ability to read HTML5 data-* attributes into jQuery's data object starting with version 1.4.

It's not a perfect marriage, though. HTML5 data-* attribute names are more like CSS names; a name like data-shrivel-up is turned into shrivelUp when read in JavaScript-land. No such rules ever applied to jQuery data names in the past, which means we may have to try both shrivel-up and shrivelUp to find a match. We know it's not ideal, but it's a consequence of trying to fit two concepts with differing semantics into a single API.

Rules of the Road for Data APIs

With that history in mind, there are a few important things you should know in order to use the .data() and jQuery.data() APIs effectively. To give you a better sense of what's going on, the items are illustrated with some code. Assume that each code block runs independently of the others and that they all refer the following HTML:

HTML:

  1. <div id = "novel" data-novelist= '{"firstname": "Jose", "lastname": "Saramago"}' > Blindness</div>
  2. <div id = "poem" data-poet= "Edna St. Vincent Millay" > Sonnet 18</div>
  3. <div id = "story" data-story-writer= "Raymond Carver" > A Small, Good Thing</div>


Here are the rules of the road:

  1. Only the .data() API reads HTML5 data-* attributes, and it does so once .

    The in-memory data object for an element is initialized from those data-* attributes the first time you call .data() for the element. Any subsequent changes to the attributes are ignored, since jQuery has already cached the data.

    Rule: If HTML5 data-* attributes change during program execution, use jQuery's .attr() method to get the current values.

    JavaScript:

    1. console .log ( $.data ( document.getElementById ( 'poem' ) , 'poet' ) ) ;
    2. //>> undefined
    3.  
    4. console .log ( $( '#poem' ) .data ( 'poet' ) ) ;
    5. //>> "Edna St. Vincent Millay"
    6.  
    7. // Change the HTML5 data-poet attribute
    8. $( '#poem' ) .attr ( 'data-poet' , 'Edmund Spenser' ) ;
    9.  
    10. console .log ( $( '#poem' ) .data ( 'poet' ) ) ;
    11. //>> "Edna St. Vincent Millay"


  2. The .data() API converts HTML5 data-* values to Javascript types whenever possible.

    That means sequences of digits or exponential-looking values like "11E5" are translated to a Javascript Number type, the string "true" becomes Boolean true , and a valid JSON string becomes a JavaScript object.

    Rule: To get HTML5 data-* attributes as strings without data conversion, use jQuery's .attr() method.

    JavaScript:

    1. console .log ( $( '#novel' ) .data ( 'novelist' ) ) ;
    2. //>> Object> {"firstname": "Jose", "lastname": "Saramago"}
    3.  
    4. console .log ( $( '#novel' ) .attr ( 'data-novelist' ) ) ;
    5. //>> '{"firstname": "Jose", "lastname": "Saramago"}'


  3. The lower-level jQuery.data() API does not read HTML5 data-* attributes.

    However, if the .data() API has been called already on that DOM element, jQuery.data() will "see" the values that it has already read from the data-* attributes. Conversely, if jQuery.data() sets a value with the same name as an HTML5 data-* attribute and .data() later reads them, the HTML5 attribute is ignored .

    Rule: To prevent confusion, do not use similar names for HTML5 data-* attributes and strictly internal data stored using jQuery.data() or .data() on the same elements.

    JavaScript:

    1. // Before reading with .data()
    2. console .log ( $.data ( document.getElementById ( 'poem' ) , 'poet' ) ) ;
    3. //>> undefined
    4.  
    5. console .log ( $( '#poem' ) .data ( 'poet' ) ) ;
    6. //>> "Edna St. Vincent Millay"
    7.  
    8. // After reading with .data()
    9. console .log ( $.data ( document.getElementById ( 'poem' ) , 'poet' ) ) ;
    10. //>> "Edna St. Vincent Millay"


  4. No jQuery data API ever changes HTML5 data-* attributes.

    Most uses of .data() and .removeData() are still for the original purpose of associating data with DOM elements in memory. Updating DOM attributes each time data was changed would slow things down for no good reason. Also, it's not even possible to serialize all data types that might be attached to a DOM element, such as functions, references to other DOM elements, or custom JavaScript objects.

    Rule: To update or remove HTML5 data-* attributes, use jQuery's .attr() or .removeAttr() methods.

    JavaScript:

    1. console .log ( $( '#poem' ) .data ( 'poet' ) ) ;
    2. //>> "Edna St. Vincent Millay"
    3.  
    4. console .log ( $( '#poem' ) .attr ( 'data-poet' ) ) ;
    5. //>> "Edna St. Vincent Millay"
    6.  
    7. // Change the HTML5 data-* attribute
    8. $( '#poem' ) .attr ( 'data-poet' , 'William Shakespeare' ) ;
    9.  
    10. console .log ( $( '#poem' ) .data ( 'poet' ) ) ;
    11. //>> "Edna St. Vincent Millay"
    12.  
    13. console .log ( $( '#poem' ) .attr ( 'data-poet' ) ) ;
    14. //>> "William Shakespeare"
    15.  
    16. // Change .data('poet')
    17. $( '#poem' ) .data ( 'poet' , 'Edmund Spenser' ) ;
    18.  
    19. console .log ( $( '#poem' ) .data ( 'poet' ) ) ;
    20. //>> "Edmund Spenser"
    21.  
    22. console .log ( $( '#poem' ) .attr ( 'data-poet' ) ) ;
    23. //>> "William Shakespeare"


  5. All data-* names are stored in camelCase in the jQuery data object, using W3C rules .

    So, data-caMEL-case becomes the camelCase property in the data object and should be accessed using .data("camelCase") . Because many people will use .data("camel-case") instead, we convert that to camelCase as well, but only if no data item named camel-case is found so it's faster to use the first form. If you get the entire data object using code like data = jQuery.data(elem) , you must use data.camelCase to access the data item.

    Rule: When accessing data taken from data-* attributes, and especially when accessing the data object directly, use the W3C camelCasing conventions.

    JavaScript:

    1. // Not recommended:
    2. console .log ( $( '#story' ) .data ( 'STORY-writer' ) ) ;
    3. //>> "Raymond Carver"
    4.  
    5. // Better:
    6. console .log ( $( '#story' ) .data ( 'storyWriter' ) ) ;
    7. //>> "Raymond Carver"
    8.  
    9. // Broken:
    10. console .log ( $( '#story' ) .attr ( 'dataStoryWriter' ) ) ;
    11. //>> undefined
    12.  
    13. // Better:
    14. console .log ( $( '#story' ) .attr ( 'data-STORY-writer' ) ) ;
    15. //>> "Raymond Carver"


Pick What You Like

Over time, jQuery's .data() API has taken on more responsibilities than it originally had when it was just a way to associate in-memory data with DOM elements and prevent IE leakage. If you need only a simple way to read HTML5 data-* attributes as strings, then the .attr() method may be the best choice, even though the siren-song-name .data() may be telling you otherwise. Whether you use .attr() or .data() , they work consistently across browsers all the way back to IE6 — even if the browser doesn't support HTML5 — so just choose the API with the feature set that works best for your needs.

Khan Exercise Rewrite

Posted July 28, 2011 by John Resig

Khan Exercise Framework Deployed

Today we’re pushing live a complete rewrite of the Khan Academy Exercise framework (live demo ).

A big push at Khan Academy has been to write more-and-more exercises for students to practice with. Naturally, to increase the number of exercises that we have, we needed to make it easier for team members, and casual committers, to write them.

When I was first looking in to Khan Academy I did a bunch of digging through their code base (which is Open Source ) and noticed that a lot of effort was going in to writing exercises. Interestingly all the exercises were being written in pure JavaScript and were dependent upon the server component in order to run properly. To me this seemed like a massive barrier to entry.

Brand New Framework

When I started just over two months ago I immediately went about rewriting the framework to use semantic HTML and not rely upon any server-side components whatsoever. To provide an example of the change that was made here is one particular exercise, Significant Figures 1, written for the old framework and written for the new framework . You can view the live version of the exercise, as well.

Khan Exercise Code Comparison

Significant Figures 1 went from 191 lines of code down to 58.

Note the dramatic lack of “code” – most logic is encapsulated and reduced to a series of variable declarations (some with minimal logic). Additionally utility functions were made significantly more useful, and generic, shared across exercises (some of this was done in the old framework but a complete rewrite allowed us to find areas of obvious overlap).

The result of the new framework is an interesting mix of semantic markup and logic – wrapped in a form of highly specialized templating. Tons of details regarding the specifics of the framework can be found in the Writing Exercises tutorial .

In short, some of the cool new features of this framework include:

  • A full module system for dynamically loading specific utilities (such as graphing).
  • A brand new templating framework , including templating inheritance, that makes it easy to reduce repeated code in exercises (some examples ).
  • A brand new graphing framework (written by Ben Alpert, named ‘Graphie’) that’s built on top of Raphael. This framework provides a simple API for creating all sorts of graphs and charts, it’s used extensively throughout the exercises.
  • An extensible plugin system for creating new answer types (to expand beyond basic multiple choice or fill in the blank).

Of course, that’s saying nothing of the actual user interaction as well. Most of the new framework’s logic is contained on the client-side and is generated directly off of Khan Academy’s REST API .

By moving logic to the client-side we’re able to have a much more interactive experience (doing all problem generation on the client-side, doing Ajax-y background submissions, things of that sort).

Testing

A big concern for us, with this rewrite, was to ensure that the quality and integrity of exercises was maintained well into the future. We wanted to make sure that the content of the exercises were correct and that regressions do not occur over time.

In fact we have three levels of testing:

  1. We have unit tests for our modules and utility functions (ensures that stuff like the templating will continue to work correctly).
  2. We have an interactive interface for generating unit tests for any given exercise (details below).
  3. We have a “Report a Problem” interface for sending post-deployment issues directly to our bug tracker.

The second stage is particularly interesting. On a fundamental level it’s hard to unit test something as complex as an exercise. While we can ensure that they still work at a functional level we can’t verify if the problems make sense, or if graphs look correct, or if it’s even possible to pick the right answer.

For these reasons we’ve introduced a new testing interface in which we use human developers as unit testers. When in test mode an additional panel is displayed asking the user to provide additional details regarding wether the problem is working correctly, or not. We ask them to really dig into the exercises and make sure that they’re working correctly, hints are being displayed properly, and other things of that nature.

Khan Exercise Testing

All of this information is collected and distilled into a piece of JavaScript code that is dropped into our test suite , all pushed into QUnit. At the moment we have around 2414 unit test collections with over 10,000 assertions.

Khan Exercise Test Dump

At the moment we’re working on ways of having better reporting and integration with our development process, for all those unit tests.

Development Process

I’m rather pleased with how the overall development process worked out. We actively kept both the code open (it’s up on Github and it’s MIT licensed) and the process open as well. We’ve had contributions from over twice as many outside contributors than members of the Khan Academy team (although the vast majority of the development was done by members of the team).

We have a detailed Getting Involved guide that explains how exactly anyone can participate in the development of the framework (or in the authoring of new exercises).

Predominantly we’ve been coordinating through a public HipChat room , using the Github Issue Tracker , and managing all the exercise work through a series of Google Spreadsheets.

We’re going to be transitioning now into creating a ton more exercises and we’d love to have even more help from the community. There is a ton of information on how to get involved in the wiki .

Next Steps and Thanks

There are a few things that we’re looking to do in the near future: Bring offline support to the exercises (for those with spotty internet connections or those using the upcoming iPad/Android application), client-side translation of content into other languages, and exercise answer checking using Node.js and JSDOM.

I also want to take this opportunity to thank everyone at Khan Academy, and all the community contributors, for helping to make this project happen. I especially want to thank Marcia Lee, Ben Alpert, Jeff Ruberg, Igor Terzic, Omar Rizwan, and Ben Kamens for their help in getting this out the door.

I should also mention that Khan Academy is hiring devs . We’re looking for both server/client devs (Python/JavaScript) and also mobile devs (iOS and Android).

Random Khan Exercises

Posted July 19, 2011 by John Resig

We’re taking an innovative new approach to providing students with exercises in the new Khan Academy exercise framework (which will be released for beta testing soon). In the old framework a problem would be randomly generated and provided to the user. This would result in a near-infinite number of randomly generated problems.

This ends up being a double-edged sword. While it’s great to provide a ton of problem variety to the students it’s fundamentally tricky as we want to have a manageable sample size of problems so that we can analyze student behavior and responses. For this reason we want to reduce the pool of possible problems to a more-manageable size (like about 200 or so – we’ll experiment with exact figures as time goes by). Most students will only do about 10-20 problems before moving on (since we define a ‘streak’ as having completed 10 problems in a row correctly) – although we want to provide enough of a pool to allow adventurous users to explore more.

Having a smaller pool size creates another issue though: Potential for student overlap. If there’s one thing that we’ve learned so far it’s that students are quite resourceful and identify patterns very quickly. They will realize if they start on the same problem together and if the problems go in the same order.

On top of this we need to make it so that every time the student hits the exercise they are presented with the same exact series of exercises. The first problem will always be the same – and the 50th problem will always be the same for that user. (This will allow us to reproduce the problems at a later date, showing them their problems/answers or analyzing the results.)

Thus we need two pieces of information to determine which problem should be presented to a user: The user’s ID and the problem # that they’re currently tackling.

We start by placing the user into a simple “bin”: We take the CRC32 of the student’s ID and mod 200 to start the user at one of the 200 possible exercises. (We picked CRC32 as it’s a simple function and we only need a basic level of granularity in the results.) Next we use the CRC32 to figure out how the user should jump through the exercises.

We can’t jump through the exercises 1 by 1, since the students will instantly recognize that pattern, so we have to take a random approach – one developed by Khan Academy intern Ben Alpert .

We start with a pool of prime numbers (the first 23 primes, to be exact) and use the user’s CRC32 to determine which of those primes will become the “jump distance” for that user.

For example:

  1. var primes = [3, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
  2.     47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
  3.  
  4. var num = crc32("jeresig");
  5. // num = 1411847358
  6.  
  7. var problemNum = num % 200;
  8. // problemNum = 158
  9.  
  10. var jumpNum = primes[ num % primes.length ];
  11. // jumpNum = 71

Thus when I visit a particular problem I will start at problem # 158, then go to problem 29, then problem 100, then problem 171, etc. On the other hand, if user “jeresig2″ visits the same problem they start at problem 171 then visit problem 182, 193, 4, etc.

(Note that we leave out 2 and 5 to avoid creating a circular loop of exercises – 2 will result in 100 repeating exercises, 5 will result in 40 repeating exercises. Of course we could just make the number of exercises prime to achieve a similar result – we’ll see!)

Even though we’re not using any built-in random number generator in this process, the distribution of chosen problems appears to be similar to a random distribution (since we’ve effectively implemented one ourselves):

Khan Problem Probability Distribution

To re-emphasize: We’re not trying to stop problem overlap – in fact we want overlap to occur, to give us data to study – but a lack of repeatable patterns has definitely been arrived at here.

We chose a collection of 23 primes because it is sufficiently large – but it also doesn’t divide into 200 cleanly (giving users that might have an identical starting position a different jump amount).

Also note that in the final solution we’re going to be combining the user’s ID with the name of the current problem – so that even if, somehow, two students end up with identical start positions and jump rates on one exercise they will have a different start position and jump rate on other exercises.

If all goes well we’ll be opening up the new exercise rewrite for beta testing within the next week or two.

Note: I’ve been posting interesting dev updates over on Google Plus . Feel free to follow me there if you wish to find out more about what I’m working on with Khan Academy or jQuery.

jQuery UI Checkbox/Radio Buttons

Posted June 24, 2011 by Benjamin Sterling

Recently I’ve had the good fortune to getting back into using jQuery and jQuery UI on a new and exciting project after a year and a half of using DOJO and MooTools – both are very good languages in their own right but not my cup of tea.  And one the things I think are really missing with jQuery UI are form controls.  There is progress being made. For instance with the select menu , still some holes from a styling perspective, but solid.  There is also the buttons widget that help with getting buttons – whether you are talking about <A>, <BUTTON> or <INPUT> – to function correctly cross browser.  And although the button widget has some “checkbox/radiobutton” type interactions it does not pass 508 testing on the project I am working on.

So, one of the bigger holes in opinion is with checkboxes and radio buttons and since I’ve had the benefit of working with Dijit and having it pass a very rigorous 508 testing process I figured the best approach is to mimic, in a much less-code kinda way, what Dijit was doing.

So, with out much more blabbering on, below are a few examples of the checkboxes and radio buttons:

First we have the checkboxes:

Then we have the radio buttons:

Some thoughts

So it’s basic and it works and keeps all the basic functionality that comes with standard radio buttons and checkboxes. This is, in my opinion, what any widget that overrides a form control should do.

What probably needs to be taking into account is, what if styles are turned off? What happens if images are disabled? Do we check for these and if styles are off or images are off don’t build? Not sure, maybe that is something to deal with on a per project basis?

Currently if you do something like $( “input[type=radio]:eq(2)” ).prop( ‘checked’, true ); or even $( “input[type=radio]:eq(2)” ).get(0).checked = true; and you are not using the widget the radio button will change accordingly, but not if you are using the widget. The change event is not being triggered. Will need to look into this a bit more.  Thoughts? Not longer an issue, put a setInterval in to check for the change of the checked property and seems to be working correctly.

The checkbox and radio button width are only supporting jQuery 1.6+, it is using the .prop method throughout.  If you need to use it with an earlier release of jQuery you just need to swap those .prop methods out for the .attr method.

As I stated before, this method of doing the radio buttons and checkboxes have been tested fairly well for 508 compliancy so I am pretty confident it should work for you.  However, with everything we do, there is always room for improvement so please let me know via github if you believe you have those improvements.

Lastly, I tried my best to follow the standards that were set on the jQuery UI wiki but please get with me on items I can improve.

The Source

https://github.com/bmsterling/jquery-ui

Please submit any bugs or issues you have on github , I will not respond to those issues within the comments (or at least can’t effectively).

Update

06/25/2011 : Updated the code to allow for onchange to trigger when the checked property has changed.

Simple use of Event Delegation

Posted June 14, 2011 by Remy
Event delegation may be some techie term that you’d rather shy away from, but if you’ve not already used it, this example will show you a simple but powerful use of event delegation. Watch Watch Simple Event Delegation (Alternative flash version) QuickTime version is approximately 22Mb, flash version is streaming. View the demo used in [...]

Using SproutCore 2.0 with jQuery UI

Posted June 11, 2011 by wycats

One of the goals of SproutCore 2.0 is to make it trivial to integrate the tools you’re already using together with SproutCore.

One way that we do that is to make it possible to drop a SproutCore app into a small part of your existing page. Greg Moeck did a great job demonstrating this functionality on the SproutCore Blog a couple of weeks ago, and I’d definitely recommend checking it out if you’re interested in learning more about embedding SproutCore 2.0 in an existing app.

Another complementary approach is to make it easy to integrate SproutCore with existing JavaScript libraries and tools. Because SproutCore 2.0 uses templates as the primary way to build your application, it integrates well with the tools you’re already using. In this post, I’ll show you the hooks you need to integrate SproutCore with anything you want, and then show you how to do a general-purpose integration with jQuery UI.

Quick Refresh: Handlebars Templates

First of all, you can take any piece of HTML and attach it to a SproutCore view. You would typically do this in order to attach event handlers to the view or to define a function that computes how a particular value should be displayed. For instance, let’s say we have some HTML that shows a business card for a person:

<div
 class
="card"
>


  <p
 class
="name"
>

{{salutation}} {{fullName}}</p>



  <p
 class
="address"
>

{{number}} {{street}}</p>



  <p
 class
="region"
>

{{city}}, {{state}} {{zip}}</p>



</div>



We can wrap this chunk of HTML in a SproutCore view, which will define the sources of each of the properties used in {{}}} .

<script
 type
="text/html"
>


{{#view Yehuda.BusinessCard contentBinding="Yehuda.businessContent"}}
  <div
 class
="card"
>


    <p
 class
="name"
>

{{content.salutation}} {{fullName}}</p>



    <p
 class
="address"
>

{{content.streetNumber}} {{content.street}}</p>



    <p
 class
="region"
>

{{content.city}}, {{content.state}} {{content.zip}}</p>



  </div>



{{/view}}
</script>



Wrapping the HTML snippet in a <script> tag tells SproutCore to render it using its template engine. You’d normally get the {{}} properties from a controller or other data source, but let’s define a view with the values baked in for now:

Yehuda.BusinessCard
 =
 SC.View
.extend
(
{

  // fill in the content in the template with contentBinding

  content:
 null
,

 
  fullName:
 function
(
)
 {

    return
 this
.get
(
'firstName'
)
 +
 ' '
 +
 this
.get
(
'lastName'
)
;

  }
.property
(
'content.firstName'
,
 'content.lastName'
)

}
)
;

 
Yehuda.businessContent
 =
 SC.Object
.create
(
{

  firstName:
 "Yehuda"
,

  lastName:
 "Katz"
,

  salutation:
 "Mr."
,

  streetNumber:
 300
,

  street:
 "Brannan"
,

  city:
 "San Francisco"
,

  state:
 "CA"
,

  zip:
 "94107"

}
)
;

If we reload the page, we will see a static business card with my information in it. If we update my content with Yehuda.businessContent.set(key, value) , SproutCore will automatically update the HTML for you. If you update any property, including firstName or lastName , which are used only as dependencies of fullName , SproutCore will automatically handle updating the HTML for you.

didCreateElement

You can also define some code to run every time an element is rendered. You can use this hook to wire up any JavaScript library to the element that SproutCore has created. For instance, let’s say we want to zebra stripe the three lines in our business card once it has been create (note: you probably would not use JS to zebra stripe in real life).

Let’s extend our view:

Yehuda.BusinessCard
 =
 SC.View
.extend
(
{

  // fill in the content in the template with contentBinding

  content:
 null
,

 
  fullName:
 function
(
)
 {

    return
 this
.get
(
'firstName'
)
 +
 ' '
 +
 this
.get
(
'lastName'
)
;

  }
.property
(
'content.firstName'
,
 'content.lastName'
)
,

 
  didCreateElement:
 function
(
)
 {

    this
._super(
)
;

    this
.$(
"p:even"
)
.addClass
(
"even"
)
;

  }

}
)
;

First of all, you will want to call super, to ensure that any hooks in parent classes get called. Second, all SproutCore views have a $ function, which is the normal jQuery function, scoped to the current element. You can also call this.$() to get back a jQuery object wrapping the element itself.

You can use this hook to do anything you want, allowing you to hook in any library you want. You would use this hook a lot like you’d use a jQuery(document).ready hook, but scoped to the view being created.

SproutCore also provides a willDestroyElement hook, which you can use to tear things down that you set up when the element was created. This is relatively rare, and is mostly used when interfacing with another toolkit that requires a teardown, or to tear down custom SproutCore observers.

jQuery UI

We can use these hooks to build some basic integration with jQuery UI. I’ve written a demo that shows how to connect SproutCore bindings to jQuery options at http://sc20-jqui.strobeapp.com/ . You can also check out the annotated source code .

The most important thing to look at is the JQ.Widget mixin, which can be mixed into view classes to attach jQuery UI options and events to SproutCore’s binding and event system.

You can get started with the SproutCore 2.0 developer preview by downloading the starter kit .

Until next time!

Om Malik interviews Steven Blank: Taking Venture Capital is a Pact with the Devil

Posted May 27, 2011 by mikehostetler

Steve Blank just posted a great interview he did with Om Malik . In the interview, he talks about many different topics but my favorite part starts at 13:00 where he discusses the fact that when you take VC, you're really making a pact with the Devil.

If you've raised money at a high valuation, you've just made a pact with the devil ... your VC is no longer interested in getting 1x return. So, now all of a sudden, you've set the price at where your investors are thinking they are going to make money.

Two is though, if you've raised more money then you can even figure out what to do with, there's a funny heuristic about startups is, ... my heuristic is, if you've raised $10,000,000, you tend to spend $10,000,001. I've yet to see a startup give back money because they couldn't spend it. So, spending kinda matches the amount of money raised.

What Blank identifies is almost exactly the reason why we've chosen the bootstrap route in appendTo. When we sat down and laid plans for what we wanted to create, we realized that we didn't need the money. Furthermore, we also realized that raising money would actually have more of a negative effect then a positive one.

Hack the Dream: Control, Natural Consequences and Grace

Posted May 26, 2011 by mikehostetler

As a follow up to my post last week about how appendTo was founded and Hacking the American Dream, I’m going to blog on some of the philosophical pillars we built the organization upon that led us here. If you have a question, please don’t hesitate to leave a comment or contact me.

Control and Management

If you’ve spent any amount of time near children, they exist in a remarkable world. They don’t seek to control anything because they have a firm understanding that there isn’t much that they can control. They don’t control when they eat. They don’t control when they sleep.

If we’re honest with ourselves, the ability to live without the need to control anything, as long as our needs are met, represents a remarkable sense of freedom.

As we grow up, we realize that control can be a good thing. With control comes responsibility, and that’s generally good too. We control a car as it drives down the road. We control what we eat, we control when we wake up, we control when we go to sleep. Self-control is a sign of maturity, a positive step towards adulthood.

Where we get into trouble is when we try to control the actions of others. The fact is, there is very little we can do to control anybody else. This is where the nasty side of control shows up. Manipulation, carrots & sticks, passive aggressive behavior and reverse psychology are all examples of patterns where someone tries to control someone else. Sometimes they work, but they don’t always result in a win-win for both parties involved.

Control in the Workforce

Part of the reason central offices exist is because forced physical presence is a way to maintain control. There are positive benefits for face-to-face collaboration, but they don’t require full-time face-to-face presence. The internet is teeming with examples of distributed teams creating something just as compelling as face-to-face teams.

The realization that a typical company or workforce is built upon a leader or owner’s ability to control the output of a worker stood in stark contrast to my experiences in Open Source. Open Source is a place where the foundation of control doesn’t exist and all forward progress is built upon the willingness and intrinsic motivation of the people doing the work.

The major difference between Open Source and a business is that people get paid. Because money changes hands, explicit control is used as a technique to ensure output. That makes sense, unless you have another paradigm to work under.

Expectations and Natural Consequences

When we founded appendTo, we were more familiar with the management structure of expectations and natural consequences. Prior to appendTo, I spent some time freelancing. Freelancing is a great way to really learn how the world works. If you don’t sell, or don’t follow through, you don’t eat. It doesn’t get much simpler than that. Thus, we made the decision to implement a system of expectations and natural consequences within appendTo rather than utilizing control as a management style.

The system of expectations and natural consequences is black and white, which creates a really sharp edge. You are either delivering or you aren’t, you are eating or you aren’t. Most employees typically don’t like that, because part of their employment is the security that comes with knowing that they will eat tomorrow. In a small startup, where your performance today affects the health of the company tomorrow, this sharp edge can be a positive thing.

Another significant reason we chose to go with a system of expectations and natural consequences is because it can be a win-win system for both parties involved, and had the built-in feature of not requiring any manipulation or nasty control techniques. As long as the expectations were defined properly and both parties understood where the lines existed, everyone could operate with a certain amount of autonomy. Once again, it kept things simple.

The only downside that we could think of was that such a system could be too harsh at times. While you can allow for mistakes, or simple “life happens” moments, what happens when expectations simply aren’t met? What do you do as a leader when the natural consequence for missing an expectation is firing someone?

The Missing Piece with Natural Consequences

For the last piece of the puzzle, the only answer was to explicitly add an element of grace into the equation. Grace is an often overlooked, yet powerful tool. Humans typically understand when they have screwed up. If consequences for screwing up aren’t enforced, that sense of screwing up tends to fade and things go downhill in a hurry. This is where strong expectations are important.

The truth is, if we required everyone to constantly live up to a set of expectations the company created, nobody would want to work at the company, including me! That’s where grace comes in.

When someone realizes they screwed up and they honestly want to be at the company, a natural human reaction is to feel bad and apologize, especially when the natural consequences of their mistake are already understood. It is at this moment that you have the tremendous opportunity as a leader to build up that individual.

This is where the relationship between the human beings involved is key. If you have laid a solid relational foundation with the other person, extending grace can have tremendous positive effects. If that relationship is just beginning, extending grace is great way to begin building that relationship.

That Magic Moment

Something magic happens when a leader extends grace to someone who clearly deserves the natural consequences of their actions. The impact on the person receiving the grace will often motivate correction of the behavior in addition to building organizational loyalty and emphasizing the value placed on the relationship.

As a leader in your organization, implementing a policy of extending grace should not be underestimated.

Too Far?

What happens when someone keeps failing? If you extend grace multiple times in a row for the same offense, and there is no attempt at improvement, my advice would be to put that person on a documented improvement plan with concrete milestones. The details of this process are beyond what I intend to write here, but the point I want to make is that it is advisable to implement limits to the extent of the grace you are willing and able to give in order to properly manage people who may wish to take advantage of the process.

Hacking the American Dream

Posted May 19, 2011 by mikehostetler

Last week I had the privilege of attending the 2011 BigOmaha conference. BigOmaha was by far the best event I have ever attended. The Silicon Prarie News team did an amazing job organizing and executing this conference.

Filled to the brim with inspiring content and amazing introductions, Jonathan Sharp, Andrew Wirick and I sat down to just hang out and decompress on the event. The short discussion that followed crystalized a perspective I've held for a while, but am only beginning to understand and communicate.

A bit of history

When I founded appendTo in October 2009, I was working full time in another company I'd founded, a Drupal consultancy called A Mountain Top, LLC. Jonathan Sharp and I were working together, but hadn't made the full jump into a partnership yet. We landed our first training gig with AOL and earned enough money to get the company off the ground. The initial plan was to merge A Mountain Top with appendTo, leveraging the success of A Mountain Top to propel the new venture.

That plan ended abruptly in mid-December. Due to a series of unforseen events, A Mountain Top came unraveled in the span of a few days. Everything I had worked to build for the prior three years evaporated in a span of a few days. Going into the holidays, I chose to take some time off, something I hadn't truly done since I began working in my own business.

It was during that time that I realized I had to change my approach. I'd learned many valuable skills in my previous venture, but had also introduced many fatal flaws into A Mountain Top. The chief flaw being I was always working for tomorrow, always searching for that big payoff.

I realized that while the damage to A Mountain Top could be repaired, I had been given a tremendous opportunity with appendTo, an opportunity to do something different.

Trying to do it "My Way"

Little did I know the impact of that choice. The first practical outcome was to choose to partner with Jonathan Sharp. We solidified that partnership in January 2010. The second was the decision to close down A Mountain Top and start fresh.

Over the next few months, the new start began to get off the ground. We landed a few more sales, participated in the jQuery 14 event, and began getting some traction. However, Jonathan and I didn't completely follow our gut. We followed well-intentioned advice that caused a few missteps, and we found ourselves out of money and out of time early in the year.

The weeks that followed, mid-April through early May, defined the future of appendTo. We threw out all the rules and decided to do three things: work hard, follow our instincts and do the right thing even when it is hard.

Initial results

What followed was an explosion of growth. We hired 6 people within the span of 2.5 months. As a bootstrapped company, we were selling new projects as fast as we hired employees, a juggling act that would be difficult to replicate even if we tried.

Along the way, we made several important decisions. We decided to build a company that would be 100% virtual. We committed to run our company infrastructure in the "cloud". We decided to pay for health insurance for everyone, covering 100% of the premium cost for all full time employees and their families.

As more and more people joined appendTo, relationships began to form. Our team grew and our capabilities grew. We committed to a transparent style of leadership, agreeing to make the hard decisions as leaders, but honestly sharing our thought process and doing our best to put the health of the company and the employees first.

We operated with the key philosophy that we were running a marathon, not a sprint. This drove our policy of maintaining realistic work hours within the company. As such we work 40-45 hours a week. Client's didn't always like or respect this policy, but we knew from experience that mandated rest promotes productivity for knowledge workers. We'd all worked at jobs where the value delivered went down as the hours we logged went up.

Emerging culture

As our culture began to form, we started to realize there was something special about appendTo. While we couldn't quite put our finger on it, or easily describe it, everyone in the company started to feel it.

We began holding focus groups to discuss the concepts that we felt made appendTo different. We would ask questions, write answers, create lists and write down definitions in an attempt to describe what we all intuitively knew had drawn us to the organization.

Our attempts to define and document our culture were important and produced a lot of great information. Yet, the simple definition of what made appendTo different kept eluding us.

Closing party at BigOmaha 2011

Fast forward to the conversation at Big Omaha last week. As we discussed common threads from the speakers and valuable advice that we could take away, the conversation drifted to the topic of appendTo's product.

We have an amazing team of people. Not only do we have a team that could build an awesome product, but they each possess amazing character and an amount of internal motivation that makes me honored to work with each one of them. The consensus is that we can build anything we put our mind to.

The trick is to find something we are all passionate about. It's not easy getting two people to be passionate about any specific thing, let alone eleven. This is why the conversation drifted to the similarities everyone at appendTo shares and the factors that draw us to work there. Our shared passions boil down to two things:

  • We are passionate about Front-End Web Development and JavaScript
  • We are passionate about working to live, not living to work

The lightbulb went on when we realized that appendTo was an organization that not only believed this, but was actually a place that followed through with making these passions a reality for each employee.

The juxtoposition of this realization against the story of other exciting startups floored me. General wisdom states that most startups are built for one of two end points, a grand exit of some sort or die trying. In appendTo, we'd built an organization geared to serve the employees while maintaining stability, and we'd succeeded.

Deep inside, we probably share the same goals as the founders of other startups. We just found a way to get there faster and with less compromise.

Freedom defined

In appendTo ...

  • I have the freedom to work anywhere in the world, as opposed to going to a specific location every day.
  • I don't have a million dollars in the bank, but I have a job that pays the bills and puts food on the table.
  • I have the freedom to work on projects that I find interesting.
  • I work with talented and passionate people that motivate me.
  • I can turn off connectivity and actually relax because I know that the team has my back.
  • My work encourages healthy relationships, with friends and family.
  • I don't have to choose between providing for my family and spending time with them, I get both.

The key point is that I wouldn't trade any of these benefits for all the money in the world. Taken together, these benefits allow us to enjoy the present rather then betting on the future.

Conclusion

As entrepreneurs, we've been taught that working hard to achieve the American Dream is all about hustling, growing big and then gunning for the big payoff. That's no longer true. Eighteen months ago, we set out to build something different. Along the way, we chose to ignore the rules and build something that made sense. What I realized this week was that we've essentially hacked the American Dream. I think that's pretty awesome.

I'd like to add a few more key points:

  • While this story is about me and I am a founder and leader of appendTo, I am only a participant. The manifestation of this hack would not have been possible without everyone's participation in the company.
  • Have you hacked the American Dream? Please share your story in the comments.

Release: Validation Plugin 1.8.1

Posted May 14, 2011 by Jörn

An update for the jQuery validation plugin is available. This brings compability with jQuery 1.6.1, while staying backwards compatible with 1.3.2, 1.4.2, 1.4.4 and 1.5.2 .

The bug was related to the plugin’s usage of the form.elements property, which jQuery 1.6 doesn’t support anymore. Other then that, there is a bug fix for adding and removing the error and valid classes on radio and checkbox elements (thanks to Phil Haack for the contribution), as well as two new localizations: Thai and Vietnamese. That brings the plugin to a total of 37 supported locales.

If you’ve been testing 1.8.0 release with jQuery 1.6 and couldn’t get it to work, despite the note saying that its working, please update to 1.8.1. The form.elements fix was in place before 1.6 final got released, and I only tested against latest code on GitHub, while 1.8.0 was indeed broken.

Download this release.

The full changelog:

  • Added Thai (TH) localization, fixes #85
  • Added Vietnamese (VI) localization, thanks Ngoc
  • Fixed issue #78. Error/Valid styling applies to all radio buttons of same group for required validation.
  • Don’t use form.elements as that isn’t supported in jQuery 1.6 anymore. Its buggy as hell anyway (IE6-8: form.elements === form).
  • Please post questions to the official Using jQuery Plugins Forum , tagging your question with (at least) “validate”. Keep your question short and succinct and provide code when possible; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

Enjoy!

jQuery 1.6 and .attr()

Posted May 13, 2011 by John Resig

jQuery 1.6 and 1.6.1 are out the door. Congrats to the team and everyone that was involved with the release!

A relatively controversial change in 1.6 was regarding how attributes and DOM object properties were handled. In 1.6 we wanted to take the major step of completely separating the two, allowing us to create an .attr() method that wasn’t quite so mealy-mouthed with regards to how attributes were handled. We did this in 1.6 because we felt that it was a substantial change (we only do major changes in the 1.x major releases of jQuery) and had the possibility of affecting people.

We did a considerable amount of testing on the code and we were quite confident that the amount of problems that people would encounter, while upgrading, would be quite minimal. The biggest pain points, we surmised, would be regarding how boolean attributes were handled (attributes like “disabled” or “selected”). However most of this would be mitigated and would likely have worked fine for users that consistently used .attr() to access and update their attributes.

After making the changes, and publishing 1.6, there were enough complaints that we had changed the API to cause us to reconsider and return .attr() to its sometimes-attribute, sometimes-property, state.

jQuery is in an incredibly tricky position now (and has been for some time). We very rarely add features to the library, for fear of bloat and added API maintenance overhead, and are rarely able to make any sort of API change, for fear of preventing people from upgrading.

Thankfully even though we’ve reverted some of the changes in 1.6, we’ve done it in a way that still maintains the performance gains that we achieved with the 1.6 release.

I wanted to try and summarize the .attr() method , to explain how it currently works in 1.6.1, but ended up writing up a sample function instead (note that this is a bit of an over-simplification, please read the code for more details):

  1. function attr( elem, name, value ) {
  2.     // Are we setting a value?
  3.     if ( value !== undefined ) {
  4.         // Make sure the element has the ability to set an attribute
  5.         if ( typeof elem.setAttribute !== "undefined" ) {
  6.             // If the user is setting the value to false
  7.             if ( value === false ) {
  8.                 // Completely remove the attribute
  9.                 elem.removeAttribute( name );
  10.            
  11.             // Otherwise set the attribute value
  12.             } else {
  13.                 // If the user is setting the value to true,
  14.                 // Set it equal to the name of the attribute
  15.                 // (handles boolean attributes nicely)
  16.                 elem.setAttribute( name, value === true ? name : value );
  17.             }
  18.        
  19.         // If it doesn't, then we're likely dealing with window or document
  20.         // (or some other object entirely)
  21.         } else {
  22.             elem[ name ] = value;
  23.         }
  24.    
  25.     // Otherwise we're getting an attribute value
  26.     // Check to see if the appropriate method exists
  27.     // Also don't use getAttribute if a boolean property exists
  28.     } else if ( typeof elem.getAttribute !== "undefined" &&
  29.                 typeof elem[ name ] !== "boolean" ) {
  30.         return elem.getAttribute( name );
  31.    
  32.     // If no getAttribute method is present, or if we
  33.     // wish to access the boolean property instead of the
  34.     // attribute, then we fallback to the DOM object property
  35.     } else {
  36.         return elem[ name ];
  37.     }
  38. }

Ironically this isn’t much shorter than the actual .attr() implementation , I recommend that you check it out.

There’s a very good chance that your code, written targeting 1.5.2, will continue to work just fine in 1.6.1 using this particular technique.

However this point now begs the question: Why does .prop() exist?

In short, for two reasons:

  1. There are legitimate use cases for interacting with some DOM properties (such as nodeName , selectedIndex , or defaultValue ) and we want to provide a simple solution for accessing, and mutating, them.
  2. Accessing properties through the .attr() method will be slightly slower than accessing them directly through .prop() (as .attr() calls .prop() internally in order to handle all property-related mutation).

In jQuery 1.5.2, and older, in order to access a DOM property you would have to do something like this:

  1. var elem = $("#foo")[0];
  2. if ( elem ) {
  3.     index = elem.selectedIndex;
  4. }

In 1.6+ you can just do:

  1. index = $("#foo").prop("selectedIndex");

Summary: There’s a good chance that your code won’t be affected at all with the changes that’ve happened, especially so with the changes in 1.6.1, and jQuery now has a convenience method for handling DOM properties in a simpler, and slightly faster, manner.

Tangentially this reminds me of a common question that I hear: What will be in jQuery 2.0? I have no idea what will be in that release, should it ever arrive, but I do know what won’t be in it: A massive API change of any sort. Even when we make, relatively minor, API changes like in the 1.6 release the amount of negative feedback that we get is monumental. If we’ve learned anything after doing 31 releases of jQuery it’s that people like having stability in their API and will cherish that over everything else.

I do want to thank the community though for being so vocal and working to communicate with the team so actively. Without the community’s communication and support it’s doubtful that the team would be able to continue operating.

I would like to take this opportunity to encourage everyone to get involved with the development of jQuery. We hold active discussions every day in IRC and hold public meetings once a week. We also post weekly status updates if you wish to follow along. Right now we’re working on the 1.7 release of the library and are actively encouraging contributions and feedback. If you want to help ensure the quality and stability of the next release of jQuery, the best way to do so is to get involved. Hope to see you around the bug tracker.

jQuery.map() in 1.6

Posted May 03, 2011 by Jordan Boesch

Among all of the great fixes and additions to jQuery 1.6, I'm happy to say that jQuery.map() now supports objects! The previous map only supported arrays. With other libraries already offering object support for map, it was a nice addition.

Let's say you want to collect an array of object keys from a JSON object.

JavaScript:

  1. var myObj = {
  2.     "name" : "jordan" ,
  3.     "hair_color" : "brown" ,
  4.     "eye_color" : "ravishing"
  5. } ;


Here's how you would have done it in older versions of jQuery (prior to 1.6):

JavaScript:

  1. var objKeys = [ ] ;
  2. $.each ( myObj, function ( key, value ) {
  3.     objKeys.push ( key ) ;
  4. } ) ;
  5. // objKeys == [ "name", "hair_color", "eye_color" ]


Here's the new way (just a little more convenient):

JavaScript:

  1. var objKeys = $.map ( myObj, function ( value, key ) {
  2.     return key;
  3. } ) ;
  4. // objKeys == [ "name", "hair_color", "eye_color" ]


Going inside the new jQuery.map()

For those that are curious and a little more advanced, there are some neat things going on under the hood of the new jQuery.map() that I would like to talk about.

Adding object support seems pretty trivial at first since jQuery.each() is already doing it - so it must be an easy patch, right? Well, not really. Let's look at how jQuery.each() is doing it. If you look at the jQuery source on github, you'll see that it's doing:

JavaScript:

  1. length = object.length ,
  2. isObj = length === undefined || jQuery.isFunction ( object ) ;


Can you see the flaw in this? It's going to treat the variable object (could be an array or object) like an object if length is undefined. What happens when I have an object with a "length" property? It dies a horrible death . Some have reported this issue .

For the new jQuery.map(), we wanted support for objects and also be able to pass an object with a length property and not have it blow up like jQuery.each() does. Dan Heberden came to the rescue . Dan spent some time making sure that jQuery.map() didn't face the same fate while keeping performance in mind.

Here is what Dan did to see if elems is an array:

JavaScript:

  1. length = elems.length ,
  2. isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length> 0 && elems[ 0 ] && elems[ length - 1 ] ) || length === 0 || jQuery.isArray ( elems ) ) ;


I should note that John Resig added :

JavaScript:

  1. || length === 0


To support empty node lists .

Let's look at the first part of our isArray variable. You'll notice it does a check for:

JavaScript:

  1. elems instanceof jQuery


We're checking to see if elems is an instanceof jQuery. We're doing this first because you're most likely dealing with a jQuery collection/array-like object . Since jQuery collections are treated like regular arrays (uses for loop), this is an optimized way of checking if we should treat elems like an array. Below is an example of jQuery.fn.map() in action.

JavaScript:

  1. $( 'div' ) .map ( function ( i, element ) {
  2.     // under the hood, this call to map passes the
  3.     // isArray variable check right away because
  4.     // $('div') is an instance of jQuery
  5.     // using 'this' here refers to the DOM element
  6. } ) ;


Here is jQuery.map() with a jQuery collection passed as the first argument:

JavaScript:

  1. $.map ( $( 'div' ) , function ( element, i ) {
  2.     // does the same as above and will pass the "instanceof" check
  3.     // also, note that the arguments are backwards
  4.     // using 'this' here refers to the window object
  5. } ) ;


If what you passed is not an instance of jQuery but it passed the isArray variable check, it means your call to the jQuery.map() utility function probably looked something like this:

JavaScript:

  1. $.map ( [ 1 , 3 , 5 ] , function ( ) { } ) ;


In this case it falls back to this rigorous check to see if it's an array. Note: I'm breaking it down into separate lines so it's easier to understand.

JavaScript:

  1. // make sure that we actually have a length property
  2. length !== undefined
  3.     // if it's a number, it could possibly be an array
  4.     // but still needs some more checking
  5.     && typeof length === "number"
  6.     && (
  7.         // make sure we're dealing with a set of non-empties
  8.         ( length> 0 && elems[ 0 ] && elems[ length - 1 ] )
  9.         // if we're dealing with an empty node list - this is rare
  10.         || length === 0
  11.         // this check is a last resort and only gets hit if we
  12.         // pass an array like $.map(new Array(1), fn);
  13.         || jQuery.isArray ( elems )
  14.     )


The rest of the logic is pretty straight forward - just some for loops and super fun for-in loops.

Hope you enjoy jQuery.map() with object support!

Joined Bocoup

Posted May 02, 2011 by Richard D. Worth

I joined the Bocoup Team in April. I couldn’t be more excited about the development work I’ll be doing at Bocoup. There are a ton of other reasons I love this job, but I’ll just mention two right now.

1. Bocoup Training

I’ll continue to develop and deliver open web technology training for today’s beginning, intermediate and advanced level web developers. JavaScript, HTML5, jQuery, Mobile, jQuery UI. The training is available to internal teams at companies large and small. It’s also offered at the Bocoup Loft in Boston.

Rolling Down To Rio

I’m anxious to take Bocoup’s training to other cities, even internationally. My first such opportunity will be in just a few weeks. I’ll deliver a specialized training class to a team of developers at globo.com (think Brazil’s cnn.com) in Rio de Janeiro. I’ll already be in Brazil to deliver a jQuery UI keynote at the first ever JavaScript conference in Brazil. As long as I’m in the country, I decided to spend a week in Rio (where I lived just over 10 years ago) and do some training. It will be an intensive 5-day course with each day covering one of 5 key topics: JavaScript, HTML5, jQuery, Mobile, and jQuery UI. Each of these topics typically is treated in a 2-3 day course, so this will be something like mega-workshop. Should be fun.

HTML5 Training at Bocoup June 1-3

My next training will be a 3-day HTML5 course at the Bocoup Loft, June 1-3. Tickets just went on sale a few days ago. Get with me this week and I can get you a discount code.

2. Bocoup <3 Open Source

Bocoup has 25% open source time. What does this mean? I can work up to 10hrs a week on Bocoup’s dime continue to develop and support jQuery and jQuery UI and other quality open source projects. This is google-esquely awesome, especially for such a new and small (by comparison) company. This isn’t just because I was hired on to Bocoup while leading the jQuery UI project. This is they way Bocoup is built. Every employee has built-in 25% time to work on open source projects, and it happens. You want examples? In the jQuery space alone: Rick Waldron, Adam Sontag, Ben Alman. That’s just a few. Oh, as long as I mentioned those names, I’m super excited to be joining them as a fellow Bocoup trainer. Super guys.

JSConf and NodeConf

I’ll be at JSConf and NodeConf this week. Actually a bunch of Bocoup people are. Oh yeah, and Bocoup organized the pre-training for both.

If you’re at either event, find me, I’ve got something for you.

Release: Validation Plugin 1.8

Posted March 25, 2011 by Jörn

An update for the jQuery validation plugin is available. This brings compability with jQuery 1.5.1, while staying backwards compatible with 1.3.2, 1.4.2, 1.4.4 and 1.5.0 .

A bug related to remove validation with client-side formatted messages was fixed, along with improvements to localizations and four new ones, resulting in a total of 34 localizations.

This release is the first to use Google Closure Compiler for minifying files. Like other projects, I’ve dropped the .pack.js files in favor of minifying and gzipping.

Download this release.

The full changelog:

  • Improved NL localization
  • Added Georgian (GE) localization, thanks Avtandil Kikabidze
  • Added Serbian (SR) localization, thanks Aleksandar Milovac
  • Added ipv4 and ipv6 to additional methods, thanks Natal Ngétal
  • Added Japanese (JA) localization, thanks Bryan Meyerovich
  • Added Catalan (CA) localization, thanks Xavier de Pedro
  • Fixed missing var statements within for-in loops
  • Fix for remote validation, where a formatted message got messed up
  • Bugfixes for compability with jQuery 1.5.1, while maintaining backwards-compability

The migration to GitHub is mostly complete, issues are now tracked there:

  • Please post questions to the official Using jQuery Plugins Forum , tagging your question with (at least) “validate”. Keep your question short and succinct and provide code when possible; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features, eg. new validation methods) to the GitHub issue tracker

Enjoy!

My Visual Studio 2010 HTML5 Templates are Updated for jQuery 1.5.1 and Modernizr 1.7

Posted March 22, 2011 by Rey Bango

I wanted to do a refresh of the Visual Studio 2010 HTML5 Templates I created last September . With jQuery now at v1.5.1 and Modernizr at v1.7, it was time for an update.

If you’ve already downloaded my original templates, you can simply overwrite those with the following files. If you’re new to this, then download the files and drop them into the folders I mention immediately below each file:

HTML5 Page Template with jQuery 1.5.1 & Modernizr 1.7

Drop this into “Visual Studio 2010 > Templates > ItemTemplates” folder

HTML5 Web Site Template with jQuery 1.5.1 & Modernizr 1.7

Drop this into “Visual Studio 2010 > Templates > ProjectTemplates” folder

Using the Templates

Once in place, all you have to do is select “File=>New Web Site” to use the new template:

To create a new HTML5 web page template, you’d select “File=>New File” to choose the HTML5 Page Template

Merging jQuery Deferreds and .animate()

Posted February 17, 2011 by Dan Heberden

Editor's Note: This article originally appeared on danheberden.com .

jQuery’s .animate() method, and the shorthand methods that use it, are fantastic tools to create animations. Creating animations that link together to achieve a particular effect, and do something specific at the end of the animation, can be a painful, messy task. Luckily, we have .queue() for mashing animations together.

But what happens when you want to bridge the gap between ajax requests and animating? When you want to queue a bunch of animations, get data from the server, and handle it all at once, without a crap-load of nested callbacks? That’s when jQuery.Deferred() puts on its cape, tightens its utility belt, and saves the day.

Disclaimer

I should note, however, that this is more-or-less giving an example of a pending feature request to add deferreds support in $.fn.animate . If the feature request is accepted and landed, it won’t show up until version 1.6 of jQuery. The principles, however, speak to jQuery’s flexibility and how to forge its multitude of great features into an even stronger tool.

While this works, its behavior isn’t consistent with that of jQuery. Namely, the new custom animate method doesn’t return ‘this’, but a Deferred object. However, that’s kind of the point of $.sub() : allowing you to copy the jQuery object and have your way with it. So, do try this at home – just don’t threaten my life if your site explodes.

The Demo

The following demo is a basic, distilled use-case for this kind of situation. Clicking the button opens a div that contains a loading message. While it’s opening, it is also querying the server for information to populate the box. Once both have finished, the loading div is hidden and the box with the retrieved data remains.

Modifying .animate()

Here is the code driving the change to .animate()

JavaScript:

  1. // create a sub of jquery (Basically, a copy we can mess with)
  2. var my$ = $.sub ( ) ;
  3.  
  4. // make my$ have a modified animate function
  5. my$.fn .animate = function ( props, speed, easing, callback ) {
  6.   // from jQuery.speed, forces arguments into props and options objects
  7.   var options = speed && typeof speed === "object" ?
  8.   jQuery.extend ( { } , speed) : {
  9.     complete: callback || ! callback && easing ||
  10.     jQuery.isFunction ( speed ) && speed,
  11.     duration: speed,
  12.     easing: callback && easing || easing &&
  13.     ! jQuery.isFunction ( easing) && easing
  14.   } ;
  15.  
  16.   // create the deferred
  17.   var dfd = my$.Deferred ( ) ,
  18.   // a copy of the complete callback
  19.   complete = options.complete ,
  20.   // and the count of how many items
  21.   count = this .length ;
  22.  
  23.   // make a new complete function
  24.   options.complete = function ( ) {
  25.     // that calls the old one if it exists
  26.     complete && complete.call ( this ) ;
  27.     // and decrements count and checks if it's 0
  28.     if ( !-- count ) {
  29.       // and when it is, resolves the DFD
  30.       dfd.resolve ( ) ;
  31.     }
  32.   } ;
  33.  
  34.   // all the hooks have been made, call the regular animate
  35.   jQuery.fn .animate .call ( this , props, options ) ;
  36.  
  37.   // return the promise that we'll do something
  38.   return dfd.promise ( ) ;
  39. } ;


While the comments explain just about everything, be sure to read up on $.sub() if you haven’t already. The new animate function on my$ simulates the method signature of the function, $.fn.animate , it’s attempting to replace. In short, speed , easing , and callback are forced into an options object — the same as if the second parameter was an object.

The deferred is created, a copy of the complete callback, and the count of how many items. Why? We want to fire the resolve() function on the deferred once all of the animations have finished. The complete() callback is replaced with a wrapper function that calls the original callback and decrements and checks the count. When the count reaches zero, all items have been animated and it’s safe to fire the resolve() function.

The untouched, standard version of $.fn.animate is called with the same ‘this’, properties, and the modified options object with the new complete wrapper function.

Returned is the promise, dfd.promise() , that lets $.when() do its awesomeness.

Putting it into action

If you haven’t familiarized yourself with deferreds, I highly recommend you read Eric Hynds’ fantastic article about it .

JavaScript:

  1. // retrieves content and updates a dom element
  2. // returns a promise
  3. function populateBox( ) {
  4.   return $.ajax ( {
  5.     url: 'your/server/url' ,
  6.     data : { } ,
  7.       type: "POST",
  8.       success: function ( data ) {
  9.         $( '#content' ) .slideDown ( ) .html ( data ) ;
  10.       }
  11.     } ) ;
  12.   }
  13.  
  14. // the "Get Message" click handler
  15. $( 'button.load' ) .click ( function ( ) {
  16.  
  17.   // save the button, box and loading as my$ objects
  18.   var $button = my$( this ) .hide ( ) ,
  19.   $box = my$( '#box' ) ,
  20.   $loading = my$( '.loading' ) ;
  21.  
  22.   // when the functions are done
  23.   $.when (
  24.     // $box was created with my$, so it will
  25.     // use the custom animate function
  26.     $box.slideDown ( ) ,
  27.     populateBox( )
  28.     // then run the 1st function on success
  29.     // and the second function if either fails
  30.   ) .then (
  31.     function ( ) {
  32.       // remove loading, we're done
  33.       $loading.slideUp ( ) ;
  34.     } ,
  35.     function ( ) {
  36.       // get that button back here
  37.       $button.show ( ) ;
  38.       // and hide the box
  39.       $box.slideUp ( ) ;
  40.     }
  41.   ) ;
  42. } ) ;


Because the new animate function was created on my$ , the copy of jQuery made using $.sub() , .hide() , .slideUp() , and other helper functions that use the custom .animate() function.

When the animation and ajax request both succeed, thus resolving the promise as true , the first callback function of $.then() is called. However, if one of them fails, the second will be called. You can re-run the demo (by clicking on the run button) and opt to fail the ajax request to see the second function get run. The .then() function is a handy mix of .done() and .fail() , which are useful if you want to provide multiple callbacks.

Summary

While I highly doubt this will be the solution to using deferreds with .animate() , I’m confident it’ll get the ball rolling. Too, it covers some other topics, such as $.sub() , deferreds, and wrapping functions with alternate behavior, that hopefully you found interesting.

Populate Select Boxes

Posted February 11, 2011 by Remy
It’s the age old (well, in webby terms) issue of how to populate one select box based on another’s selection. It’s actually quite easy compared with the bad old days, and incredibly easy with jQuery and a dash of Ajax. Watch Watch Populate Select Boxes screencast (Alternative flash version) QuickTime version is approximately 60Mb, flash [...]

Presenting at the jQuery Summit Online Conference on November 17th

Posted November 12, 2010 by Rey Bango

Next week, Environments for Humans will be hosting their 2nd jQuery Summit Online Conference and what a great event it will be. The speakers (myself included) are just an who’s-who of the jQuery world so you can be sure to get awesome presentations during the event. Lined up are experts like:

  • John Resig
  • Jonathan Snook
  • Richard Worth
  • Emily Lewis
  • …and a lot more.

The event is divided into two tracks targeting designers on the 16th and developers on the 17th. I’ll be presenting on the 17th and will be discussing how to use the new jQuery Templates plugin to make code layout much easier.

You can register for the event by going to the jQuery Summit website and when you do, be sure to take advantage of the following code for a 20% discount on your registration: JQUERY2010

The great thing about this is by registering, you’re also helping out the jQuery project as Environments for Humans is donating part of the proceeds of the conference to the jQuery Foundation.

I’m looking forward to this event and I hope to see you there as well!

How Polyfills “fill in the gaps” to make HTML5 and CSS3 Usable Today

Posted October 11, 2010 by Rey Bango

There’s been a lot of commotion over the last week since the W3C announced that HTML5 is not ready yet for deployment to websites . Some really smart people have weighed in on this topic and I agree with their thoughts. Last Thursday, I did a presentation on the new features of HTML5 and part of that was demonstrating how polyfills work to allow you to leverage these new features while still providing a good cross-browser experience.

What’s a Polyfill?

I really love Paul Irish’s definition since it sums it up perfectly:

polyfill: A shim that mimics a future API, providing fallback functionality to older browsers.

The basic premise is that most older browsers may not have all of the features of the HTML5 and CSS3 specifications and they need a helping hand to make them provide a good user experience. A great example of this are the new HTML5 semantic tags like <article>, <section>, <header> & <nav> which render fine in all major modern browsers like IE9 beta, Firefox, Chrome, Safari & Opera but lack support in popular browsers like IE6 through IE8.

So for my demo, I decided to create a simple page that showed a blog-like layout using these new tags while ensuring that they can still render correctly in IE8. Here’s the layout code I used.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Rey's Awesome HTML5 Blog</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width; initial-scale=1.0" />
     
    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
  
</head>
 
<body>
    
	<header>
        <h1>Rey's Awesome HTML5 Blog</h1>
	</header>

    <nav>
    	<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Contact</a></li>
		</ul>
    </nav>
    	
	<section>

        <header>
        <h1>Rey's Blog Posts</h1>
	    </header>

        <article>
            <header><h1>The In's & Out's of HTML5</h1></header>
		    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. Fusce vitae orci. </p>

            <footer>
                October 7, 2010 - comments( 0 )
            </footer>
        </article>

        <article>
            <header><h1>HTML5 Ate My Lunch</h1></header>
		    <p>Fusce vitae orci. Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. </p>
            <footer>
                October 5, 2010 - comments( 3 )
            </footer>
	    </article>		

	</section>
		
	<footer>
		<p>Copyright Rey Bango, 2010</p>
	</footer>

</body>
 </html>

I used a HTML5 reset style sheet because unfortunately, most browser don’t have an internal style sheet that sets the expected behavior for specific elements. For example, you would expect an <section> element to be block level but due to a lack of the internal browser style sheet, it renders inline.

Then, I added the styles I needed to get my page to look the way I wanted:

/* Global */
body { font-size: 16px; font-family: arial,helvetica,clean,sans-serif;  }
a { color : #33CC33; } 
a:hover { text-decoration: none; }

/* Header */
header h1 { font-size: 48px; }

nav { overflow: auto; margin-bottom: 25px; }
nav li {float:left; padding-right: 5px; }

/* Main Content Area */
section { width: 500px; font-size: 12px; }
section h1 { font-size: 16px; }

article { background: #CCCC99; margin-bottom: 10px; padding: 5px; -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; }
article footer { text-align: right; margin-right:5px; } 
article h1 { font-size: 12px; }

and when I tested it in Firefox 3.6.10, it looked exactly like I expected:

but look what happened when I tried to bring up the page in IE8:

None of the stylings were available because IE8 doesn’t recognize the new HTML5 elements. Further, in order to get IE6-8 to recognize these elements, you explicitly have to create the DOM nodes for them using JavaScript. The exact reason is unclear but it may be some type of parser bug. The following code needs to be in the <head> section of your page in order for the elements to be created and recognized by IE6-8:

document.createElement("header");
document.createElement("nav");
document.createElement("section");
document.createElement("article");
document.createElement("footer");

It’s a little bothersome to do that but it’s not a massive bit of code at least.

Enter Modernizr

The code I just listed to create your HTML5 elements is certainly useful but work has already been done to handle that for us via the awesome Modernizr JavaScript library . Not only does it act as a polyfill, creating these new elements for us automatically, but it offers a ton of detection capabilities for features of both HTML5 & CSS3. This allows you to determine how you will offer fallback support when a feature isn’t available.

Including Modernizr.js is incredibly easy since it’s only a one line script tag like this:

<script src="js/modernizr-1.5.min.js"></script>

As I mentioned, Modernizr is smart enough to determine when new semantic elements need to be created and will handle the dynamic creation of elements such as <article>, <section>, <header> & <nav> instead of you having to write JavaScript code to do it. So once I’ve added Modernizr to my page, I get the following results in IE8:

Now you’re probably looking at this screenshot and say, “Hey, you have no rounded corners!”. You’re right because I used the CSS3 border-radius property to create rounder corners for all of my <article> elements and IE8 doesn’t support that property. The important thing, though, is that IE8 now recognizes these new elements and allowed me to style them.

But What About those Rounder Corners?

Geez, you guys are so demanding! Okay, so the cool thing is that Modernizr offers detection of key features of HTML5 *and* CSS3 and with that, we can determine if something like border-radius is available and if not, using a new term coined by Alex Sexton, we’ll use “regressive enhancement ” to provide similar capabilities for older browsers. In this case, we’re going to see if border-radius is available and if not, lazyload in Mike Aslup’s jQuery Corners plugin to fill in the gap:

    <!-- Load jQuery -->
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
        // See if border-radius is available 
        if (!Modernizr.borderradius) {

            // If not, then load in the jQuery Corners plugin and apply rounded corners to the article elements
            $.getScript("js/jquery.corner.js", function () {
                $("article").corner();
            });

        }
    </script>


Now, when the code detects that border-radius is not available, it will just use the Corners jQuery plugin instead and render the following in any browser that doesn’t support the property:

Download the Code

I hope this post has shown you how polyfills can allow you to use HTML5 & CSS3 today. While I respect the W3C’s desire to ensure that the HTML5 specification is up-to-snuff, I think it’s important to realize that developers are resourceful and professional enough to create best practices that allow us to build apps with these new features right now.

I would highly recommend reviewing this VERY BIG LIST of polyfills and shims which can provide much of the missing capabilities in older browsers.

If you’d like to play with the code directly, I’ve packaged it up in a .zip file and you can download it here:

Code for HTML5 Semantic Tags using Polyfill to Degrade Gracefully (.zip)

How to Create HTML5 Website and Page Templates for Visual Studio 2010

Posted September 21, 2010 by Rey Bango

Now that I work at Microsoft, I’m using Visual Studio 2010 as my main editor. By default, an empty web page is created with an XHTML 1.0 doctype and it’s pretty barebones. Since I’m focusing on HTML5 & JavaScript development, having to constantly update the page with references to the new HTML5 doctype, jQuery, Modernizr and all of the other tags I use for my pages was becoming a drag.

Today, I noticed a blog post by Zander Martineau in which he added a lot of HTML5 goodness to the Coda IDE in the form of clips, which is the code snippet format supported by Coda. This got me inspired to find out how to do something similar in Visual Studio, so I pinged Damian Edwards of the Visual Studio team for advice. He pointed me to the following article which explained how to create “Item Templates” in Visual Stuido .

The gist of it is that you can take any page that you create and turn it into a re-usable template via the “File->Export Template…” wizard. It walks you through the process of choosing a specific file or entire project/website to use as a template.

Adding a Page Template

So here’s the basic HTML5 template I wanted to include:

<!doctype html>   
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title></title>
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<meta name="author" content="" />
	<meta name="viewport" content="width=device-width; initial-scale=1.0" />
	
    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
	
    <!-- !Modernizr - All other JS at bottom 
	<script src="js/modernizr-1.5.min.js"></script> -->

	<!-- Grab Microsoft's or Google's CDN'd jQuery. fall back to local if necessary -->
    <!-- <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script> -->
	<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> -->
	<script>	    !window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>

</head>

<body>
	<div id="container">

	</div>
</body>

</html>

After I created and saved this page, I went to “File->Export Template…” and followed these steps:

Now, when I select “File->New File…” to add a new item, my template is available:

Adding a Web Site Template

Creating this page template was a huge help. I can now start with a fresh template that specifically works for my style of development but I didn’t want to stop there. I also wanted to create a skeleton that I could use as the basis for new websites and I wanted it to package all of the important files that I use from the get-go. In this case, I wanted:

  • My HTML5 basic page template
  • jQuery
  • Modernizr
  • HTML5 Reset CSS file
  • An empty CSS file called style.css
  • A consistent folder structure for all of these

The first thing I needed to do was to create a new website in Visual Studio. From there, I needed to create and/or organize all of the files that I wanted as the basis for my skeleton. Using the same Export Template wizard, I followed the following steps to create my project skeleton:

So now when I select “File=>New Web Site” I see my new template:

and when I choose that, here’s what gets loaded for my new site:

Download the Templates

Note: The templates in this article have been updated to support jQuery 1.5.1 & Modernizr 1.7. Check it out here .

This is a huge time-saver for me and I want to share this. I’ve made both templates available for download so you can drop them into Visual Studio yourself. Just grab the specific file and drop the zip into the folder I specified:

HTML5 Page Template

Drop this into “Visual Studio 2010 > Templates > ItemTemplates” folder

HTML5 Web Site Template

Drop this into “Visual Studio 2010 > Templates > ProjectTemplates” folder

Introducing jQuery API Search

Posted September 10, 2010 by Karl Swedberg

Half-baked tutorials and plugins have been stacking up for months in my virtual kitchen, waiting for me to fire up the oven, finish the cooking, and spread them out on the table. For some reason, though, I've become less and less sure about whether I've put all the right ingredients into the mix. It's irritating, to be sure, but I'm tired of fretting about it. I'm going to consider this the first of what I hope to be many "taste tests" — experiments in various degrees of completion thrown against the wall to see what, if anything, sticks.

As some of you may know, the online jQuery documentation went through a major overhaul in January of this year, coinciding with the release of jQuery 1.4. Packt Publishing "open sourced" the jQuery 1.4 Reference Guide that Jonathan Chaffer and I had been writing, allowing us to put its entire contents (and more) on api.jquery.com . Some of you may also know that the raw XML content of the site is available as a single file , which has allowed other sites such as jqapi.com and idocs.brandonaaron.net to provide alternative views of that content. But what most of you probably do not know is that the jQuery API has been available for quite some time as a searchable API that returns the results in JSON format.

Note: The reason you probably don't know about it is that it's half-baked. So, please go easy on it until some smart people have a chance to look under the hood at what I'm doing. Crazy abuse will surely bring it to its knees.

Motivation

I wanted to let people access the jQuery documentation via JavaScript from any other site and pull out exactly what is needed. I also wanted to play around with JSONP. This fits both of those desires.

URL

To access the searchable API, use the following URL:

http://api.jquery.com/jsonp/

Examples

You can tap into the API with one of jQuery's Ajax methods. If you use $.get() or $.getJSON() , you'll need to append "?callback=?" to the URL. With $.get() , you'll also need to set the dataType argument to "jsonp".

Find entries in the API that have "class" in their name and then do something with them:

JavaScript:

  1. $.get ( 'http://api.jquery.com/jsonp/?callback=?' ,
  2.   { name : 'class' } ,
  3.   function ( data ) {
  4.     // do something with data
  5.   } ,
  6.   'jsonp' ) ;


Find all effects-category entries and then do something with them:

JavaScript:

  1. $.getJSON ( 'http://api.jquery.com/jsonp/?callback=?' ,
  2.   { category: 'effects' } ,
  3.   function ( json) {
  4.     // do something with json
  5. } ) ;


You can, of course, also use the low-level $.ajax() method.

Find entries with a title that ends in "ajax"; append a link for each to the document body:

JavaScript:

  1.   url: 'http://api.jquery.com/jsonp/' ,
  2.   dataType: 'jsonp' ,
  3.   data : { title: 'ajax' , match: 'end' } ,
  4.   success: function ( json) {
  5.     for ( var i= 0 , len= json.length ; i< len ; i++ ) {
  6.       var entry = json[ i] ;
  7.       $( '<a />' , {
  8.         href: entry.url ,
  9.         html : entry.title
  10.       } ) .appendTo ( 'body' ) ;
  11.     }
  12.   }
  13. } ) ;


Search Types

The JSONP API is searchable by name, category, and version. Searching by more than one criterion returns results that match all of the criteria. All searches are case-insensitive.

  • Search by name:
    • Key : title
    • Value : the name of any jQuery method, property, or selector
    • Searches in : post title and post slug
    • Substitutions : Before querying the database, all "$" are converted to "jQuery" and each instance of one or more spaces is converted to a hyphen ("-") for both the search values and the the post title and slug.
    • Default : all titles
  • Search by category name
    • Key : category
    • Value : category name
    • Substitutions : Before querying the database, each instance of one or more spaces is converted to a hyphen ("-")
    • Searches in : category slug
    • Default : all categories
  • Search by version number
    • Key : version
    • Value : a jQuery version number
    • Searches in : category slug for all categories that are a child of the main "version" category
    • Default : all versions

String Matching

The "match" parameter lets you be confine the results to those that match the entire search term, or just the start or end of it.

  • Key : match
  • Value : one of "start", "end", or "exact" (for search by version number, one of "end" or "exact")
  • Default : "anywhere", except for version number, which has a default of "start"

Returned Data

Data is returned as an array of objects. Each item in the array is an object representing a single method, property, or selector. For example, a result with one item would have the following structure:

JavaScript:

  1. [
  2.   {
  3.     "url" : "..." ,
  4.     "title" : "..." ,
  5.     "type" : "..." , // "method", "property", or "selector"
  6.     "signatures" : [
  7.     {
  8.       "added" : "..." ,
  9.       "params" : [
  10.       {
  11.         "name" : "..." ,
  12.         "type" : "..." ,
  13.         "optional" : "..." , // either "true" or an empty string
  14.         "desc" : "..." // description of the parameter
  15.       }
  16.       ]
  17.     }
  18.     ] ,
  19.     "desc" : "..." , // short description
  20.     "longdesc" : "..." , // long description
  21.     "return" : "..." // type of return value
  22.   }
  23. ]


Note that currently the examples/demos from each entry are not returned.

A (Fairly) Basic Demo

I put together a quick demo to give an idea of the API's flexibility. Type something into the "Name" field in the form below—say, "ajax"—and watch as the results come back. Inside the "Advanced" area, choose the "Matching... End " radio button and search again to see how the results differ.

✚ Search Again

jQuery API Search A demonstration

Advanced

Matching
Include in Results

Clear Results

A Little Less Basic Demo

I replicated this search form on a test server and added back-button support with Ben Alman's crazy delicious BBQ Plugin . Try out the demo .

But wait! There's more!

I put the whole shebang (well, except for the server-side stuff) in a GitHub repo. Clone it, fork it, have your way with it .

But Wait! There's Less!

As I mentioned above, this little project is incomplete. If you peek at the scripts, you'll quickly spot some major chunks of code in need of refactoring. Also, had I but world enough and time, I'd use a nice templating system such as mustache.js or the jQuery Templates plugin to output the search results. But I'll leave all that for another day (or another developer).