Welcome to Javascript Tutorial

Java Script IntroductionIf you're new to programming/scripting, JavaScript is a good place to start. Having said that, it's still quite different to HTML so I recommend you take your time and cover off a little bit each day. Don't worry if it takes you several days to complete - it's better to fully understand everything than to brush over it and not fully comprehend it.
I suggest you bookmark this tutorial now, then continue on.
What is JavaScript?JavaScript is a scripting language that enables web developers/designers to build more functional and interactive websites.
Common uses of JavaScript include:
  • Alert messages
  • Popup windows
  • Dynamic dropdown menus
  • Form validation
  • Displaying date/time
JavaScript usually runs on the client-side (the browser's side), as opposed to server-side (on the web server). One benefit of doing this is performance. On the client side, JavaScript is loaded into the browser and can run as soon as it is called. Without running on the client side, the page would need to refresh each time you needed a script to run.
What do I need to create JavaScript?You can create JavaScript using the same equipment you use when creating HTML. That is:
  • Computer
  • Text editor. For example, Notepad (for Windows), Pico (for Linux), or Simpletext (Mac). You could use a HTML editor if you like but it's not needed.
  • Web Browser. For example, Internet Explorer or Firefox. You will need to ensure JavaScript is enabled within your browser's settings (this is normally enabled by default).
How to enable JavaScriptTo view webpages with JavaScript, you need to ensure your browser has JavaScript enabled. Generally speaking, you can still view the webpage without JavaScript, but you will not be able to take advantage of the JavaScript functionality.
How do I check if my browser has JavaScript enabled?You normally do this by checking your browser's options. This will depend on the browser you're using. Instructions for some of the more common browsers are below:
Internet Explorer (6.0):
  1. Go to Tools from the top menu
  2. Select Internet Options
  3. Click on the Security tab
  4. Click Custom Level
  5. Scroll down until you see the Scripting section
  6. Ensure that the Active Scripting option is set at Enabled
  7. Click OK
Netscape Navigator (4.8):
  1. Go to Edit from the top menu
  2. Select Preferences
  3. Select Advanced
  4. Select Scripts & Plugins
  5. Check the Enable JavaScript checkbox
  6. Click OK
Mozilla Firefox (1.0):
  1. Go to Tools from the top menu
  2. Select Options
  3. Select Web Features from the left menu
  4. Ensure the Enable JavaScript option is checked
  5. Click OK
Mozilla Firefox (1.5):
  1. Go to Tools from the top menu
  2. Select Options
  3. Click on the Content button
  4. Ensure that the Enable JavaScript option is checked
  5. Click OK
Apple Safari (1.0):
  1. Go to Safari from the top menu
  2. Select Preferences
  3. Select Security
  4. Ensure that the Enable JavaScript option is checked
  5. Click OK
How do I disable JavaScript?You simply go through the steps above but ensure the JavaScript options are not checked/selected.
If you're developing web pages with JavaScript, it's good practice to view your website with JavaScript disabled. This will show you what your website will look like to users who choose to disable JavaScript.
Other browsers?Most (if not all browsers) give you the option to enable/disable JavaScript. If your browser is not listed above, the steps above will give you some idea of how to find it. Just look for something called tools, options, preferences or something similar.
WarningJava and JavaScript are two different things - make sure you're enabling/disabling the right option!

JavaScript SyntaxWhat does JavaScript syntax mean? JavaScript syntax refers to a set of rules that determine how the language will be written (by the programmer) and interpreted (by the browser).
The JavaScript syntax is loosely based on the Java syntax. Java is a full blown programming environment and JavaScript could be seen as a sub-set of the Java syntax. Having said this, that is where the similarities end - Java and JavaScript are two totally different things.
In learning JavaScript you will become familiar with terms such as variables, functions, statements, operators, data types, objects etc.
It will take most of this tutorial to show you the complete JavaScript syntax. For now, I'll give you a quick intro by showing you an example and explanation.
Example code <script >
<!--
document.write("JavaScript is not Java");
-->
</script>

This results in:
JavaScript is not Java The above example is how you write text to a web page using JavaScript.
Explanation of code
  • The <script> tags tell the browser to expect a script in between them. You specify the language using the type attribute. The most popular scripting language on the web is JavaScript.
  • The bits that look like HTML comments tag (<-- -->) are just that - HTML comment tags. These are optional but recommended. They tell browsers that don't support JavaScript (or with JavaScript disabled) to ignore the code in between. This prevents the code from being written out to your website users.
  • The part that writes the actual text is only 1 line (document.write("JavaScript is not Java");). This is how you write text to a web page in JavaScript. This is an example of using a JavaScript function (also known as method).
Where to put your scripts?You can place your scripts in any of the following locations:
  • Between the HTML document's head tags.
  • Within the HTML document's body (i.e. between the body tags).
  • In an external file (and link to it from your HTML document).
 
JavaScript Popup BoxesYou've probably encountered JavaScript popup boxes many times while visiting websites. Now, I don't mean "popup windows" - we'll cover that later. What I mean is, a popup box that displays a message, along with an "OK" button. Depending on the popup box, it might also have a "Cancel" button, and you might also be prompted to enter some text. These are all built into JavaScript and are what I call "JavaScript popup boxes". They can also referred to as "dialog boxes", "JavaScript dialogs", "popup dialog" etc.
Types of PopupsJavaScript has three different types of popup box available for you to use. Here they are:
AlertDisplays a message to the user. Example:
ConfirmAsks the user to confirm something. Often, this is in conjunction with another (potentially significant) action that the user is attempting to perform. Example:
PromptPrompts the user for information. Example:
Popup CodeHere's the syntax for specifying popup boxes, along with some examples.
Type of PopupSyntaxExample CodeExample Display Alertalert("Message");alert("Hey, remember to tell your friends about Quackit.com!"); Confirmconfirm("Message");confirm("Are you sure you want to delete the Internet?"); Promptprompt("Message","Default response");prompt('Please enter your favorite website', 'Quackit.com'); Note that the user's browser determines what the popup box actually looks like. This is because our popup code is simply telling the browser to "display this type of popup with this message". It is up to the browser to render the correct type of popup with the specified message.
Integating JavaScript with HTMLYou will have noticed that the (above) example popups didn't appear as soon as you loaded this page. They only appeared after you clicked the relevant button. This is because I placed code into each HTML button, so that when it was clicked, it triggered off our JavaScript.
This is a very common way of using JavaScript on the web. By "attaching" JavaScript to our HTML elements, we can make our pages much more responsive to our users' actions.
The following lesson explains this in more detail.

JavaScript and HTMLIn previous lessons, we've learned about the syntax of JavaScript, but we haven't yet learned how to "attach" the JavaScript to our HTML elements. That's what I'll show you in this lesson.
Standalone JavaScriptFirst, let's look at what a standalone piece of JavaScript looks like.
<script >
<!--
alert('Hey, remember to tell your friends about Quackit.com!');
-->
</script>

If we place the above JavaScript between the 'head' tags (or 'body' tags), it will run as soon as we load the page.
Now this is fine - as long as you want it to run as soon as the page loads!
But, what if you don't want it to run as soon as the page loads? What if you only want it to run when a user clicks on a button?
Easy! This is where you need to use an "event handler".
What's an Event Handler?In JavaScript/HTML, an event handler allows you to attach your JavaScript to your HTML elements.
Event handlers allow your web page to detect when a given "event" has occurred, so that it can run some JavaScript code. An example of an "event" could be say, a click on an HTML element.
In your code, an event handler is simply a special attribute that you add to your HTML element. For example, to run some JavaScript when the user clicks on an element, you add the onClick attribute to the element.
The examples below demonstrate this for you.
Adding JavaScript to an HTML ElementHere's a basic example of adding JavaScript to an HTML element. In this case, when the user clicks on our button, a JavaScript alert box is displayed. This is done by adding an onClick attribute and placing the JavaScript alert box code into it.
When you use JavaScript like this, you don't need to use script tags (like we did above). Simply place your JavaScript within the event handler and it will work.
Code:
<input onClick="alert('Hey, remember to tell your friends about Quackit.com!');" value="Click Me!" /> Result:
JavaScript "On Double Click"You could just have easily used another event to trigger the same JavaScript. For example, you could run JavaScript only when the double clicks the HTML element. We can do this using the onDblClick event handler.
Code:
<input onDblClick="alert('Hey, remember to tell your friends about Quackit.com!');" value="Double Click Me!" /> Result:
There are plenty of other event handlers you can use within your JavaScript/HTML code. In total, there are 18 event handlers (as listed by the W3C). We'll cover these in more detail later.
Complex CodeOnce you become well versed in JavaScript, you'll be able to write some complex programs using lots of code. When this happens, you'll want to place your code into a "function". We'll cover functions later but, for now, understand that you'll be able to call your function just like we call the JavaScript alert() function in the above examples - using event handlers.
 External JavaScript FileYou can place all your scripts into an external file (with a .js extension), then link to that file from within your HTML document. This is handy if you need to use the same scripts across multiple HTML pages, or a whole website.
To link to an external JavaScript file, you add a src attribute to your HTML script tag and specify the location of the external JavaScript file.
Linking to an external JavaScript file <script src="external_javascript.js"></script>

Contents of your external JavaScript fileThe code in your .js file should be no different to the code you would normally have placed in between the script tags. But remember, you don't need to create script tag again - it is already on the HTML page calling the external file!

JavaScript OperatorsJavaScript operators are used to perform an operation. There are different types of operators for different uses.
Below is a listing of JavaScript operators and a brief description of them. Don't worry if you don't understand all of them at this stage - just bookmark this page for reference and return whenever you need to.
Artithmetic Operators OperatorDescription +Addition -Subtraction *Multiplication /Division %Modulus (remainder of a division) ++Increment --Decrement Assignment Operators OperatorDescription =Assign +=Add and assign. For example, x+=y is the same as x=x+y. -=Subtract and assign. For example, x-=y is the same as x=x-y. *=Multiply and assign. For example, x*=y is the same as x=x*y. /=Divide and assign. For example, x/=y is the same as x=x/y. %=Modulus and assign. For example, x%=y is the same as x=x%y. Comparison Operators OperatorDescription ==Is equal to ===Is identical (is equal to and is of the same type) !=Is not equal to !==Is not identical >Greater than >=Greater than or equal to <Less than <=Less than or equal to Logical/boolean Operators OperatorDescription &&and ||or !not String OperatorsIn JavaScript, a string is simply a piece of text.
OperatorDescription =Assignment +Concatenate (join two strings together) +=Concatenate and assign  JavaScript VariablesLike other programming languages, JavaScript variables are a container that contains a value - a value that can be changed as required.
For example, you could prompt your website users for their first name. When they enter their first name you could store it in a variable called say, firstName. Now that you have the user's first name assigned to a variable, you could do all sorts of things with it like display a personalised welcome message back to the user for example. By using a variable to store the user's first name, you can write one piece of code for all your users.
Declaring JavaScript variablesFirst, you need to declare your variables. You do this using the var keyword. You can declare one variable at a time or more than one. You can also assign values to the variables at the time you declare them.
Different methods of declaring JavaScript variables // declaring one javascript variable
var firstName;

// declaring multiple javascript variables
var firstName, lastName;

// declaring and assigning one javascript variable
var firstName = 'Homer';

// declaring and assigning multiple javascript variables
var firstName = 'Homer', lastName = 'Simpson';

Using JavaScript variablesAlthough there are many uses for JavaScript variables, here is a quick and dirty example:
<script language="javascript" >

<!-- hide me
var firstName = prompt("What's your first name?", "");
// end hide -->

<!-- hide me
document.write(firstName);
// end hide -->

</script>

The above example opens a JavaScript prompt, prompting the user for their first name. It will then write the name to the page (in practice, you would output the name somewhere between the <body></body> tags).
I suspect you can find a much better use for your javascript variables but this simply to demonstrate how easily you can store data inside a variable - data that could change at any moment.
Rules for JavaScript Variables
  • Can contain any letter of the alphabet, digits 0-9, and the underscore character.
  • No spaces
  • No punctuation characters (eg comma, full stop, etc)
  • The first character of a variable name cannot be a digit.
  • JavaScript variables' names are case-sensitive. For example firstName and FirstName are two different variables. 
JavaScript FunctionsIn JavaScript, you will use functions a lot. A function (also known as a method) is a self-contained piece of code that performs a particular "function". You can recognise a function by its format - it's a piece of descriptive text, followed by open and close brackets.
Sometimes there will be text in between the brackets. This text is known as an argument. An argument is passed to the function to provide it with further info that it needs to process. This info could be different depending on the context in which the function is being called.
Arguments can be extremely handy, such as allowing your users to provide information (say via a form) that is passed to a function to process. For example, your users could enter their name into a form, and the function would take that name, do some processing, then present them with a personalised message that includes their name.
A function doesn't actually do anything until it is called. Once it is called, it takes any arguments, then performs it's function (whatever that may be).
Writing a function in JavaScriptIt's not that hard to write a function in JavaScript. Here's an example of a JavaScript function.
Write the function:
<script >
<!--
function displayMessage(firstName) {
alert("Hello " + firstName + ", hope you like JavaScript functions!")
}
//-->
</script>

Call the function:
<form>
First name:
<input name="yourName" />
<input

onclick="displayMessage(form.yourName.value)"
value="Display Message" />
</form>

This should work like this:
First name: Exlanation of codeWriting the function:
  1. We started by using the function keyword. This tells the browser that a function is about to be defined
  2. Then we gave the function a name, so we made up our own name called "displayMessage". We specified the name of an argument ("firstName") that will be passed in to this function.
  3. After the function name came a curly bracket {. This opens the function. There is also a closing bracket later, to close the function.
  4. In between the curly brackets we write all our code for the function. In this case, we use JavaScript's built in alert() function to pop up a message for the user.
Calling the function:
  1. We created an HTML form with an input field and submit button
  2. We assigned a name ("yourName") to the input field
  3. We added the onclick event handler to the button. This event handler is called when the user clicks on the button (more about event handlers later). This is where we call our JavaScript function from. We pass it the value from the form's input field. We can reference this value by using "form.yourName.value".
JavaScript EventsIn the previous lesson, we used an event handler to trigger off a call to our function. There are 18 event handlers that you can use to link your HTML elements to a piece of JavaScript.
When you write a JavaScript function, you will need to determine when it will run. Often, this will be when a user does something like click or hover over something, submit a form, double clicks on something etc.
These are examples of events.
Using JavaScript, you can respond to an event using event handlers. You can attach an event handler to the HTML element for which you want to respond to when a specific event occurs.
For example, you could attach JavaScript's onMouseover event handler to a button and specify some JavaScript to run whenever this event occurs against that button.
The HTML 4 specification refers to these as intrinsic events and defines 18 as listed below:
Event Handler Event that it handles onBlur User has left the focus of the object. For example, they clicked away from a text field that was previously selected. onChange User has changed the object, then attempts to leave that field (i.e. clicks elsewhere). onClick User clicked on the object. onDblClick User clicked twice on the object. onFocus User brought the focus to the object (i.e. clicked on it/tabbed to it) onKeydown A key was pressed over an element. onKeyup A key was released over an element. onKeypress A key was pressed over an element then released. onLoad The object has loaded. onMousedown The cursor moved over the object and mouse/pointing device was pressed down. onMouseup The mouse/pointing device was released after being pressed down. onMouseover The cursor moved over the object (i.e. user hovers the mouse over the object). onMousemove The cursor moved while hovering over an object. onMouseout The cursor moved off the object onReset User has reset a form. onSelect User selected some or all of the contents of the object. For example, the user selected some text within a text field. onSubmit User submitted a form. onUnload User left the window (i.e. user closes the browser window). The events in the above table provide you with many opportunities to trigger some JavaScript from within your HTML code.
I encourage you to bookmark this page as a reference - later on you may need a reminder of which events you can use when solving a particular coding issue.

JavaScript If StatementsWhen you write code, you will often need to use conditional statements.
A conditional statement refers to a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like.
JavaScript If statements are an example of conditional statements. With If statements, you can tell the browser to execute a piece of code only if a given condition is true.
Example If statement: <script >
<!--
var myColor = "Blue";

if (myColor == "Blue") {
document.write("Just like the sky!");
}

//-->
</script>

The resulting output:
Just like the sky! Exlanation of codeWe first declare a variable called "myColor" and set the value to "Blue". We then use a JavaScript if statement to test if the value of the variable is "Blue". If it is, we output some text to the user.
To create a JavaScript If statement
  1. Start with the word "if"
  2. Between open and closed brackets, write the actual condition that is being tested (i.e. if something is equal to something else).
  3. Between open and closed curly brackets (or braces), specify what will happen if the condition is satisfied.
JavaScript If Else statementThe above code is OK if you only want to display something when the condition is true. But what if you want to display something when the condition isn't true. For example, what if the variable "myColor" was equal to, say, "red"?
This is where an If Else statement comes in handy. The "Else" part is what we're interested in here. The "Else" is what tells the browser what to do if the condition is not true.
Example If Else statement: <script >
<!--
var myColor = "Red";

if (myColor == "Blue") {
document.write("Just like the sky!");
}
else {
document.write("Didn't pick blue huh?");
}

//-->
</script>

The resulting output:
Didn't pick blue huh? Exlanation of codeThe first part of this code is the same as the previous example. The second part is where we specify what to do if the condition is not true. . Therefore, you write "else" followed by what you want to occur, surrounded by curly braces.
  1. Write an if statement (as per first example)
  2. Follow this with the word "else"
  3. Between open and closed curly brackets (or braces), specify what to do next.
JavaScript If Else If statementThe If Else If statement is more powerful than the previous two. This is because you can specify many different outputs based on many different conditions - all within the one statement. You can also end with an "else" to specify what to do if none of the conditions are true.
Example If Else If statement: <script >
<!--
var myColor = "Red";

if (myColor == "Blue") {
document.write("Just like the sky!");
}
else if (myColor = "Red") {
document.write("Just like shiraz!");
}

else {
document.write("Suit yourself then...");
}
//-->
</script>

The resulting output:
Just like shiraz! Exlanation of codeWe started with an "if" and ended with an "else", however, in the middle, we used an "else if" statement to specify what to do if the "myColor" variable was equal to Red. This statement looks exactly like the "if" statement - just with an "else" prepended to it.
By the way, we could have specified as many "else if" conditions as we liked.

JavaScript Switch StatementIn the previous lesson about JavaScript If statements, we learned that we can use an If Else If statement to test for multiple conditions, then output a different result for each condition.
For example, if the variable "myColor" was equal to "Blue", we could output one message. If it is "Red" we could output another etc
Another way of doing this is to use the JavaScript Switch statement. An advantage of using the switch statement is that it uses less code, which is better if you have a lot of conditions that you need to check for.
Example Switch statement:Here, we will re-write the last example in the previous lesson into a switch statement.
<script >
<!--
var myColor = "Red";

switch (myColor)
{
case "Blue":
document.write("Just like the sky!");
break
case "Red":
document.write("Just like shiraz!");
break
default:
document.write("Suit yourself then...");
}
//-->
</script>

The resulting output:
Just like shiraz! Exlanation of codeWe started by declaring a variable called "myColor" and setting it to "Red". We then opened a switch statement, passing in the variable we want to test (myColor). This is followed by a set of "cases" within curly braces. We add a "default" condition, which is only executed if none of the above cases are true. It's important to use "break" after each case - this prevents the code from running into the next case.
  1. We started by declaring a variable called "myColor" and setting it to "Red"
  2. We then opened a switch statement, passing in the variable we want to test (myColor)
  3. This is followed by a set of "cases" within curly braces. It's important to use "break" after each case - this prevents the code from running into the next case.
  4. Prior to the closing bracket, we add a "default" condition, which is only executed if none of the above cases are true
 JavaScript While LoopIn JavaScript and most other languages, "loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.
The JavaScript While loop executes code while a condition is true.
For example, you could make your program display a the value of a counter while the count is less than or equal to say, 10.
Example While statement: <script >
<!--
var myBankBalance = 0;

while (myBankBalance <= 10) {
document.write("My bank balance is $" + myBankBalance + "
");
myBankBalance ++;
}

//-->
</script>

The resulting output:
Right now, my bank balance is $0
Right now, my bank balance is $1
Right now, my bank balance is $2
Right now, my bank balance is $3
Right now, my bank balance is $4
Right now, my bank balance is $5
Right now, my bank balance is $6
Right now, my bank balance is $7
Right now, my bank balance is $8
Right now, my bank balance is $9
Right now, my bank balance is $10
Exlanation of code
  1. We started by declaring a variable called "myBankBalance" and setting it to 0
  2. We then opened a while loop, inserting our condition between brackets. Our condition checks if the current value of the myBankBalance variable is less than or equal to 10.
  3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of myBankBalance, preceded by some text. This code is placed within curly braces.
  4. We then increment the value by 1.
  5. When the browser reaches the closing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. Of course, by now, the myBankBalance variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 10), it exits from the loop.
 JavaScript For LoopWe learned in the previous lesson that "loops" enable your program to continuously execute a block of code for a given number of times, or while a given condition is true.
In that lesson, we saw that the While loop executes code while a condition is true.
In this lesson, we will see that the JavaScript For loop executes code for a specified number of times.
Therefore, we could rewrite the example from the previous lesson to use a for loop.
Example For statement: <script >
<!--
var myBankBalance = 0;

for (myBankBalance = 0; myBankBalance <= 10; myBankBalance++)
{
document.write("My bank balance is $" + myBankBalance + "
");
}

//-->
</script>

The resulting output:
My bank balance is $0
My bank balance is $1
My bank balance is $2
My bank balance is $3
My bank balance is $4
My bank balance is $5
My bank balance is $6
My bank balance is $7
My bank balance is $8
My bank balance is $9
My bank balance is $10
Exlanation of code
  1. We started by declaring a variable called "myBankBalance" and setting it to 0
  2. We then opened a for loop with our condition between brackets. Our condition sets a value to our variable, checks if the current value of the variable is less than or equal to 10, then increments the value by 1.
  3. This is followed by code to execute while the condition is true. In this case, we are simply, outputting the current value of myBankBalance, preceded by some text. This code is placed within curly braces.
  4. When the browser reaches the closing curly brace, if the condition is still true, it goes back to the first curly brace and executes the code again. Of course, by now, the myBankBalance variable has been incremented by 1. If the condition is not true (i.e. the variable is greater than 10), it exits from the loop.
 JavaScript Try... CatchThe more JavaScript you code the more errors you'll encounter. This is a fact of life in any programming environment. Nobody's perfect and, once your scripts become more complex, you'll find there are sometimes scenarios that result in an error that you didn't think of.
JavaScript errors on web pages can scare your visitors away. How many times have you encountered a web page with errors, only to click the "back" button?
OK, so you can't always prevent errors from occuring, but you can do something about them. The JavaScript "Try... Catch" statement helps you handle errors in a "nice" way.
To use the Try... Catch statement, you take any code you think could potentially result in an error, and wrap it within the "try" statement. You then code what you want to happen in the event of an error and wrap that in a "catch" statement.
Code without a Try... Catch statement: <script >
<!--
document.write("My bank balance is $" + myBankBalance);
//-->
</script>

The above code will result in an error. This is because the variable "myBankBalance" hasn't been declared yet.
Code with a Try... Catch statement: <script >
<!--
try
{
document.write("My bank balance is $" + myBankBalance);
}
catch(err)
{
document.write("Sorry, an error has occurred");
document.write("...but hey, don't let that stop you!");
}
//-->
</script>

The resulting output:
Sorry, an error has occurred...but hey, don't let that stop you! The above code will hide the error and present something more user friendly to the user. This is because the code with the error was wrapped inside a "try" statement. And, because there was an error, the browser outputs whatever is between the "catch" statement.
 JavaScript Escape CharactersWhen working with strings, you'll notice there are some characters that always seem to break your program. These include apostrophes, ampersands, double quotes etc.
When working with these characters, you need to use what is known as an "escape character". An escape character enables you to output characters you wouldn't normally be able to, usually because the browser will interpret it differently to what you intended.
In JavaScript, the backslash (\) is an escape character.
As an example, let's say I want to display the following text: They call it an "escape" character. Let's try that without an escape character:
Without an escape character: <script >
<!--
document.write("They call it an "escape" character");
//-->
</script>

The above code won't work as intended because, as soon as the browser encounters the first double quote, it will think that the string has finished. Further, it will result in an error because it will be expecting the closing bracket.
Code with an escape character: <script >
<!--
document.write("They call it an \"escape\" character");
//-->
</script>

The resulting output:
They call it an "escape" character The above code will display the double quotes as intended.
 JavaScript Void(0)Sometimes, you may need to call some JavaSript from within a link. Normally, when you click a link, the browser loads a new page (or refreshes the same page).
This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.
To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero).
Example of void(0):We have a link that should only do something (i.e. display a message) upon two clicks (i.e. a double click). If you click once, nothing should happen. We can specify the double click code by using JavaScript's "ondblclick" method. To prevent the page reloading upon a single click, we can use "JavaScript:void(0);" within the anchor link.
Code:
<a href="JavaScript:void(0);" ondblclick="alert('Well done!')">Double Click Me!</a> Result:
Double Click Me! Same Example, but without void(0):Look at what would happen if we didn't use "JavaScript:void(0);" within the anchor link...
Code:
<a href="" ondblclick="alert('Well done!')">Double Click Me!</a> Result:
Double Click Me! Did you notice the page refresh as soon you clicked the link. Even if you double clicked and triggered the "ondbclick" event, the page still reloads!
Note: Depending on your browser, your browser might have redirected you to the "/javascript/tutorial/" index page. Either way, JavaScript's "void()" method will prevent this from happening.
Void(0) can become useful when you need to call another function that may have otherwise resulted in an unwanted page refresh.

JavaScript CookiesCookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use cookies to store information that they need (or prefer). Websites often use cookies to personalise the user experience - such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits.
Despite the many misconceptions about cookies being malicious, they are quite harmless. Cookies can't give your personal details to other websites, or transmit a virus or anything like that. A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not harder.
Creating Cookies in JavaScript document.cookie =
"myContents=Quackit JavaScript cookie experiment;
expires=Fri, 19 Oct 2007 12:00:00 UTC; path=/";

Now check your cookies folder to see if the cookie was created. Alternatively, write code to read the cookie.
Note: If the cookie wasn't created, check the expiry date - it needs to be a date in the future.
You can update this value by using the same code with a different value. If you want to add a second value, simply use a different variable name (for example "myContents2=").
Reading Cookies in JavaScript document.write(document.cookie);

You simply reference the cookie using document.cookie. The only problem with the above code is that it outputs the equals sign and everything before it (i.e. "myContents="). To stop this from happening, try the following code:
document.write(document.cookie.split("=")[1])

Deleting Cookies in JavaScriptTo delete a cookie, you can use the same code you used to create it but this time, set the expiry date in the past:
document.cookie =
"myContents=Quackit JavaScript cookie experiment;
expires=Fri, 14 Oct 2005 12:00:00 UTC; path=/";

Once you are comfortable with JavaScript and cookies, you can do things like use the getDate() function to set the date at a date in the future (say, 6 months), creating a function for setting and naming your cookies etc.
 JavaScript Date and TimeJavaScript provides you with the ability to access the date and time of your users' local computer, which can be quite useful at times. Displaying the current date and time in a nice user friendly way using JavaScript is not quite as simple as you might like. You need to massage the data a little. You can do this using a bunch of JavaScript date and time functions.
Displaying the Current DateTyping this code...
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth()
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")

Results in this...
28/11/2010 Displaying the Current TimeTyping this code...
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

if (minutes < 10)
minutes = "0" + minutes

document.write("<b>" + hours + ":" + minutes + " " + "</b>")

Results in this...
14:45 You may have noticed that we had to add a leading zero to the minutes part of the date if it was less than 10. By default, JavaScript doesn't display the leading zero. Also, you might have noticed that the time is being displayed in 24 hour time format. This is how JavaScript displays the time. If you need to display it in AM/PM format, you need to convert it.
Displaying the Current Time in AM/PM FormatTyping this code...
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}

if (minutes < 10)
minutes = "0" + minutes

document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")

Results in this...
2:45 PM  JavaScript ArraysWhat is an array?Arrays are a fundamental part of most programming languages and scripting languages. Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.
For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
faqQuestion1 = "What is an array?"
faqQuestion2 = "How to create arrays in JavaScript?"
faqQuestion3 = "What are two dimensional arrays?"

This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.
Visualizing ArraysArrays can be visualized as a stack of elements.
Array 0What are JavaScript arrays? 1How to create arrays in JavaScript? 2What are two dimensional arrays? Note: Some languages start arrays at zero, other start at one. JavaScript arrays start at zero.
Creating Arrays in JavaScriptMost languages use similar syntax to create arrays. JavaScript arrays are created by first assigning an array object to a variable name...
var array_name = new Array(number_of_elements)

then by assigning values to the array... array_name[0] = "Array element"

So, using our prior example, we could write:
var faq = new Array(3)
faq[0] = "What are JavaScript arrays"
faq[1] = "How to create arrays in JavaScript?"
faq[2] = "What are two dimensional arrays?"

Accessing Arrays in JavaScriptYou can access an array element by referring to the name of the array and the element's index number.
Displaying Array Elements document.write(faq[1])

The above code displays the second element of the array named faq (JavaScript array index numbers begin at zero). In this case, the value would be How to create arrays in JavaScript?
Modifying the Contents of an ArrayYou can modify the contents of an array by specifying a value for a given index number:
faq[1] = "How to modify an array?"

In this case, the value of the second element of this array would now be How to modify an array?
Two Dimensional ArraysSo far we've only discussed one dimensional arrays. You can also create two dimensional arrays, which can be much more powerful than one dimensional arrays. Two dimensional arrays are covered in the next lesson.
 Two Dimensional ArraysVisualizing Two Dimensional ArraysWhereas, one dimensional arrays can be visualized as a stack of elements, two dimensional arrays can be visualized as a multicolumn table or grid.
For example, we could create a two dimensional array that holds three columns of data; a question, an answer, and a topic.
Two Dimensional Array 0 Arrays What is an array? An ordered stack of data 1 Arrays How to create arrays? Assign variable name to array object, then assign values to the array. 2 Arrays What are two dimensional arrays? An ordered grid of data Creating Two Dimensional ArraysGenerally, creating two dimensional arrays is very similar to creating one dimensional arrays. Some languages allow you to create two dimensional arrays simply by adding an index item, however JavaScript doesn't support two dimensional arrays.
JavaScript, does however, allow you to simulate a two dimensional array. You can do this by creating an "array of an array".
To do this, you create an array, loop through the array, and for each element, you create another array. Then, you simply add an index for each column of your grid. In JavaSript this would look something like this:
var faq = new Array(3)

for (i=0; i <3; i++)
faq[i]=new Array(3)

faq[0][1] = "Arrays"
faq[0][2] = "What is an array?"
faq[0][3] = "An ordered stack of data"

faq[1][1] = "Arrays"
faq[1][2] = "How to create arrays?"
faq[1][3] = "Assign variable name to array object,
then assign values to the array."

faq[2][1] = "Arrays"
faq[2][2] = "What are two dimensional arrays?"
faq[2][3] = "An ordered grid of data"

 
InnerHTML In JavaScriptThe innerHTML property can be used to modify your document's HTML on the fly.
When you use innerHTML, you can change the page's content without refreshing the page. This can make your website feel quicker and more responsive to user input.
The innerHTML property is used along with getElementById within your JavaScript code to refer to an HTML element and change its contents.
The innerHTML property is not actually part of the official DOM specification. Despite this, it is supported in all major browsers, and has had widespread use across the web for many years. DOM, which stands for Document Object Model, is the hierarchy that you can use to access and manipulate HTML objects from within your JavaScript.
The innerHTML SyntaxThe syntax for using innerHTML goes like this:
document.getElementById('{ID of element}').innerHTML = '{content}'; In this syntax example, {ID of element} is the ID of an HTML element and {content} is the new content to go into the element.
Basic innerHTML ExampleHere's a basic example to demonstrate how innerHTML works.
This code includes two functions and two buttons. Each function displays a different message and each button triggers a different function.
In the functions, the getElementById refers to the HTML element by using its ID. We give the HTML element an ID of "myText" using id="myText".
So in the first function for example, you can see that document.getElementById('myText').innerHTML = 'Thanks!'; is setting the innerHTML of the "myText" element to "Thanks!".
Code:
<script >
function Msg1(){
document.getElementById('myText').innerHTML = 'Thanks!';
}
function Msg2(){
document.getElementById('myText').innerHTML = 'Try message 1 again...';
}
</script>
<input onclick="Msg1()" value="Show Message 1" />
<input onclick="Msg2()" value="Show Message 2" />
<p id="myText"></p>

Result:
Example 2: innerHTML With User InputHere's an example of using innerHTML with a text field. Here, we display whatever the user has entered into the input field.
Code:
<script >
function showMsg(){
var userInput = document.getElementById('userInput').value;
document.getElementById('userMsg').innerHTML = userInput;
}
</script>
<input maxlength="40" id="userInput"
onkeyup="showMsg()" value="Enter text here..." />
<p id="userMsg"></p>

Result:
Example 3: Formatting with getElementByIdIn this example, we use the getElementById property to detect the color that the user has selected. We can then use style.color to apply the new color. In both cases, we refer to the HTML elements by their ID (using getElementById.)
Code:
<script >
function changeColor(){
var newColor = document.getElementById('colorPicker').value;
document.getElementById('colorMsg').style.color = newColor;
}
</script>
<p id="colorMsg">Choose a color...</p>
<select id="colorPicker" onchange="JavaScript:changeColor()">
<option value="#000000">Black</option>
<option value="#000099">Blue</option>
<option value="#990000">Red</option>
<option value="#009900">Green</option>
</select>

Result:
Choose a color... Black Blue Red Green  JavaScript Reserved WordsYou should avoid using these reserved words and keywords as function or variable names as JavaScript has reserved these words for its own use.
JavaScript Reserved Words break continue do for import new this void case default else function in return typeof while comment delete export if label switch var with
Java Keywords (Reserved by JavaScript) abstract implements protected boolean instanceOf public byte int short char interface static double long synchronized false native throws final null transient float package true goto private  
ECMAScipt Reserved Words catch enum throw class extends try const finally   debugger super  
Other JavaScript Keywords alert eval Link outerHeight scrollTo Anchor FileUpload location outerWidth Select Area find Location Packages self arguments focus locationbar pageXoffset setInterval Array Form Math pageYoffset setTimeout assign Frame menubar parent status blur frames MimeType parseFloat statusbar Boolean Function moveBy parseInt stop Button getClass moveTo Password String callee Hidden name personalbar Submit caller history NaN Plugin sun captureEvents History navigate print taint Checkbox home navigator prompt Text clearInterval Image Navigator prototype Textarea clearTimeout Infinity netscape Radio toolbar close innerHeight Number ref top closed innerWidth Object RegExp toString confirm isFinite onBlur releaseEvents unescape constructor isNan onError Reset untaint Date java onFocus resizeBy unwatch defaultStatus JavaArray onLoad resizeTo valueOf document JavaClass onUnload routeEvent watch Document JavaObject open scroll window Element JavaPackage opener scrollbars Window escape length Option scrollBy    JavaScript Event HandlersWhen your users visit your website, they do things like click on things, hover over things etc. These are examples of what JavaScript calls events. Using JavaScript, you can respond to an event using Event Handlers. You can attach an event handler to the HTML element for which you want to respond to when a specific event occurs. For example, you could attach JavaScript's onMouseover event handler to a button and specify some JavaScript to run whenever this event occurs against that button.
The HTML 4 specification defines 18 event handlers as listed below:
Event Handler Event that it handles onBlur User has left the focus of the object. For example, they clicked away from a text field that was previously selected. onChange User has changed the object, then attempts to leave that field (i.e. clicks elsewhere). onClick User clicked on the object. onDblClick User clicked twice on the object. onFocus User brought the focus to the object (i.e. clicked on it/tabbed to it) onKeydown A key was pressed over an element. onKeyup A key was released over an element. onKeypress A key was pressed over an element then released. onLoad The object has loaded. onMousedown The cursor moved over the object and mouse/pointing device was pressed down. onMouseup The mouse/pointing device was released after being pressed down. onMouseover The cursor moved over the object (i.e. user hovers the mouse over the object). onMousemove The cursor moved while hovering over an object. onMouseout The cursor moved off the object onReset User has reset a form. onSelect User selected some or all of the contents of the object. For example, the user selected some text within a text field. onSubmit User submitted a form. onUnload User left the window (i.e. user closes the browser window).  JavaScript Date and Time FunctionsJavaScript provides the following date and time functions. Note that UTC stands for Universal Coordinated Time which refers to the time as set by the World Time Standard. Previously referred to as Greenwich Mean Time or GMT.
Function Description Returned Values getDate()
getUTCDate() Day of the month 1-31 getDay()
getUTCDay() Day of the week (integer) 0-6 getFullYear()
getUTCFullYear() Year (full four digit) 1900+ getHours()
getUTCHours() Hour of the day (integer) 0-23 getMilliseconds()
getUTCMilliseconds() Milliseconds (since last second) 0-999 getMinutes()
getUTCMinutes() Minutes (since last hour) 0-59 getMonth()
getUTCMonth() Month 0-11 getSeconds()
getUTCSeconds() Seconds (since last minute) 0-59 getTime() Number of milliseconds since 1 January 1970   getTimezoneOffset() Difference between local time and GMT in minutes 0-1439 getYear() Year 0-99 for years between 1900-1999
Four digit for 2000+ parse() Returns the number of milliseconds since midnight 1 January 1970 for a given date and time string passed to it.   setDate()
setUTCDate() Sets the day, given a number between 1-31 Date in milliseconds setFullYear()
setUTCFullYear() Sets the year, given a four digit number Date in milliseconds setHours()
setUTCHours() Sets the hour, given a number between 0-23 Date in milliseconds setMilliseconds()
setUTCMilliseconds() Sets the milliseconds, given a number Date in milliseconds setMinutes()
setUTCMinutes() Sets the minutes, given a number between 0-59 Date in milliseconds setMonth()
setUTCMonth() Sets the month, given a number between 0-11 Date in milliseconds setSeconds()
setUTCSeconds() Sets the seconds,l given a number between 0-59 Date in milliseconds setTime() Sets the date, given the number of milliseconds since 1 January 1970 Date in milliseconds setYear() Sets the year, given either a two digit or four digit number Date in milliseconds toGMTString()
toUTCString() GMT date and time as a string day dd mmm yyyy hh:mm:ss GMT toLocaleString() Local date and time as a string Depends on operating system, locale, and browser toString() Local date and time as a string Depends on operating system, locale, and browser UTC() Returns the number of milliseconds since 1 January 1970 for a given date in year, month, day (and optionally, hours, minutes, seconds, and milliseconds) Date in milliseconds valueOf() Number of milliseconds since 1 January 1970 Date in milliseconds  JavaScript Examples Related:
• HTML Examples
This page contains JavaScript examples - examples of JavaScript tricks that you can use for your own website.
You can use any of these examples simply by copying and pasting the code straight into your website.
We've got plenty of HTML examples too!
DescriptionCodeResult Popup Window <!-- JavaScript examples by Quackit.com --> <script > // Popup window code function newPopup(url) { popupWindow = window.open( url,'popUpWindow','height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes') } </script> <a href="JavaScript:newPopup('http://www.quackit.com/html/codes/');">Get your HTML codes here!</a> Get your HTML codes in a popup! Jump Menu <!-- JavaScript examples by Quackit.com --> <script language="javascript" > <!-- hide function jumpto(x){ if (document.form1.jumpmenu.value != "null") { document.location.href = x } } // end hide --> </script> <form name="form1"> <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option>Jump to...</option> <option value=http://www.quackit.com>Quackit Homepage</option> <option value=http://www.quackit.com/javascript/>JavaScript</option> <option value=http://www.quackit.com/html/>HTML</option> <option value=http://www.quackit.com/css/>CSS</option> <option value=http://www.quackit.com/sql/tutorial/>SQL</option> <option value=http://www.quackit.com/database/tutorial/>Database Tutorial</option> <option value=http://www.quackit.com/web_hosting/>Web Hosting Tutorial</option> </select> </form> <p >Codes by <a href="http://www.quackit.com">Quackit</a> Jump to... Quackit Homepage JavaScript HTML CSS SQL Database Tutorial Web Hosting Tutorial Automatically launch the "print" dialog <!-- JavaScript examples by Quackit.com --> <a href="JavaScript:window.print();">Print this page</a> Print this page "Print" dialog with printer icon <!-- JavaScript examples by Quackit.com --> <a href="JavaScript:window.print();"><img src="/pix/printer_icon.gif" border="0" width="17" height="17" align="middle" alt="Print Version" /></a> Alert Box <!-- JavaScript examples by Quackit.com --> <input onclick="alert('Wow... you sure do know how to click!');" value="Click me..." /> Confirm Box <!-- JavaScript examples by Quackit.com --> <script > function confirmHappy() { var happiness=confirm("Are you sure you're happy?"); if (happiness==true) { alert("Wow! You seem really happy!"); } else { alert("You should get out more!"); } } </script> <input onclick="confirmHappy()" value="If you're happy and you know it, click me..." /> Prompt <!-- JavaScript examples by Quackit.com --> <script > function displayPrompt() { var name=prompt("What's your name?","Homer"); if (name!=null && name!="") { alert("Well " + name + ". You seem very daring!"); } else { alert("Hey, I asked you your name!"); } } </script> <input onclick="displayPrompt()" value="I dare you to click me!" /> Status Bar Messages <!-- JavaScript examples by Quackit.com --> <a href="http://www.quackit.com/html/codes/" onMouseover="JavaScript:window.status='Get your HTML codes here!'; return true;"onMouseout="JavaScript:window.status=''; return true">Hover over me!</a> Hover over me! (Doesn't work? Learn more here).
Image Rollover <!-- JavaScript examples by Quackit.com --> <script > <!-- // Pre load images for rollover if (document.images) { smile = new Image nosmile = new Image smile.src = "http://www.quackit.com/pix/smile.gif" nosmile.src = "http://www.quackit.com/pix/nosmile.gif" } function swapImage(thisImage,newImage) { if (document.images) { document[thisImage].src = eval(newImage + ".src") } } --> </script> <a href="http://www.quackit.com/javascript/image_rollovers.cfm" onMouseOver="swapImage('jack','smile')" onMouseOut="swapImage('jack','nosmile')"> <img src="http://www.quackit.com/pix/nosmile.gif" width="100" height="100" border="0" alt="Picture of Jack" name="jack"> </a> Timed Redirect <!-- JavaScript examples by Quackit.com --> <script > <!-- function timedRedirect(redirectTo, timeoutPeriod) { setTimeout("location.href = redirectTo;",timeoutPeriod); } // --> </script> <a href="JavaScript:void(0);" onclick="JavaScript:timedRedirect(redirectTo='http://www.quackit.com/html/examples/', timeoutPeriod='2000')">Redirect in 2 seconds...</a> Redirect in 2 seconds... Timed Refresh <!-- JavaScript examples by Quackit.com --> <script > <!-- function timedRefresh(timeoutPeriod) { setTimeout("location.reload(true);",timeoutPeriod); } // --> </script> <p><a href="javascript:timedRefresh(3000)">Refresh this page in 3 seconds...</a></p> Refresh this page in 3 seconds... JavaScript Dropdown MenuDropdown menus like this are sometimes referred to as a "Jump menu". This is because it "jumps" to the selected URL as soon as you make the selection. (Other drop down menus require you to click on a "go" button after you've made your selection - which is the safe way to go if you're worried about users who don't have JavaScript enabled).
  To create a "Jump menu" like this: Jump to... Quackit Homepage JavaScript HTML CSS SQL Database Tutorial Web Hosting Tutorial  do the following:
  1. Copy and paste the following code in between the <head> and </head> tags
    <script language="javascript" > <!-- hide function jumpto(x){ if (document.form1.jumpmenu.value != "null") { document.location.href = x } } // end hide --> </script>


  2. Insert the following code exactly where you want your menu to occur in between the <body> and </body> tags:
    <form name="form1"> <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option>Jump to...</option> <option value=http://www.quackit.com>Quackit Homepage</option> <option value=http://www.quackit.com/javascript/>JavaScript</option> <option value=http://www.quackit.com/html/>HTML</option> <option value=http://www.quackit.com/css/>CSS</option> <option value=http://www.quackit.com/sql/tutorial/>SQL</option> <option value=http://www.quackit.com/database/tutorial/>Database Tutorial</option> <option value=http://www.quackit.com/web_hosting/>Web Hosting Tutorial</option> </select> </form>
  3. Change the URL references to your own (or you can keep them pointing at Quackit if you so wish!)
 JavaScript PrintYou can use JavaScript to automatically open print dialogue box so that users can print the page. Although most users know they can do something like "File > Print", a "Print this page" option can be nice, and may even encourage users to print the page. Also, this code can be triggered automatically upon loading a printer friendly version.
Creating a "Print this page"The following code creates a hyperlink and uses the Javascript print function to print the current page:
<a href="JavaScript:window.print();">Print this page</a> The above code results in the following:
Print this page To automatically open the print dialogue box:You can call the JavaScript print function upon loading a Printer friendly version. This will automatically open the print dialogue box for the user.

  1. Copy and paste the following code in between the <head> tags of the printer friendly version:
    <script language="Javascript1.2">
    <!--
    function printpage() {
    window.print();
    }
    //-->

    </script>

  2. Add the following to your <body> tag: onload="printpage()"
So, your body tag should look something like this:
<body onload="printpage()">Creating a "Print Version"You can use Cascading Style Sheets to create a different print version of your web page. By this, I mean, you can apply different styles to each HTML element - you can apply one style to the screen version and another style to the print version. A common example is using a different font for the printed version or hiding "screen-only" elements.
 JavaScript Alert BoxThe JavaScript alert box is useful for alerting your users to something important. When a JavaScript alert box is triggered, a small box will pop up and display the text that you specify in your JavaScript code.
Creating/Triggering a JavaScript AlertYou create a JavaScript alert box by calling the built-in JavaScript alert() function. All you need to do is pass your message to this function.
JavaScript Alert - "On Click"You can place the JavaScript alert() function directly into a button element, then use the 'onclick' event to trigger it. Like this:
<!-- JavaScript and HTML codes by Quackit.com --> <input value="Click me..." onclick="alert('Thanks... I feel much better now!');" /> JavaScript Alert - Before Page LoadsThe above example uses the JavaScript 'onclick' event to trigger the alert box. This example, on the other hand, loads automatically as the page is loading. By placing the code by itself (i.e. not within a link/button), this will automatically trigger the alert box as soon as the page is loading.
The alert will popup as the browser renders the code. Therefore, if you place the code within the head tags, your alert box will popup before the HTML elements are displayed. On the other hand, if you call your alert() function within the body tags, users will be able to see any HTML elements that have been rendered prior to the alert box code:
<!-- JavaScript and HTML codes by Quackit.com --> <html> <head> <body> <div > <h1>Amazing Web Page</h1> <script > alert('But wait, there\'s more...'); </script> <p><a href="JavaScript:self.close();">Close This Silly Page!</a></p> </div> </body> </html> View Example JavaScript Alert - After Page LoadsIf you prefer to have the full page visible while the user reads the alert box message, use the 'onload' event.
To do this, place a function in the document's head, then trigger it using the 'onload' attribute in the document's body tag.
<!-- JavaScript and HTML codes by Quackit.com --> <html> <head> <script > function alertUser(msg) { alert(msg); } </script> </head> <body onload="alertUser('Welcome to this AMAZING web page!')"> <div > <h1>Amazing Web Page.</h1> <p><a href="JavaScript:self.close();">Close</a></p> </div> </body> </html> View Example JavaScript Alert - Within Another FunctionThe most common use for the JavaScript alert is to call it from within a function that does something else. The alert simply draws the user's attention to something that the function has done (or detected).
Code
<!-- JavaScript and HTML codes by Quackit.com --> <script language="javascript" > function jumpto(x){ if (document.form1.jumpmenu.value != "null") { if (document.form1.jumpmenu.value != "http://www.quackit.com") { alert('Sorry to see you leaving Quackit. Hope to see you back soon!'); } document.location.href = x } } </script> <form name="form1"> <select name="jumpmenu" onChange="jumpto(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)"> <option>Jump to...</option> <option value="http://www.quackit.com">Quackit Homepage</option> <option value="http://www.zappyhost.com">ZappyHost</option> <option value="http://www.code-generator.net">Code Generator</option> <option value="http://www.natural-environment.com">Natural Environment</option> <option value="http://www.great-workout.com">Great Workout</option> </select> </form> Result:
Jump to... Quackit Homepage ZappyHost Code Generator Natural Environment Great Workout In the above example, if you choose anything but "Quackit Homepage", you'll see a JavaScript alert.
  JavaScript ConfirmThe JavaScript confirm box gives your users a chance to confirm an action before JavaScript runs it. The 'confirm' box is created using JavaScript's built-in confirm() function. When the JavaScript confirm() function is triggered, a small box will pop up and display an "OK" button and a "Cancel" button (along with text that you specify in your JavaScript code).
Creating/Triggering a JavaScript ConfirmAs mentioned, you create a JavaScript confirm box by calling the built-in JavaScript confirm() function. All you need to do is pass your message to this function.
Basic JavaScript ConfirmYou can place the JavaScript confirm() function straight into an HTML tag. Like this:
<!-- JavaScript and HTML codes by Quackit.com --> <input onclick="confirm('Did you really mean to click the button?');" value="Click me..." /> JavaScript 'confirm()' Within Another FunctionThe above example works, but it doesn't really do much. You could make your website more useful by including the confirm() function within another function.
Here's an example:
<!-- JavaScript and HTML codes by Quackit.com --> <script language="javascript" > function jumpto(selectedURL){ if (document.navForm.jumpmenu.value != "null") { var confirmLeave = confirm('Are you sure you want to leave the Quackit website?'); if (confirmLeave==true) { document.location.href = selectedURL } else { return false; } } } </script> <p>Visit one of these excellent websites:</p> <form name="navForm"> <select name="jumpmenu" onChange="jumpto(document.navForm.jumpmenu.options[document.navForm.jumpmenu.options.selectedIndex].value)"> <option>Jump to...</option> <option value="http://www.zappyhost.com">ZappyHost</option> <option value="http://www.code-generator.net">Code Generator</option> <option value="http://www.natural-environment.com">Natural Environment</option> <option value="http://www.great-workout.com">Great Workout</option> </select> </form> Visit one of these excellent websites:
 JavaScript PromptThe JavaScript prompt box prompts the user to input text. The 'prompt' box is created using JavaScript's built-in prompt() function. When the JavaScript prompt() function is triggered, a small box will pop up and display a message to the user (supplied by you), a text field (for the user's input), an "OK" button, and a "Cancel" button.
