Friday, August 31, 2012

JavaScript and HTML DOM Reference


JavaScript Objects Reference

The references describe the properties and methods of each object, along with examples.

Browser Objects Reference

The references describe the properties and methods of each object, along with examples.

Core DOM Objects Reference

The references describe the properties and methods of each object, along with examples.

HTML DOM Objects Reference

The references describe the properties and methods of each object, along with examples.

JavaScript Quiz Test


You can test your JavaScript skills with W3Schools' Quiz.

The Test

The test contains 20 questions and there is no time limit.
The test is not official, it's just a nice way to see how much you know, or don't know, about JavaScript.

Count Your Score

You will get 1 point for each correct answer. At the end of the Quiz, your total score will be displayed. Maximum score is 20 points.

JavaScript HTML DOM Examples


Examples of using JavaScript to access and manipulate the HTML DOM objects.

Document Object

Write text to the output with document.write()
Write formatted text to the output with document.write()
Return the number of anchors in a document
Return the innerHTML of the first anchor in a document
Return the number of forms in a document
Return the name of the first form in a document
Return the number of images in a document
Return the id of the first image in a document
Return the number of links in a document
Return the id of the first link in a document
Return all name/value pairs of cookies in a document
Return the domain name of the server that loaded the document
Return the date and time the document was last modified
Return the URL of the document that loaded the current document
Return the title of a document
Return the full URL of a document
Open an output stream, and add some text
Open an output stream in a new window, and add some text
Difference between write() and writeln()
Alert innerHTML of an element with a specific ID
Alert the number of elements with a specific name
Alert the number of elements with a specific tagname
More Document object examples in our JavaScript reference.

Anchor Object

More Anchor object examples in our JavaScript reference.

Area Object

More Area object examples in our JavaScript reference.

Base Object

More Base object examples in our JavaScript reference.

Button Object

More Button object examples in our JavaScript reference.

Form Object

More Form object examples in our JavaScript reference.

Frame/IFrame Objects

More Frame/IFrame object examples in our JavaScript reference.

Image Object

More Image object examples in our JavaScript reference.

Event Object

onblur - Execute a JavaScript when a user leaves an input field
onchange - Execute a JavaScript when a user changes the content of an input field
onclick - Execute a JavaScript when a button is clicked
ondblclick - Execute a JavaScript when a button is double-clicked
onerror - Execute a JavaScript if an error occurs when loading an image
onfocus - Execute a JavaScript when an input field gets focus
onkeydown - Execute a JavaScript when a user is pressing/holding down a key
onkeypress - Execute a JavaScript when a user is pressing/holding down a key
onkeyup - Execute a JavaScript when the user releases a key
onload - Execute a JavaScript immediately after a page has been loaded
onload - Execute a JavaScript immediately after an image has been loaded
onmousedown + onmouseup - Execute scripts when pressing/releasing a mouse button
onmousedown - Alert which mouse button the user pressed
onmousedown - Alert the name of the element a user clicked on
onmousemove + onmouseout - Execute scripts when moving the mouse pointer over/out of an image
onmouseover + onmouseout - Execute scripts when moving the mouse over/out of an image
onresize - Execute a JavaScript when the browser window is resized
onselect - Execute a JavaScript after some text has been selected
onunload - Execute a JavaScript before the browser closes the document
What is the keycode of the key pressed?
What are the coordinates of the cursor?
What are the coordinates of the cursor, relative to the screen?
Was the shift key pressed?
Which event type occurred?

Option and Select Objects

Table, TableHeader, TableRow, TableData Objects


JavaScript Browser Objects Examples


Examples of using JavaScript to access and manipulate the Browser objects.

Window Object

Display an alert box
Display an alert box with line-breaks
Display a confirm box, and alert what the visitor clicked
Display a prompt box
Create a pop-up window Open a new window when clicking on a button
Open a new window and control its appearance
Open multiple new windows
Assure that the new window does NOT get focus (send it to the background)
Assure that the new window GETS focus
Close the new window
Checks whether the new window has been closed or not
Return the name of the new window
Write some text to the source (parent) window
Move the new window relative to its current position
Move the new window to the specified position
Print the current page
Resize a window by the specified pixels
Resize a window to a specified size
Scroll the content by the specified number of pixels
Scroll the content to a specified position
A simple timing
Set and stop a timer with setTimeout() and clearTimeout()
Set and stop a timer with setInterval() and clearInterval()
More Window object examples in our JavaScript reference.

Navigator Object

More Navigator object examples in our JavaScript reference.

Screen Object

More Screen object examples in our JavaScript reference.

History Object

More History object examples in our JavaScript reference.

Location Object

More Location object examples in our JavaScript reference.

JavaScript Objects Examples


Examples of using the built-in JavaScript objects.

String Object

More String object examples in our JavaScript reference.

Date Object

More Date object examples in our JavaScript reference.

Array Object

More Array object examples in our JavaScript reference.

Boolean Object

More Boolean object examples in our JavaScript reference.

Math Object

General

More Math object examples in our JavaScript reference.

JavaScript Examples


Basic JavaScript Examples


JavaScript Statements, Comments and Blocks


JavaScript Variables


JavaScript Conditional If ... Else


JavaScript Popup Boxes


JavaScript Functions


JavaScript Loops


JavaScript Events


JavaScript Error Handling


Advanced JavaScript Examples


Have You Learned JavaScript?


JavaScript Summary

