If you're comfortable with jQuery but a bit shaky with JavaScript, this concise guide will help you expand your knowledge of the language - especially the code that jQuery covers up for you. Many jQuery devotees write as little code as possible, but with some JavaScript under your belt, you can prevent errors, reduce overhead, and make your application code more efficient.
This book explores event handling, prototypes, and working with the DOM and AJAX through examples and lots of code. You'll learn common conventions and patterns in JavaScript and - if you've never coded with JavaScript before—a tutorial will take you through the basics.
The best way to explain events is probably by using an example, and the best example (as I’m assuming that you know jQuery) is to show an extract of jQuery code that works with events. The following code turns the anchor element with ID foo red when it is clicked, and then prevents the link from being followed by calling e.preventDefault():
$('a#foo').click(function (e) {
$(this).css('color', 'red');
e.preventDefault();
});
Events in JavaScript
Following is the same code, but in pure JavaScript. It will not work in IE8 and below, which we will cover in the next section:
So which are fired first, bubbling or captured event listeners? Does the event start at the element, bubble up, and then capture back down again, or does it start at the document? The WC3 specifies that events should capture down from the document, and then bubble back up again, which you can see in Figure 1-3.