Click here to Skip to main content
13,255,340 members (57,313 online)
Click here to Skip to main content
Add your own
alternative version


393 bookmarked
Posted 11 Oct 2000

JavaScript For Beginners

, 26 Oct 2000
Rate this:
Please Sign up or sign in to vote.
A very easy tutorial for JavaScript beginners


Embedding and including

Let's first see a simple example:

<title>This is a JavaScript example</title>
<script language="JavaScript">
document.write("Hello World!");
<body> Hi, man! </body>

Usually, JavaScript code starts with the tag <script language="JavaScript"> and ends with the tag </script>. The code placed between <head> and </head>. Sometimes, people embed the code in the <body> tags:

.....// The code embedded in the <body> tags.

Why do we place JavaScript code inside comment fields <!-- and //-->? It's for ensuring that the Script is not displayed by old browsers that do not support JavaScript. This is optional, but considered good practice. The LANGUAGE attribute also is optional, but recommended. You may specify a particular version of JavaScript:

<script language="JavaScript1.2">

You can use another attribute SRC to include an external file containing JavaScript code:

<script language="JavaScript" src="hello.js"></script>

For example, shown below is the code of the external file hello.js:

document.write("Hello World!")

The external file is simply a text file containing JavaScript code with the file name extension ".js". Note:

  1. Including an external file only functions reliably across platforms in the version 4 browsers.
  2. The code can't include tags <script language...> and </script>, or you will get an error message.

Back to top

write and writeln

In order to output text in JavaScript you must use write() or writeln(). Here's an example:

<TITLE> Welcome to my site</TITLE></HEAD>
document.write("Welcome to my site!");
// -->

Note: the document object write is in lowercase as JavaScript is case sensitive. The difference between write and writeln is: write just outputs a text, writeln outputs the text and a line break.

Back to top

Document object

The document object is one of the most important objects of JavaScript. Shown below is a very simple JavaScript code:

document.write("Hi there.")

In this code, document is the object. write is the method of this object. Let's have a look at some of the other methods that the document object possesses.


You can always include the last update date on your page by using the following code:
<script language="JavaScript">
document.write("This page created by John N. Last update:" + document.lastModified);

All you need to do here is use the lastModified property of the document. Notice that we used + to put together This page created by John N. Last update: and document.lastModified.

bgColor and fgColor

Lets try playing around with bgColor and fgColor:


Back to top

Message Box


There are three message boxes: alert, confirm, and prompt. Let's look at the first one:
window.alert("Welcome to my site!")

You can put whatever you want inside the quotation marks.


An example for confirm box:
window.confirm("Are you sure you want to quit?") 


Prompt box is used to allow a user to enter something according the promotion:

window.prompt("please enter user name") 

In all our examples above, we wrote the box methods as window.alert(). Actually, we could simply write the following instead as:


Back to top

Variables and Conditions

Let's see an example:

var x=window.confirm("Are you sure you want to quit")

if (x)
    window.alert("Thank you.")
    window.alert("Good choice.")

There are several concepts that we should know. First of all,

is a variable declaration. If you want to create a variable, you must declare the variable using the var statement. x will get the result, namely, true or false. Then we use a condition statement if else to give the script the ability to choose between two paths, depending on this result (condition for the following action). If the result is true (the user clicked "ok"), "Thank you" appears in the window box. If the result is false (the user clicked "cancel"), "Good choice" appears in the window box instead. So we can make more complex boxes using var, if and those basic methods.

var y=window.prompt("please enter your name")

Another example:

var x=confirm("Are you sure you want to quit?")
if (!x)
Welcome to my website!.

If you click "cancel", it will take you to yahoo, and clicking ok will continue with the loading of the current page "Welcome to my website!". Note:if (!x)means: if click "cancel". In JavaScript, the exclamation mark ! means: "none".

Back to top


Functions are chunks of code.Let's create a simple function:

function test()
   document.write("Hello can you see me?")

Note that if only this were within your <script></script> tags, you will not see "Hello can you see me?" on your screen because functions are not executed by themselves until you call upon them. So we should do something:

function test()
   document.write("Hello can you see me?")

Last linetest() calls the function, now you will see the words "Hello can you see me?".

Back to top

Event handler

What are event handlers? They can be considered as triggers that execute JavaScript when something happens, such as click or move your mouse over a link, submit a form etc.


onClick handlers execute something only when users click on buttons, links, etc. Let's see an example:

function ss()
alert("Thank you!")
<input type="button" value="Click here" onclick="ss()">

The function ss() is invoked when the user clicks the button. Note: Event handlers are not added inside the <script> tags, but rather, inside the html tags.