This tutorial has taught you how to add JavaScript to your HTML pages, to make your web site more dynamic and interactive.

You have learned how to create responses to events, validate forms and how to make different scripts run in response to different scenarios.

You have also learned how to create and use objects, and how to use JavaScript's built-in objects.
For more information on JavaScript, please look at our JavaScript examples and our JavaScript reference.

Now You Know JavaScript, What's Next?

The next step is to learn about the HTML DOM, jQuery, and AJAX.
If you want to learn about server-side scripting, the next step is to learn ASP or PHP.

HTML DOM
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
The HTML DOM is platform and language independent and can be used by any programming language like Java, JavaScript, and VBScript.

If you want to learn more about the DOM, please visit our HTML DOM tutorial.

jQuery
jQuery is a JavaScript Library.
jQuery greatly simplifies JavaScript programming.

If you want to learn more about jQuery, please visit our jQuery tutorial.

AJAX
AJAX = Asynchronous JavaScript and XML.
AJAX is not a new programming language, but a new way to use existing standards.
AJAX is about exchanging data with a server, and update parts of a web page - without reloading the whole page.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
If you want to learn more about AJAX, please visit our AJAX tutorial.

ASP / PHP
While scripts in an HTML file are executed on the client (in the browser), scripts in an ASP/PHP file are executed on the server.

With ASP/PHP you can dynamically edit, change or add any content of a Web page, respond to data submitted from HTML forms, access any data or databases and return the results to a browser, customize a Web page to make it more useful for individual users.

Since ASP/PHP files are returned as plain HTML, they can be viewed in any browser.

If you want to learn more about ASP, please visit our ASP tutorial.
If you want to learn more about PHP, please visit our PHP tutorial.

JavaScript Create Your Own Objects


Objects are useful to organize information.

Try it Yourself - Examples


JavaScript Objects

Earlier in this tutorial we have seen that JavaScript has several built-in objects, like String, Date, Array, and more. In addition to these built-in objects, you can also create your own.

An object is just a special kind of data, with a collection of properties and methods.

Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

Properties

The syntax for accessing a property of an object is:

objName.propName

You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:

personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=30;
personObj.eyecolor="blue";

document.write(personObj.firstname);

The code above will generate the following output:
John

Methods

An object can also contain methods.

You can call a method with the following syntax:

objName.methodName()

Note: Parameters required for the method can be passed between the parentheses.
To call a method called sleep() for the personObj:
personObj.sleep();


Creating Your Own Objects

There are different ways to create a new object:

1. Create a direct instance of an object

The following code creates a new instance of an object, and adds four properties to it:

personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
alternative syntax (using object literals):
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj:
personObj.eat=eat;

2. Create an object constructor

Create a function that construct objects:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand.

Once you have the object constructor, you can create new instances of the object, like this:

var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");
You can also add some methods to the person object. This is also done inside the function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}

Note that methods are just functions attached to objects. Then we will have to write the newlastname() function:

function newlastname(new_lastname)
{
this.lastname=new_lastname;
}

The newlastname() function defines the person's new last name and assigns that to the person. 

JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").

JavaScript Timing Events



With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:
  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

setInterval("javascript function",milliseconds);

The first parameter of setInterval() should be a function.

The second parameter indicates the length of the time-intervals between each execution.

Note: There are 1000 milliseconds in one second.

Example

Alert "hello" every 3 seconds:
setInterval(function(){alert("Hello")},3000);

Try it yourself »

The example show you how the setInterval() method works, but it is not very likely that you want to alert a message every 3 seconds.

Below is an example that will display the current time. The setInterval() method is used to execute the function once every 1 second, just like a digital watch.

Example

Display the current time:
function myFunction()
{
setInterval(function(){myTimer()},1000);
}

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}

Try it yourself »

How to Stop the Execution?

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

clearInterval(intervalVariable)

To be able to use the clearInterval() method, you must use a global variable when creating the interval method:

myVar=setInterval("javascript function",milliseconds);

Then you will be able to stop the execution by calling the clearInterval() method.

Example

Same example as above, but we have added a "Stop the timer" button:
var myVar;

function myFunction()
{
myVar=setInterval(function(){myTimer()},1000);
}

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}

function myStopFunction()
{
clearInterval(myVar);
}

Try it yourself »

The setTimeout() Method

Syntax

setTimeout("javascript function",milliseconds);

The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.

The first parameter of setTimeout() should be a function.

The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

Example

Wait 3 seconds, then alert "Hello":
setTimeout(function(){alert("Hello")},3000);

Try it yourself »

How to Stop the Execution?

The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.

Syntax

clearTimeout(timeoutVariable)

To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:

myVar=setTimeout("javascript function",milliseconds);

Then, if the function has not allready being executed, you will be able to stop the execution by calling the clearTimeout() method.

Example

Same example as above, but we have added a "Stop the alert" button:
var myVar;

function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}

function myStopFunction()
{
clearTimeout(myVar);
}

Try it yourself »

More Examples


Wednesday, August 29, 2012

JavaScript Form Validation


JavaScript Form Validation

JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:
  • has the user left required fields empty?
  • has the user entered a valid e-mail address?
  • has the user entered a valid date?
  • has the user entered text in a numeric field?

Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:

function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}

The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it yourself »


E-mail Validation

The function below checks if the content has the general syntax of an email.

This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end:

function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}

The function above could be called when a form is submitted:

Example

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

Try it yourself »