Creating/Triggering a JavaScript PromptAs mentioned, you create a JavaScript prompt box by calling the built-in JavaScript prompt() function. The function accepts two parameters: Your message to the user (for example, "What is your favorite website?"), and the default response (eg, "Quackit.com").
JavaScript Prompt - Basic ExampleYou can place the JavaScript prompt() function straight into an HTML tag. Like this:
<!-- JavaScript and HTML codes by Quackit.com --> <input onclick="prompt('What is your favorite website?', 'Quackit.com');" value="Click me..." /> JavaScript Prompt - A More Useful ExampleThe above example works, but it doesn't really do much. We asked the user for their input but we didn't do anything with their input!
We could make this more useful by using the user's input to determine what we display to them. So, here's another (more useful) example, where we include the JavaScript prompt() function within another function. Here, we make our website more personal by displaying the user's name in our message to them:
Here's an example:
<!-- JavaScript and HTML codes by Quackit.com --> <script language="javascript" > function welcomeMsg(promptMsg) { visitorName = prompt(promptMsg, ''); alert("Welcome " + visitorName + "," + "\n\n" + "You are currently visiting one of the best web development sites on the net! Hope you find Quackit useful!" + "\n\n" + "Hey " + visitorName + ", don't forget to recommend us to your friends!"); } </script> <form> <input onclick="welcomeMsg('What is your name?');" value="Read our Welcome Message!" /> </form>  JavaScript Status Bar MessagesJavaScript can be used to display messages in the status bar using window.status. For example, you can display a javascript status bar message whenever your users hover over your hyperlinks.
Status Bar ExampleHover over me!
To do this, use the following code:
<a href="javascript_status_bar_messages.cfm"
onMouseover="JavaScript:window.status='Status Bar Message goes here'; return true"
onMouseout="JavaScript:window.status=''; return true">Hover over me!</a>