The onload event handler is used to call the execution of JavaScript after loading:

<body onload="ss()">
<frameset onload="ss()">
<img src="whatever.gif" onload="ss()">


These handlers are used exclusively with links.

<a href="#" onMouseOver="document.write('Hi, nice to see you!">Over Here!</a>
<a href="#" onMouseOut="alert('Good try!')">Get Out Here!</a>


onunload executes JavaScript while someone leaves the page. For example to thank users.

<body onunload="alert('Thank you for visiting us. See you soon')">

Handle multiple actions

How do you have an event handler call multiple functions/statements? That's simple. You just need to embed the functions inside the event handler as usual, but separate each of them using a semicolon:

<input type="button" value="Click here!" onClick="alert('Thanks
for visiting my site!');window.location=''">

Back to top


Let's say you have a form like this:

<form name="aa">
<input type="text" size="10" value="" name="bb"><br>
<input type="button"

value="Click Here"onclick="alert(">

Notice that we gave the names to the form and the element. So JavaScript can gain access to them.


If you want to get information from users and want to check each element (ie: user name, password, email) individually, and alert the user to correct the wrong input before moving on, you can use onBlur. Let's see how onblur works:

function emailchk()
if (x.indexOf("@")==-1)
	alert("It seems you entered an invalid email address.")

Email:<input type="text" size="20" name="email"

Comment: <textarea name="comment" rows="2" cols="20"></textarea><br>
<input type="submit" value="Submit">

If you enter an email address without the @, you'll get an alert asking you to re-enter the data. What is: x.indexOf(@)==-1? This is a method that JavaScript can search every character within a string and look for what we want. If it finds it will return the position of the char within the string. If it doesn't, it will return -1. Therefore, x.indexOf("@")==-1 basically means: "if the string doesn't include @, then:

alert("It seems you entered an invalid email address.")

What's focus()? This is a method of the text box, which basically forces the cursor to be at the specified text box. onsubmit Unlike onblur, onsubmit handler is inserted inside the <form> tag, and not inside any one element. Lets do an example:

function validate()
	alert ("Please enter User Name")
	return false
	alert ("Please enter Password")
	return false
<form name="login" onsubmit="return validate()">
<input type="text" size="20" name="userName">
<input type="text" size="20" name="password">
<input type="submit" name="submit" value="Submit">

if(document.login.userName.value==""). This means "If the box named userName of the form named login contains nothing, then...". return false. This is used to stop the form from submitting. By default, a form will return true if submitting. return validate() That means, "if submitting, then call the function validate()".

Protect a file by using Login

Let's try an example

<SCRIPT Language="JavaScript">
function checkLogin(x)
if (( != "Sam")||(x.pass.value !="Sam123"))
	alert("Invalid Login");
	return false;
<p>UserID:<input type="text" name="id"></p>
<p>Password:<input type="password" name="pass"></p>
<p><input type="button" value="Login" onClick="checkLogin(this.form)"></p>

|| means "or", and ,!= indicates "not equal". So we can explain the script: "If the id does not equal 'Sam', or the password does not equal 'Sam123', then show an alert ('Invalid Login') and stop submitting. Else, open the page 'main.htm'".

Back to top


In most cases, a form can be repaced by a link:

<a href="JavaScript:window.location.reload()">Click to reload!</a>

More examples:

<a href="#" onClick="alert('Hello, world!')">Click me to say Hello</a><br>
<a href="#" onMouseOver="location='main.htm'">Mouse over to see Main Page</a>

Back to top


Let's see an example:

var x= new Date();
document.write (x);

To activate a Date Object, you can do this: var x=new Date(). Whenever you want to create an instance of the date object, use this important word: new followed by the object name().

Dynamically display different pages

You can display different pages according to the different time. Here is an example:

var banTime= new Date()
var ss=banTime.getHours()
if (ss<=12)
	document.write("<img src='banner1.gif'>")
	document.write("<img src='banner2.gif'>") 
Date object

Back to top


Open a window

To open a window, simply use the method "":

<input type="button" value="Click here to see" onclick="'test.htm')">

You can replace test.htm with any URL, for example, with

Size, toolbar, menubar, scrollbars, location, status

Let's add some of attributes to the above script to control the size of the window, and show: toolbar, scrollbars etc. The syntax to add attributes is:


For example:

<input type="button" value="Click here to see"


Another example with no attributes turned on, except the size changed:

<input type="button" value="Click here to see"


Here is the complete list of attributes you can add:

width height toolbar
location directories status
scrollbars resizable menubar


To reload a window, use this method:


Close Window

Your can use one of the codes shown below:

<input type="button" value="Close Window" onClick="window.close()">
<a href="javascript:window.close()">Close Window</a>


The basic syntax when loading new content into a window is:


This is the same as

<a href="test.htm>Try this </a>

Let's provide an example, where a confirm box will allow users to choose between going to two places:

function ss()
var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
if (ok)

Remote Control Window

Let's say you have opened a new window from the current window. After that, you will wonder how to make a control between the two windows. To do this, we need to first give a name to the window.Look at below:'test.htm','','width=200,height=200')

By giving this window a name "aa", it will give you access to anything that's inside this window from other windows. Whenever we want to access anything that's inside this newly opened window, for example, to write to this window, we would do this: aa.document.write("This is a test.").

Now, let's see an example of how to change the background color of another window:

<input type="button" value="Open another page"

<input type="radio" name="x" onClick="aa.document.bgColor='red'">
<input type="radio" name="x" onClick="aa.document.bgColor='green'">
<input type="radio" name="x" onClick="aa.document.bgColor='yellow'">


Using "opener" property, we can access the main window from the newly opened window.

Let's create Main page:

<input type="button" value="Open another page"


Then create Remote control page (in this example, that is test.htm):

function remote(url){
<p><a href="#" onClick="remote('file1.htm')">File
<p><a href="#" onClick="remote('file2.htm')">File

Try it now!

Back to top


One of the most popular uses of loading multiple frames is to load and change the content of more than one frame at once. Lets say we have a parent frame:

<frameset cols="150,*">
<frame src="page1.htm" name="frame1">
<frame src="page2.htm" name="frame2">

We can add a link in the child frame "frame1" that will change the contents of not only page1, but page2 too. Shown below is the html code for it:

<h2>This is page 1 </h2>
<a href="page3.htm"

onClick="parent.frame2.location='page4.htm'">Click Here</a>

Notice: You should use "parent.frameName.location" to access another frame. "parent" standards for the parent frame containing the frameset code.

Back to top


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
SanketKubade26-Oct-17 2:25
memberSanketKubade26-Oct-17 2:25 
QuestionHelp Pin
Śliwka Łukasz25-Jan-17 1:17
memberŚliwka Łukasz25-Jan-17 1:17 
Question5ed Pin
Karthik Bangalore10-Jul-16 23:11
memberKarthik Bangalore10-Jul-16 23:11 
GeneralMy vote of 4 Pin
Ujjval Shukla13-Jun-15 2:18
memberUjjval Shukla13-Jun-15 2:18 
QuestionSuperb article Pin
Punit Sharma9-May-15 10:39
memberPunit Sharma9-May-15 10:39 
GeneralVote 5 Pin
Tit Copernicus2-Nov-14 19:30
memberTit Copernicus2-Nov-14 19:30 
QuestionVery GOOD Pin
neoxquick@gmail.com17-Mar-14 23:11
memberneoxquick@gmail.com17-Mar-14 23:11 
GeneralMy vote of 3 Pin
Allen Anderson7-Mar-14 20:52
memberAllen Anderson7-Mar-14 20:52 
SuggestionJavaScript Pin
J-Tru31-Dec-13 7:55
memberJ-Tru31-Dec-13 7:55 
SuggestiononMouseOver typo Pin
Alec Gilbert5-Oct-13 14:09
memberAlec Gilbert5-Oct-13 14:09 
GeneralMy vote of 5 Pin
hasharw25-Sep-13 21:56
memberhasharw25-Sep-13 21:56 
QuestionJscript Pin
Rajat Mangal25-Aug-13 14:19
memberRajat Mangal25-Aug-13 14:19 
QuestionThank u Pin
k aparna20-Dec-12 20:47
memberk aparna20-Dec-12 20:47 
GeneralMy vote of 5 Pin
udoyen4-Oct-12 11:55
memberudoyen4-Oct-12 11:55 
GeneralMy vote of 1 Pin
Member 918769229-Jun-12 19:13
memberMember 918769229-Jun-12 19:13 
GeneralGood article Pin
sameeraRangaChakila8-May-12 1:09
membersameeraRangaChakila8-May-12 1:09 
GeneralMy vote of 5 Pin
Prince Antony G29-Nov-11 23:08
memberPrince Antony G29-Nov-11 23:08 
GeneralMy vote of 5 Pin
Shashikant_Giri25-May-11 1:25
memberShashikant_Giri25-May-11 1:25 
GeneralExcellent article Pin
Walter Capers13-Jan-11 2:54
memberWalter Capers13-Jan-11 2:54 
Generalbeginner, using 'book of javascript.' broken image question. Pin
ellibet5-Jul-10 11:39
memberellibet5-Jul-10 11:39 
GeneralMy vote of 1 Pin
vasilerusu22-Feb-10 4:17
membervasilerusu22-Feb-10 4:17 
GeneralPassing dynamic button ID to the javascript function [modified] Pin
Rajeshgut8-Oct-09 5:41
memberRajeshgut8-Oct-09 5:41 
GeneralClean and clear Pin
Balkrishna Talele1-Jul-09 21:58
memberBalkrishna Talele1-Jul-09 21:58 
GeneralLogin Example problem Pin
I am BATMAN6-May-09 7:40
memberI am BATMAN6-May-09 7:40 
QuestionURL parameters Pin
VHsuper6225-Mar-09 19:29
memberVHsuper6225-Mar-09 19:29 
GeneralRe: Tutorial Pin
shita00925-Nov-08 6:51
membershita00925-Nov-08 6:51 
QuestionHow to do the Gmail style dynamic deleting the child node? Pin
AlexKiat31-Jul-08 4:50
memberAlexKiat31-Jul-08 4:50 
QuestionHi. [modified] Pin
vinaykskvs29-May-08 2:01
membervinaykskvs29-May-08 2:01 
GeneralIt good and simple Pin
gujjeli13-May-08 22:21
membergujjeli13-May-08 22:21 
QuestionInput data using a virtual keyboard?? Pin
huh3-Apr-08 8:24
memberhuh3-Apr-08 8:24 
GeneralDatabase Problem Pin
manojbhoyar2-Apr-08 0:39
membermanojbhoyar2-Apr-08 0:39 
Generalhy i am rohit wadhwa Pin
rohit wadhwa24-Mar-08 4:11
memberrohit wadhwa24-Mar-08 4:11 
Generalhmmm.. jabardasta artical.... Pin
laxya20-Mar-08 1:16
memberlaxya20-Mar-08 1:16 
Questionworking with javascript popup in 2.0 Pin
DownBySpj30-Nov-07 1:36
memberDownBySpj30-Nov-07 1:36 
Generalvery nice... Pin
govardhankumar3-Oct-07 22:19
membergovardhankumar3-Oct-07 22:19 
GeneralGood article........ Pin
Rajeev KTS InfoTech29-Aug-07 23:09
memberRajeev KTS InfoTech29-Aug-07 23:09 
QuestionI know a real little bit about Javascript:omg:. Please help! Pin
LaineGenna7-Aug-07 17:27
memberLaineGenna7-Aug-07 17:27 
QuestionJavascript removechild Pin
Member #373983818-Jan-07 13:26
memberMember #373983818-Jan-07 13:26 
QuestionDrag and drop and how to snap Pin
Chica Nadadora9-Oct-06 15:31
memberChica Nadadora9-Oct-06 15:31 
AnswerRe: Drag and drop and how to snap Pin
just3ala215-Oct-06 23:56
memberjust3ala215-Oct-06 23:56 
GeneralRe: Drag and drop and how to snap Pin
RichardGrimmer12-Oct-08 0:33
memberRichardGrimmer12-Oct-08 0:33 
Questionhow to call 2 js functions for a single event Pin
kartsj10-Aug-06 2:47
memberkartsj10-Aug-06 2:47 
AnswerRe: how to call 2 js functions for a single event Pin
just3ala216-Oct-06 0:04
memberjust3ala216-Oct-06 0:04 
Questionlike GMAI, YAHOO CANADA Pin
4mworld16-Jul-06 1:54
member4mworld16-Jul-06 1:54 
Thanks but how we can load contnt dynamicly like in google mail where the menus reamin in place but contnt change dynamicly pleas helpSmile | :)

The best stay at lest of war
AnswerRe: like GMAI, YAHOO CANADA Pin
just3ala216-Oct-06 0:05
memberjust3ala216-Oct-06 0:05 
QuestionHow to make cancel the default in a confirm box Pin
rmaringer24-Feb-06 12:41
memberrmaringer24-Feb-06 12:41 
AnswerRe: How to make cancel the default in a confirm box Pin
rashmi_sam9-Mar-06 19:07
memberrashmi_sam9-Mar-06 19:07 
GeneralRe: How to make cancel the default in a confirm box Pin
rmaringer10-Mar-06 3:57
memberrmaringer10-Mar-06 3:57 
GeneralRe: How to make cancel the default in a confirm box Pin
krishna1122-Apr-08 19:11
memberkrishna1122-Apr-08 19:11 
Generalmenu display Pin
anusreeravi22-Feb-06 21:01
memberanusreeravi22-Feb-06 21:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 27 Oct 2000
Article Copyright 2000 by Nongjian Zhou
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid