Some other important things to know when scripting with JavaScript. 

JavaScript is Case Sensitive

A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar".
JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables, objects and functions.

White Space

JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent:
name="Hege";
name = "Hege";


Break up a Code Line

You can break up a code line within a text string with a backslash. The example below will be displayed properly:
document.write("Hello \
World!")
However, you cannot break up a code line like this:
document.write \
("Hello World!");




In JavaScript you can add special characters to a text string by using the backslash sign.

Insert Special Characters

The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string.
Look at the following JavaScript code:

var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
   

In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called
To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:

var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);

JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.
Here is another example:

document.write ("You \& I are singing!");

The example above will produce the following output:
You & I are singing!
The table below lists other special characters that can be added to a text string with the backslash sign:
Code Outputs
\' single quote
\" double quote
\& ampersand
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed


The throw statement allows you to create an exception.


The Throw Statement

The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

Syntax

throw(exception)
The exception can be a string, integer, Boolean or an object.
Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

Example

The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:


<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
  {
  if(x>10)
    {
    throw "Err1";
    }
  else if(x<0)
    {
    throw "Err2";
    }
  else if(isNaN(x))
    {
    throw "Err3";
    }
  }
catch(er)
  {
  if(er=="Err1")
    {
    alert("Error! The value is too high");
    }
  if(er=="Err2")
    {
    alert("Error! The value is too low");
    }
  if(er=="Err3")
    {
    alert("Error! The value is not a number");
    }
  }
</script>
</body>
</html>




The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:




<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Click OK to continue viewing this page,\n";
  txt+="or Cancel to return to the home page.\n\n";
  if(!confirm(txt))
    {
    document.location.href="http://www.w3schools.com/";
    }
  }
}
</script>
</head>


<body>
<input type="button" value="View message" onclick="message()" />
</body>


</html>


The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

Syntax

try
  {
  //Run some code here
  }
catch(err)
  {
  //Handle errors here
  }

Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!


Example

<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.description + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>
</head>


<body>
<input type="button" value="View message" onclick="message()" />
</body>


</html>


When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.

The try...catch statement allows you to test a block of code for errors.




onMouseOver and onMouseOut are often used to create "animated" buttons.
Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected:



<a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a>



The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:


<form method="post" action="xxx.htm" onsubmit="return checkForm()">



The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:
<input type="text" size="30" id="email" onchange="checkEmail()">


The onLoad and onUnload events are triggered when the user enters or leaves the page.
The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".


Events are actions that can be detected by JavaScript.

Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.
Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.
Examples of events:
  • A mouse click
  • A web page or an image loading
  • Mousing over a hot spot on the web page
  • Selecting an input field in an HTML form
  • Submitting an HTML form
  • A keystroke
Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!



The for...in statement loops through the elements of an array or through the properties of an object.

Syntax

for (variable in object)
  {
  code to be executed
  }

Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.

Example

Use the for...in statement to loop through an array:

Example

<html>
<body>

<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
  {
  document.write(mycars[x] + "<br />");
  }
</script>

</body>
</html>


The continue statement will break the current loop and continue with the next value

Example

.
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    continue;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>


The break statement will break the loop and continue executing the code that follows after the loop (if any).

Example



<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    break;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }
</script>
</body>
</html>


A little known but cool feature of Internet Explorer is its support for XML data islands. Basically, you can embed some XML data in a page like this:
<html>
 <head>
  <xml>
   <root>Some dataroot>
  xml>
 head>
Even cooler, you can reference an external data source:
<xml src="data.xml">xml>

The classic “Ajax” way to load XML data involves a couple of ActiveX objects:
var http = new ActiveXObject("Microsoft.XMLHTTP");
http.open("GET", "data.xml", false);
http.send(null);
var xmlDocument = http.responseXML;
responseXML is a tricky beast, on most platforms it refers to an XML document. This means you can do things like access the root node through the documentElement property. Unfortunately this does not work on Internet Explorer:
alert(xmlDocument.documentElement);
// ==> [object Element] for Mozilla
// ==> null             for Internet Explorer 
To create a true XML document for Internet Explorer you must use the responseText property and another ActiveX object to parse it:
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
xmlDocument.loadXML(http.responseText);
An easier way to achieve the same result without ActiveX is this:
var xml = document.createElement("xml");
xml.src = "data.xml";
document.body.appendChild(xml);
var xmlDocument = xml.XMLDocument;
document.body.removeChild(xml);
The code above will load and parse an external XML file. The resulting object is a true XMLresponseXML returned by the XMLHttpRequest document which can be treated the same as the object on other platforms.
The above code will only work on a local file system. When dealing with remote data you check the readyState property to ensure that the data has been fully loaded. You can also trap the onreadystatechange event as you would for the XMLHttpRequest object.