You may have noticed that I specified the onMouseout to restore the status bar to nothing when the user hovers away from the link.
Example Doesn't Work for You?Most (newer) major browsers disable status bar messages by default. If your status bar doesn't change when you hover over the link, it's probably because of this.
If you really want to see this example, you can enable status bar messages by changing your browser settings.
For example, in Firefox:
  1. Go to Tools > Options
  2. Click the Content tab
  3. Ensure that the JavaScript option is checked
  4. Click Advanced (next to the Enable JavaScript option)
  5. Check the Change status bar text option
  6. Click OK to save this screen
  7. Click OK again
In Internet Explorer:
  1. Go to Tools > Internet Options
  2. Click the Security tab
  3. Ensure that the Internet option is selected/highlighted
  4. Click Custom Level... (this launches the security settings for the Internet zone)
  5. Scroll down until you see Allow status bar updates via script (under the Scripting option). Click Enable
  6. Click OK to save this screen
  7. Click OK again
  Image Rollovers Jack
Image rollovers are a popular way of making a website appear more dynamic. Image rollovers are often used for highlighting buttons when users hover over them with using their mouse. Of course, there are plenty of other uses for image rollovers too, because the basic principal of image rollovers is that you simply swap one image with another image.
Basic image rolloversYou code image rollovers by using the onMouseover event handler to swap the first image with the second image. The onMouseout event handler swaps it back to the original image.
<a href="http://www.quackit.com/javascript/image_rollovers.cfm"
onMouseOver="/pix/smile.gif"
onMouseOut="/pix/nosmile.gif">
<img src="/pix/nosmile.gif"
width="100"
height="100"
border="0"
name="jack">
</a>

