JavaScript: A Tutorial
JavaScript is a programming language typically implemented in web browsers to allow user interactions with the web page. In the HTML/CSS/JavaScript combination, HTML markups the content of a web page, CSS styles the presentation, and JavaScript controls the behavior. Some examples of behavior on a web page include: hide-and-show, drag-and-drop, and form validation.
JavaScript has all the basic features of programming languages, such as variables, functions, conditionals, loops, etc. JavaScript is a script language; it is interpreted and run by the web browser.
A Brief History of JavaScript
- 1995, invented in Netscape
- 1996, adopted by Microsoft IE, under the name JScript
- 1999, standardized as ECMAScript V3
- 1999, XMLHttpRequest was introduced in major browsers
- 2005, the term AJAX (Asynchronous JavaScript and XML) was coined. Many JavaScript frameworks and libraries become popular.
JavaScript was invented in Netscape; however, Netscape lost the web browser war to Microsoft IE around 2000. After that, JavaScript was considered as a language for “amateurs” but not professional programmers. Until 2005, the need of fast web signified the AJAX framework, and JavaScript became the dominate web technology. Note that, the essentials of AJAX (XMLHttpRequest) were ready even in 1999 in most browsers, but that was not popular until 2005.
How to Add JavaScript to a Web Page?
Just as CSS, there are three ways to include JavaScript in a web page: inline, embedded, and external.
Inline script is directly written inside the HTML tags. This approach mixes the behavior with the structure; it should be avoided.
Embedded script is to use the “script” tag to add JavaScript codes inside HTML. This way is OK if the script is specific for the residing page.
<script type="text/javascript"> doSomething(); </script>
External script is the best way to use JavaScript in HTML. Here we use the “script” tag to include a path to an external JavaScript file.
<script type="text/javascript" src="something.js"> </script>
The “script” element can be put inside the head or body of an HTML file. However, note that, it will be loaded and run when the “script” element is parsed by the browser. That means the browser has not completely construct the DOM tree. Therefore, if we wish to manipulate the DOM, the script should be added (run) just before the closing “body” tag.
JavaScript Language Basics
As a programming language, JavaScript has variables, operations, strings, arrays, functions, conditionals and loops. Note that, JavaScript is weakly-typed; the types of variables are determined at the run time.
var foo = 7; var bar = 3 + 4 * 5; var arr = [3, 4, 5]; var str = "JavaScript"; if (something) { // Do something } while (something) { // Do something } for (var i = 0; i < 10; i++) { // Do something }
Functions in JavaScript are first-class members; JavaScript is a functional programming language. There are two ways to define functions: named or anonymous.
function add(a, b) { return a + b; } var add2 = function(a, b) { return a + b; } add(4, 5); // gives 9 add2(4, 5); // gives 9
JavaScript is object-oriented; everything is an object. An object is essentially a hashmap of key-value pairs, where the keys are properties or methods. JavaScript is prototype-based (instance-based), and there is no “class” in JavaScript; this is different from class-based languages like C++ or Java.
var point = {}; point.x = 4; point.y = 5; point.add = function() { return this.x + this.y; } var obj = { language: 'Java' }; obj.language = 'C'; obj.easy = true; // two ways of accessing properties obj['easy'] = false;
Iterations over arrays or objects can be done using the for-each statements.
var arr = ['Alice', 'Bob', 'Carl']; for (var i in arr) { alert(arr[i]); } var obj = {a: 'Alice', b: 'Bob'}; for (var key in obj) { alert(obj[key]); }
In JavaScript, a closure is a special object which has two part: a function, and the context that the function was created; the context mainly means the local variables referred by the function. In JavaScript, variables either have a global scope or a function scope. Only functions create scope for variables; brackets do not.
function getCounter() { var i = 0; return function(){ i++; alert(i); } } var ctr = getCounter(); ctr(); // i == 1 ctr(); // i == 2
In the code above, function getCounter creates a context for local variable i and also the returned anonymous function. Whenever getCounter is called, it creates the context, and return a new function which lives in that context. Thus, the local variables are somehow associated with the returned new function. This feature can be used to implement object-oriented design patterns.
JavaScript and DOM
JavaScript interacts the web page through the DOM (Document Object Model). Recall that the DOM is the internal structure that the web browser uses to render a HTML page.
There is a slight difference between the terminologies in HTML and in JavaScript. HTML elements and attributes are referred to as nodes and properties in JavaScript.
A web page is represented with the “document” object, which is also a “Node” object. There are several get methods to grab elements inside the document: getElementById(), getElementsByTagName().
HTML: <div id="help"> ... </div> CSS #help { ... } JavaScript document.getElementById('help');
HTML <p>...</p><p>...</p><p>...</p> CSS p { ... } JavaScript document.getElementsByTagName('p');
These methods belong to the Node object; they can be chained together.
HTML <div id="help"> ... </div> <p>...</p><p>...</p><p>...</p> </div> JavaScript document.getElementById('help').getElementsByTagName('p');
The properties of the Node object allows visiting neighboring nodes in the DOM tree. The following are some of the Node properties: parentNode, childNodes, firstChild, lastChild, previousSibling, nextSibling.
The following method uses recursion and the firstChild and nextSibling properties to walk through a DOM tree.
function walkDOM(node, func) { func(node); node = node.firstChild; while (node) { walkDOM(node, func); node = node.nextSibling; } }
Since the standard JavaScript does not provide get elements by class name, the following code does this using the node properties.
function getElementsByClassName(className) { var result = []; walkDOM(document.body, function(node) { var c = node.className; if (!c) return; var a = c.split(' '); for (var i = 0; i < a.length; i++) { if (a[i] === className) { result.push(node); break; } } }); return result; }
One thing to be careful is that, if the JavaScript code accesses the DOM, we have to make sure the DOM is ready on the browser side when the code runs. A common solution to put the code running the script at the end of the body tag.
<html> <head> <script type="text/javascript" src="help.js"></script> </head> <body> ...... <script type="text/javascript"> initialize(); </script> </body> </html>
Oftentimes we want to attach events to the elements. Events occur whenever some action happen on the web page, for example click, mouseover, mouseup. The browser has an event-driven, asynchronous programming model.
Events are targeted to particular nodes. Events cause the invocation of event handler (listener) functions. The following are way to attach handlers to events.
IE:
elem.attachEvent(‘onclick’, doWork);
Other browsers:
elem.addEventListener(‘click’, doWork, false);