Enumeration lies at the heart of DOM Scripting:
var lists = document.getElementsByTagName("UL");
for (var i = 0; i < lists.length; i++) {
  lists[i].className = "menu";
}

for (var i = 0; i < array.length; i++) {
  print(array[i]);
}

for (var key in object) {
  print(object[key]);
}
Us JavaScripters are forever writing loops like these. To ease the strain on our keyboards Mozilla recently introduced a handy forEach method for arrays:
array.forEach(print);
If you don’t understand the code above then go and read the documentation.
That’s fine for arrays but what about DOM node lists? That’s where most of our loop writing is concentrated. Fortunately, the clever Mozilla developers provide generic array methods to help us:
var lists = document.getElementsByTagName("UL");
Array.forEach(lists, function(list) {
  list.className = "menu";
});
Cool huh? The Array.forEach method treats any object passed to it as if it were an array. So long as that object has a length property then we are OK.
We can easily implement this method for non-Mozilla browsers:
// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
  Array.forEach = function(object, block, context) {
    for (var i = 0; i < object.length; i++) {
      block.call(context, object[i], i, object);
    }
  };
}
I’ve been using this technique for enumeration quite a lot recently and I decided to extend the idea:
// generic enumeration
Function.prototype.forEach = function(object, block, context) {
  for (var key in object) {
    if (typeof this.prototype[key] == "undefined") {
      block.call(context, object[key], key, object);
    }
  }
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
  if (object) {
    var resolve = Object; // default
    if (object instanceof Function) {
      // functions have a "length" property
      resolve = Function;
    } else if (object.forEach instanceof Function) {
      // the object implements a custom forEach method so use that
      object.forEach(block, context);
      return;
    } else if (typeof object.length == "number") {
      // the object is array-like
      resolve = Array;
    }
    resolve.forEach(object, block, context);
  }
};
This allows me to write loops without knowing what kind of object I’m dealing with:
function printAll() {
  forEach (arguments, function(object) {
    forEach (object, print); 
  });
};
// or
forEach (document.links, function(link) {
  link.className = "super-link";
});
// or
forEach ([1, 2, 3], print);
forEach ({a: 1, b: 2, c: 3}}, print);
// etc

Explanation

The global forEach function allows us to enumerate any object according to its type. If the object is array-like (has a length property) then we enumerate it like an array. All other objects are enumerated using the standard for var x in y mechanism.
When enumerating over objects, the discovered keys are compared against Object.prototype. If the key is defined on the Object object then it is not enumerated. That means that you cannot enumerate the built-in methods like toString and valueOf.
The global forEach function will delegate the enumeration of functions to Function.forEach. So, if you choose to enumerate over a Function object you will skip the built-in methods there too.

The Kick-Ass Bit

Although I’ve defined a forEach method on Function.prototype this is never called by the global forEach function (except when you are enumerating functions).
I’ve provided this as a bonus feature. :-) Basically, by calling the forEach method on a function you can enumerate an object and compare the keys with that function’s prototype. That means that you will only enumerate custom properties of the object. An example is required:
// create a class
function Person(name, age) {
  this.name = name || "";
  this.age = age || 0;
};
Person.prototype = new Person;

// instantiate the class
var fred = new Person("Fred", 38);

// add some custom properties
fred.language = "English";
fred.wife = "Wilma";
Enumerate using the standard forEach method:
forEach (fred, print);
// => name: Fred
// => age: 38
// => language: English
// => wife: Wilma
Enumerate using the Person.forEach method:
Person.forEach (fred, print);
// => language: English
// => wife: Wilma
Note that the properties defined on the prototype are not enumerated in the second example.