There's only one problem with the above method for performing image rollovers, and that is, the browser doesn't load the second image until the user hovers over the first image. This image could take a second or two to load - which reduces the impact of the rollover. You really want the image to swap immediately - not after a few seconds.
Better image rolloversTo prevent any delay in your second image appearing, you need to preload your images. This is not as tricky as it sounds - you simply load all your images into the browsers cache at the time the page loads.
To preload your imagesPlace this code between the <head></head> tags of your document (as you would normally do with most JavaScript).
// Pre load images for rollover
if (document.images) {
smile = new Image
nosmile = new Image

smile.src = "/pix/smile.gif"
nosmile.src = "/pix/nosmile.gif"
}
else {
smile = ""
nosmile = ""
}

The if, else checks if the browser can perform image rollovers. These browsers include the document.images object (which was implemented in JavaScript 1.1 and all subsequent versions).
Your image rollover using your preloaded images <a href="http://www.quackit.com/javascript/image_rollovers.cfm"
onMouseOver="document.jack.src=smile.src"
onMouseOut="document.jack.src=nosmile.src">
<img src="/pix/nosmile.gif"
width="100"
height="100"
border="0"
name="jack">


This part is similar to the basic image rollover, but it is now calling the preloaded images - so there shouldn't be any delay when you hover over them!
Image rollovers and functionsYou could go a step further and stick your image rollover code into a function. This can be handy if you have multiple image rollovers because you only need to write the code in one place, then call the function whenever you perform an image rollover - you don't need to write lots of duplicate code.
The image rollover function:
// Pre load images for rollover
if (document.images) {
smile = new Image
nosmile = new Image

smile.src = "/pix/smile.gif"
nosmile.src = "/pix/nosmile.gif"
}


function swapImage(thisImage,newImage) {
if (document.images) {
document[thisImage].src = eval(newImage + ".src")
}
}


Calling the rollover function:
<a href="http://www.quackit.com/javascript/image_rollovers.cfm"
onMouseOver="swapImage('jack','smile')"
onMouseOut="swapImage('jack','nosmile')">
<img src="/pix/nosmile.gif"
width="100"
height="100"
border="0"
name="jack">
</a>

Using the above function, if a browser doesn't support the document.images object, then it will simply ignore the code - there's no need for an else in this case.
 JavaScript Popup WindowsYou can use JavaScript to create popup windows. Popup windows are different to simply opening a new browser window.
If you only want to open a new browser window you can add the target="_blank" attribute within your
<a> tag (see Opening a new window in HTML). Popup windows however, are more powerful. Using JavaScript's window.open() method, you can determine what the window looks like (i.e. size, whether it has scrollbars, status bars etc).
Basic JavaScript Popup ScriptHere is the basic script for generating a popup window:
window.open('http://www.quackit.com/common/link_builder.cfm','popUpWindow','height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes'); This code is best placed inside a function (see below). But first things first. Here's an explanation of the above code.
The window.open() method takes three arguments: the URL of the new page, the name of the window, and the attributes of the window. The attributes are optional and should be quite self explanatory in the above example. You can change these to see how it affects the popup window.
Basic Function for Popup WindowsYou can put the above code into a function, then call the function, passing the URL as a parameter, whenever you want to open a popup window.
Doing this allows you to cut down on the amount of code you use when using popups.
Here's a working example.
The JavaScript:
// Popup window function function basicPopup(url) { popupWindow = window.open(url,'popUpWindow','height=500,width=500,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes'); } The above script creates a function that accepts a parameter called "url". You can now call the function in your HTML as follows.
The HTML:
<a href="http://www.quackit.com/common/link_builder.cfm" onclick="basicPopup(this.href);return false">Open a popup window</a> Here, we create a normal HTML link, but we also add the onclick event handler to trigger our JavaScript function. In the script, we use this.href to refer to the HTML link (saves us typing it out twice). This piece is the "url" parameter that we're passing to the function.
The return false bit ensures our base page doesn't actually go to that address - only the popup window.
ExampleSo, putting the two together, our code should work like this:
Open a popup window But wait!
You can make your function even more portable by using the script below.
A Better ScriptThis script is more versatile than the above script. This is because the function accepts parameters for more of the popup's properties (ie. height, width, position, name). This means you won't need to create a new function every time you want a different sized popup, a popup with a different name, or a popup in a different position.
<script language="javascript"> var popupWindow = null; function positionedPopup(url,winName,w,h,t,l,scroll){ settings = 'height='+h+',width='+w+',top='+t+',left='+l+',scrollbars='+scroll+',resizable' popupWindow = window.open(url,winName,settings) } </script> <p><a href="http://www.quackit.com/common/link_builder.cfm" onclick="positionedPopup(this.href,'myWindow','500','300','100','200','yes');return false">Positioned Popup</a></p> The above code creates the following link:
Positioned Popup
Automatically Center your PopupThis function centers the popup in the middle of the users' screen. The JavaScript code will detect the screen size (each user could have a different screen size), then position the popup window in the center.
So, if you need the popup centered in the middle of the users' screen, use the following code:
<script language="javascript"> var popupWindow = null; function centeredPopup(url,winName,w,h,scroll){ LeftPosition = (screen.width) ? (screen.width-w)/2 : 0; TopPosition = (screen.height) ? (screen.height-h)/2 : 0; settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable' popupWindow = window.open(url,winName,settings) } </script> <p><a href="http://www.quackit.com/common/link_builder.cfm" onclick="centeredPopup(this.href,'myWindow','500','300','yes');return false">Centered Popup</a></p> The above code creates the following link:
Centered Popup
 JavaScript RedirectA URL redirect or URL redirection usually refers to when a web page, as soon as it is loaded, redirects to another web page. This technique can be useful if the content on your page has moved to another page.
In JavaScript, you script a redirect using the same code you use to load a page.
Redirect codeTo create a JavaScript redirect, place the following code between the head tags of your HTML page (replacing the URL with the URL that you want to redirect to).
<script >
<!--
window.location = "http://www.quackit.com"
//-->
</script>

 Timed JavaScript RedirectYou might know that you can use JavaScript to redirect to another page. But did you know that you can tell JavaScript to wait before it does this redirect?
You can create a timed JavaScript redirect using the following code (replacing the URL with the URL that you want to redirect to).
<script >
<!--
setTimeout("location.href = 'http://www.natural-environment.com';",1500);
-->
</script>

Timed Redirect FunctionThere may be times when you want a JavaScript timed redirect, but you don't want it to redirect as soon as the page loads. You might only want it to kick in after an event occurs on the page.
To do this, place your timed redirect code into a function. Then you can call it with any event handler you like.
<script >
<!--
redirectTime = "1500";
redirectURL = "http://www.natural-environment.com";
function timedRedirect() {
setTimeout("location.href = redirectURL;",redirectTime);
}
// -->
</script>

<div
onclick="JavaScript:timedRedirect()">
Click me for a timed redirect.
</div>

The above code results in this:
Click me for a timed JavaScript redirect.In these examples, the page will only redirect if the user has JavaScript enabled on their browser. If you want a timed redirect to occur regardless, try using an HTML redirect. Note that if you use HTML, your timed redirects will occur when the page loads.
Redirecting to Multiple URLsLet's improve our JavaScript function a little bit. Here, we will modify our function so that we can pass in the URL of our choice, as well as the amount of time we want it to wait before redirecting. By doing this, we won't need to "hardcode" the variables in the JavaScript above the function as we did above.
Modifying our function will enable us to call it from multiple places on the same page (for example, we could call the function from two different buttons - each with a different URL to redirect to).
In order to do this, the change is very simple. All we need to do is tell the function to accept two parameters - one for the URL, and one for the timeout period. We do this by placing the variable names in the brackets, separated by a comma. Like this:
<script >
<!--
function eventualRedirect(redirectTo, timeoutPeriod) {
setTimeout("location.href = redirectTo;",timeoutPeriod);
}
// -->
</script>

<div
onclick="JavaScript:eventualRedirect(redirectTo='http://www.natural-environment.com',
timeoutPeriod='1500'
)">Go to Natural Environment.</div>
<br />
<div
onclick="JavaScript:eventualRedirect(redirectTo='http://www.great-workout.com',
timeoutPeriod='2500'
)">Go to Great Workout.</div>

The above code results in this:
Go to Natural Environment.
Go to Great Workout.  JavaScript Refresh Page Refresh Page
By incorporating refresh code with a JavaScript function, you can trigger a refresh at any time that makes sense to your web application.
HTML RefreshThe above examples will only work as long as the user has JavaScript enabled on their browser. You can also use HTML to refresh a page automatically once the page has loaded. This is achieved by using the HTML meta tag.