Asynchronous JavaScript + XML, is not a new technology or a new programming language. It is a term coined in 2005 by Jesse James Garrett, which describes a “new” approach to using a number of existing technologies together, including: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and the XMLHttpRequest object. It is a new technique for creating better, faster, and more interactive web applications.
When these technologies are combined in the AJAX model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly.
AJAX is about better Internet-applications
Internet-applications have many benefits over desktop applications; they can reach a larger audience, they are easier to install and support, and easier to develop. However, Internet-applications are not always as “rich” and user-friendly as traditional desktop applications and most Web applications are slow and tedious. In the traditional Web application, the interaction between the customer and the server goes like this:
1. Customer accesses Web application
2. Server processes request and sends data to the browser while the customer waits
3.Customer clicks on a link or interacts with the application
4.Server processes request and sends data back to the browser
while the customer waits
5. etc…. There is a lot of customer waiting. It’s a model adapted from the Web’s original use as a hypertext medium.
How Ajax is Different
An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something
Ajax Acts as an Intermediary
The Ajax engine works within the Web browser (through JavaScript and the DOM) to render the Web application and handle any requests that the customer might have of the Web server. The beauty of it is that because the Ajax engine is handling the requests, it can hold most information in the engine itself, while allowing the interaction with the application and the customer to happen asynchronously and independently of any interaction with the server.
Asynchronous
This is the key. In standard Web applications, the interaction between the customer and the server is synchronous. This means that one has to happen after the other. If a customer clicks a link, the request is sent to the server, which then sends the results back. With Ajax, the JavaScript that is loaded when the page loads handles most of the basic tasks such as data validation and manipulation, as well as display rendering the Ajax engine handles without a trip to the server. At the same time that it is making display changes for the customer, it is sending data back and forth to the server. But the data transfer is not dependent upon actions of the customer.


Custom checkbox elements
custom checkboxes demo
This idea came about from AOL's use of image checkboxes in the recently launched version of their WebMail product as a means of selecting email messages rather than standard checkboxes. The images you see are inserted after each input element who's type attribute is "checkbox" for every form found in the document. The original checkbox has its display set to "none" and all events that are assigned to that checkbox are then assigned to the image. The images are given alt attributes that describe their current status as well.

Scrollable checklists

An alternative to the select element with enabled multiple attribute. Enjoy scrollable checklists without all the hassle of worrying about deselecting previously-selected options.
This script is compatible with: IE 5.0+, Firefox 0.8+ for Win32 platform and Safari 1.2+, IE 5.2, Camino 8.2+, Netscape 7+, OmniWeb 4.1+, iCab 3.0+ for Apple Macintosh platform.



JotForm

JotForm is web based WYSIWYG form builder. You can design forms to use somewhere else or design forms and let this service collect the data for you as well. Solution is completely free. JotForm requires a javascript and cookies enabled browser. Currently it is completely tested on Firefox and Internet Explorer.
DESCR



Styled Form Controls

Typically, textareas, buttons and text fields have been easy enough to style and the functionality to use images as buttons is inherant to HTML. The styled form controls needed to be dynamically inserted into the page using a javascript. No javascript, no change.
formStyle has been tested in the following browsers: Internet Explorer 7 (Beta 1), 100% Compatibility, some cosmetic flicker issues when toggling controls. Mozilla Firefox 1.0.6 - Full compatibility. Netscape Navigator 7.2 - Full compatibility. Netscape 6.0 - Full compatibility. Minor CSS-styling fault in BigOrb example. Opera Browser 8.0 - Full compatibility.



CRIR: Checkbox & Radio Input Replacement

This combination of JavaScript and CSS will hide checkbox and radio inputs that have a class = "crirHiddenJS", an id, and a proper label tag.
This will allow you to style the label however you wish using CSS, and the actual input control will be hidden. The form will still collect data as it normally would because the label itself will trigger the hidden input control. If javascript is disabled no inputs will be hidden and the form is still be fully functional.



wForms - A Javascript Extension to Web Forms

wForms is an open-source, unobtrusive javascript library that adds commonly needed behaviors to traditional web forms without the need for any programming skill.



Niceforms

Since normal input fields (including radio buttons, checkboxes, textareas, etc) can only be styled to a small degree, we'll just go ahead and hide them while replacing their visual appearance with our own custom look.
It works great in Mozilla(Win) and IE6. There are some display issues on IE5.x and Opera that can be corrected in the next version.



Really easy field validation with Prototype
Prototype field validation
Robust javascript validation library that is simple to implement and didn't require do any extra work other than creating the form. It is easy with Prototype.




Narrative JavaScript
Narrative JavaScript is a small extension to the JavaScript language that enables blocking capabilities for asynchronous event callbacks. This makes asynchronous code refreshingly readable and comprehensible.

Javascript With Advanced Continuation Support
Asynchronous operations written in a synchronous style: Traditional Ajax applications require the programmer to either write a maze of event handlers, or to provide only extremely simple and idempotent operations. Jwacs provides library functions that make asynchronous operations such as an XMLHttpRequest appear synchronous.



JsLINB - Javascript framework of LINB
LINB(Lazy Internet and Browser) is designed to allow developers coding in a more targetable, clearly, and efficiently way, which is platform-independent, language-independent, and C/S, B/S, RIA compatible.
Thread feature: javascript thread implementation that can control the sequence of asyn functions.



Concurrent XML Queries with AJAX
Solution that would reduce the wait time, but second reduce the amount of data shown to the user, as it is mostly similar data consolidating and filtering the data before returning it to the user is essential. Some sort of threaded model similar to the observer/observable model, where each XML query is launched on its own 'thread'.




01
AutoComplete from phpguru.org
Phpguru autocomplete
A Javascript library which provides an autocomplete dropdown which you can attach to one or more form inputs (typically text inputs, or textareas). It functions the same as the Internet Explorer autocomplete dropdown, and works on MSIE, and Firefox (tested on IE6, 5.5 & 5 and Firefox 1.0.1).
02
WICK AutoComplete
WICK AutoComplete demo

This is WICK, the Web Input Completion Kit, an evolving framework that leverages web standards such as JavaScript, DOM and CSS to facilitate textual input in form UI elements assisted by local and remote data sources. This framework strives to remain unobtrusive and preserve a form's semantics and accessibility.


03
Script.aculo.us Autocompleter
Script.aculo.us demo version

Easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly. It's an add-on to the Prototype framework. Autocompleting text fields with this library is very easy.


04
BComplete Autosuggest Script
Bcomplete java script solution
BComplete is an autocomplete (or auto-suggest, perhaps) script for web applications, similar to what Google and Yahoo employ in some of their online programs.


05
Autocompletition by Wiseguysonly
Autocompletion with AJAX
Ajax autocompletion for the impatient. Making input fields that attempt to second guess what your user is typing based on live data. This is the PHP mix, but it is presented out-of-depth enough to make it easily extensible into the language of your choice (e.g. ASP, ColdFusion, Perl, Ruby etc).


06
Autocomplete control from Momche
Autocomplete control with dropdown
To use this script the INPUT field's tag, which will be autocompleted should have an attribute autocomplete. Tested with: IE 5+, Mozilla (NS 6,7)


07
AutoSuggest: An AJAX auto-complete text field
AutoSuggest text field
The AutoSuggest class adds a popdown menu of suggested values to a text field. The user can either click directly on a suggestion to enter it into the field, or navigate the list using the up and down arrow keys, selecting a value using the tab key. The values for the suggestion list are to provided as XML (by a PHP script, or similar).


08
Ajax dynamic list
Ajax dynamic list script
This script shows you a list of options based on what you type into a text input. Example: Type in "A" and Ajax will get you a list of all contries starting with "A".


09
AutoSuggest
AutoSuggest
An attempt at a simple method for javascript-based suggestion dropdowns for autocompletion. Text input fields with customized automatic completion have lots of great uses. This script is an attempt at providing a solution to the problem that is clear and modular enough to be easily hacked up and modified for other uses.


10
XMLHttpRequest Autocomplete
Type the first few letters of an english word in the text field and pause for a second. You can use the arrow keys and mouse to navigate the list of suggestions. Tab, enter, or clicking will replace the contents of the text field with the selected entry from the list.


11
GMail-style text completion for text input elements
This implementation works for recent versions of Mozilla, Firefox and Internet Explorer. Simply type a character or two. After a (customisable) delay, a remote database will be queried for suitable completions, these completions will be presented to you in a drop-down style box. Make your selection with the Up/Down keys followed by Enter.


12
Nitobi AJAX components demo
The Ultimate Ajax-powered Autocomplete Solution. Featuring six unique search modes with support for multiple platforms and browsers. Perform paging, suggestive searching, and fuzzy-searching in an easy-to-implement interface.


13
Capxous framework
Capxous javascript framework
The most elegant AJAX autocomplete component in community User types in text field. JavaScript makes the retrieval URL then sends an AJAX request. JavaScript shows suggestion list received from the server side.