Open Source Tutorials - Open Source Training
Open source training & tutorials from experienced, passionate people
chrome icon firefox icon ie icon opera icon safari icon Sings in these Browsers
A- A A+

By A Web Design

Javascript Tutorial | Javascript Training

You are looking for:

  • A Javascript tutorial ( or three ) on how to validate what’s being keyed into the text boxes used on your Contact - Us form on your website
  • A Javascript tutorial on how to add Captcha to your web site’s registration form. This is another priority. You know that this can help prevent spam bots from registering on your website

You’ve come to the right place, for easy to learn, well graded, Javascript training.

Each Javascript tutorial, steps you through the basics of how to craft Javascript code to do what you want.

All tutorials have been written and tested by people using Javascript for a number of years. I really believe that you will not look anywhere else for your Javascript training.

Each carefully graded Javascript tutorial demonstrates:

  • Just how easy it is to structure and embed Javascript in your HTML code
  • Simple code that delivers a specific advantage to your website

OpenSourceVarsity.com is likely the only place online where you can chat live with a Javascript professional. We welcome your questions about Javascript, every Monday, Wednesday and Friday between 10:00AM and 12:00AM Indian Standard Time.

All the Javascript training material can be freely downloaded to your desktop as PDF files and used for reference again and again, so you have it whenever you need it.

Take advantage of all the Javascript training that happens in our tech forum discussions and community. Why not hop across to our Open source tutorial forum, and start posting your questions and get help from your peers right now!.

Also, remember that every Monday, Wednesday and Friday, between 10:00am and 12:00am Indian Standard Time (i.e. GMT + 5.30) you can enter into live chat with Mr. Ivan Bayross a technical author who has written and published more than sixty seven books, and is still writing.


pdf icons

Introduction to Javascript

Javascript

Javascript is an object-oriented, client side, scripting language that empowers programmers to create interactive web pages. Javascript permits user data, which is entered into an HTML form to be validated as required.

Javascript offers several advantages to a web developer such as:

  1. A shortened development cycle
  2. Ease of learning
  3. Small size scripts

And so on.

The power of Javascript can be easily and quickly used to extend the functionality of static HTML pages.

Javascript is a dialect of the ECMAScript standard and is characterized as a dynamic, weakly typed, prototype-based language. Javascript was influenced by many languages and was designed to look like Java, but to be easier for non-programmers to work with.

History of Javascript

Javascript was originally developed by Brendan Eich of Netscape under the name Mocha, which was later renamed to LiveScript, and finally to Javascript. The change of name from LiveScript to Javascript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web Browser.

Javascript was first introduced and deployed in the Netscape Browser version 2.0B3 in December 1995. The naming has caused confusion, giving the impression that the language is a spin-off of Java, and it has been characterized by many as a marketing ploy by Netscape to give Javascript the opportunity to leverage what was then a hot new web-programming language i.e. Java.
"Javascript" is a trademark of Sun Microsystems. It is used under license for technology invented and implemented by Netscape Communications and current entities such as the Mozilla Foundation.
Due to the widespread success of Javascript as a client-side scripting language for web pages, Microsoft developed a compatible dialect of the language, naming it JScript to avoid trademark issues.

The Advantages Of Javascript

An Interpreted Language: Javascript is an interpreted language, which requires no compilation steps. This provides an easy development process. Javascript is completely interpreted by a Browser’s built in interpreter in exactly the same as the Browser interprets HTML.

Embedded Within HTML: Javascript does not require any special or separate editor for programs to be written, edited or compiled. It can be written in any text editor like Notepad, along with appropriate HTML tags, and saved as <filename.html>. HTML files with embedded Javascript commands can then be read and interpreted by any Browser that is Javascript enabled (i.e. has a built in Javascript interpreter).

Minimal Syntax - Easy to Learn: By learning just a few commands and simple rules of syntax, complete applications can be built using Javascript.

Quick Development: Because Javascript does not require time-consuming compilations, scripts can be developed in a short period of time. This is enhanced by the fact that many GUI interface features, such as alerts, prompts, confirm boxes, and other GUI elements, are handled by client side Javascript, the Browser and HTML code

Designed for Simple, Small Programs: It is well suited to implement simple, small programs (for example, a unit conversion calculator between miles and kilometers, or pounds and kilograms or dollars and Euros). Such programs can be easily written and executed at an acceptable speed using Javascript. In addition, they can be easily integrated into a web page.

Performance: Javascript can be written such that the HTML files are fairly compact and quite small. This minimizes storage requirements on the Web server and download time for the client. Additionally, because Javascript programs are usually included in the same file as the HTML code for a web page, they require fewer separate Web server accesses.

Procedural Capabilities: Every programming language needs to support facilities such as Condition checking, Looping and Branching. Javascript provides syntax, which can be used to add such procedural capabilities to a web page <filename.html> coding.

Designed for Programming User Events: Javascript supports Object/Event based programming. Javascript recognizes when a form Button is pressed. This event can have suitable Javascript code attached, which will execute when the Button Pressed event occurs.

Javascript can be used to implement context sensitive help. Whenever an HTML form’s Mouse cursor Moves Over a button or a link on the page a helpful and informative message can be displayed in the status bar at the bottom of the Browser window.

Easy Debugging and Testing: Being an interpreted language, scripts in Javascript are tested line by line, and the errors are also listed as they are encountered, i.e. an appropriate error message along with the line number is listed for every error that is encountered. It is thus easy to locate errors, make changes, and test it again without the overhead and delay of compiling.

Platform Independence / Architecture Neutral: Javascript is a programming language that is completely independent of the hardware on which it works. It is a language that is understood by any Javascript enabled Browser. Thus, Javascript applications work on any machine that has an appropriate Javascript enabled Browser installed. This machine can be anywhere on the network.

Since each Browser is for a specific platform, Javascript interpretation will be with respect to the specific platform. The Browser will add whatever platform specific information is required to the Javascript while it interprets the code. Thus, Javascript is truly platform independent. A Javascript program developed on a Unix machine will work perfectly well on a Windows machine.

The fact that a platform specific Browser, maintained at the client end, does the interpretation of Javascript, relieves the developer of the responsibility of maintaining multiple source code files for multiple platforms.

Javascript in web pages

Today’s web sites need to go much beyond HTML to delight a visitor. Today it is a must to allow users, browsing through a web site, to actually interact with the web site. The web site must be intelligent enough to accept users input and dynamically structure web page content, tailor made, to a user’s requests.

This may be as simple as ensuring a web page delivered to a user, has a background color that the user is comfortable with or as complex as delivering a web page with special font sizes for a user with visual disabilities.

Users, who browse through a web site today, prefer to choose to view what interests them. Hence even the content of a web page needs to be dynamic, based on what a user wishes to see.

This requires a web site development environment that will allow the creation of Interactive web pages. These web pages will accept input from a user, then based on the input received return customized web pages, both in content and presentation, to the user.

In the absence of any user input the web site must be intelligent enough to return a default web page containing predetermined information and text formatting.

This calls for a web site development environment with coding techniques capable of accepting a client’s requests and processing these requests. The result of the processing being passed back to the client as standard HTML pages.

The need to return standard HTML pages, that map to a user’s input, is due to the fact are designed to interpret and render HTML on a client’s machine.

Capturing user input is traditionally done via a Form.

After a form captures user input, the form must have a built in technique for sending the information captured back to the Web server for further processing. Processing user requests is generally done via programs located on the Web server.

The form must also have code for Validating user input. Invalid user input, will either cause data to be sent back from the Web server to the Browser which is not what the user wants or give rise to an error message being sent back to the Browser from the Web server. Neither of which would really attract repeat visits to the web site. Javascript does an excellent job of validating user input, client side.

Any Internet application development environment must also facilitate coding, which would run in a Browser at client side for data validation.

Most development environments offer standard constructs for data validation. Standard programming constructs are:

  1. Condition checking constructs
  2. Case checking constructs
  3. Super controlled Loop constructs

Additionally, all development environments provide syntax to create and use memory variables, constants, and functions.

If the development environment is object oriented it will provide an object hierarchy to work with. An Object Oriented Programming (OOP) environment always offers event driven programming. This means that the programming environment will recognize object based events and allow the connection of code snippets to these events. When an event occurs, the code snippets will execute.

All this functionality and more is available in Javascript.

pdf icons text icons

Change the Background Color of an HTML Element (DIV)

FOCUS:

Our aim is to change the background color of a DIV, which must be done on click of a command button.

The id of the DIV whose background color must be changed on click of a command button is main.

HTML Code Snippet

 
<div id="main" class="main">
  <p>Welcome to my web site</p>
  <p>We sell all the widgets you need.</p>
</div>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td>
      <input type="button" id="cmdChangeColor" name="cmdChangeColor" 
      value="Change Background color" onclick="changecolor();" />
    </td>
  </tr>
</table>
 


Javascript Code Snippet

 
  <script type="text/javascript">
  function changecolor()
  {
    var mainContent = "";
    mainContent = document.getElementById("main");
    mainContent.style.backgroundColor = "#FFFF99";
  }
  </script>
 
 

How the DIV’s background color is changed:

When the command button whose id is cmdChangeColor is clicked a user defined Javascript method changecolor(); is invoked.

When changecolor(); is invoked a built in Javascript method getElementById("main") is passed the name of the DIV. Hence the variable mainContent will now hold a handle to the DIV whose id=main.

 
  mainContent = document.getElementById("main");
 

Once the handle to the DIV is available simply set the DIV’s background color by accessing the style property ( i.e.style.backgroundColor={”User defined HEX color value” })of the DIV using standard object oriented notation as shown below.

 
  mainContent.style.backgroundColor="#FFFF99";
  //i.e. #FFFF99 = Yellow.
 


The Complete Code Snippet

 
<html>
<head>
  <title>First HTML DOM Example</title>
  <style type="text/css">
  .main
  {
    font-family:Arial, Helvetica, sans-serif;
    font-size:14px;
    border:solid 1px #000000;
  }
  </style>
  <script type="text/javascript">
  function changecolor()
  {
    var mainContent = "";
    mainContent = document.getElementById("main");
    mainContent.style.backgroundColor = "#FFFF99";
  }
  </script>
</head>
 
<body>
  <div id="main" class="main">
    <p>Welcome to my web site</p>
    <p>We sell all the widgets you need.</p>
  </div>
  <table border="1" cellspacing="0" cellpadding="0">
    <tr>
      <td>
        <input type="button" id="cmdChangeColor" 
        name="cmdChangeColor" value="Change Background color" 
        onclick="changecolor();" />
      </td>
    </tr>
  </table>
</body>
</html>
 

pdf icons

Javascript DOM Introduction

What is Document Object Model?

The Document Object Model (DOM) is an API for HTML and XML documents. It provides a structural representation of any document, permitting a programmer to modify its content and thus the visual presentation of the document on the VDU screen. Essentially, it exposes the content of web pages to Client side scripts that can then manipulate web page content.

W3C’s definition of DOM: The Document Object Model is a platform- and language-neutral interface that will allow client side scripts to dynamically access and update the content, structure and style of a web page in real time. Subsequent to the document’s content being processed (manipulated by a script) the results of that processing will be be incorporated back into the web page on the VDU screen.

All of the properties, methods, and events available to a web developer for manipulating and creating web page content and structure are organized into objects (e.g., the document object that represents the document itself, the table object that represents HTML table elements, the form object that represents HMTL form objects and so forth). Those objects are made accessible to scripting languages in most Browsers.

The DOM is most often manipulated using code written in JavaScript. What this means is that code written in JavaScript, uses the DOM to access all web page elements.

The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API. Though the here is on JavaScript, implementations of the DOM can be built for any programming language such as Java, C# and so on.

Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and Javascript that allows a document’s elements to be manipulated at will.

Hierarchy of Javascript DOM object

The DOM hierarchy continues downward to encompass individual elements on a FORM, such as Text boxes, Labels, Radio buttons, Check boxes, Command buttons and so on, which belong to the form.

JavaScript’s object hierarchy is mapped to the DOM, which in turn is mapped to the web page elements in the Browser window. Hence, when a web page is rendered in a JavaScript enabled browser window, JavaScript is capable of uniquely identifying each element in the web page, because major elements of a web page are bound to the DOM.

The DOM that JavaScript recognizes is described in diagram 1.

JavaScript’s DOM is referred to as an instance hierarchy.

Instance

No HTML object is registered in the DOM by a JavaScript enabled browser unless they are assembled in memory prior being rendered in the browser window.

What this means is, if a document does not have any Anchors described in it the Anchors object will exist but it will be empty. If the document does not have any Links in it the Links object will exist but it will be empty.

Hierarchy

All objects on a web page are not created equal. Each exists in a set relationship with other objects on the web page. From diagram 9.1??? the navigator (i.e. Browser) occupies the topmost slot in the DOM followed by the Window object and so on.

Below the Window is the Document object. Below the document object three other objects exist. They are the Anchor, Link and Form objects. Individual form elements are found under the Form object.

In addition to the DOM, other objects currently recognized by a JavaScript enabled browser are Plug-ins, Applets and Images. Hence using a JavaScript enabled browser and JavaScript most of the major web page objects are accessible.

However, every single element of a web page rendered in the browser window, is not part of the DOM.

For example, HTML tags such as <HEAD> . . . </HEAD>or <BODY> . . . </BODY>are not part of the DOM. Presentation styles, headings, body text, H1 to H6 and so on are not part of the DOM hence not recognized by JavaScript.

diagram1
Diagram1

Understanding Objects In HTML

HTML can be used to create a Graphical User Interface (GUI) in a web page. HTML is capable of accessing and using a number of objects that actually belong to the operating system (i.e. M.S. Windows XP or Vista or 7 and so on). One such object is a textbox. A ‘textbox’ is used in an HTML form to capture user input.

The text box is an object, which belongs to the DOM. JavaScript recognizes a text box. JavaScript facilitates access to all the methods of a textbox. One of the methods of the textbox permits access to the contents of the text box. Hence, JavaScript can process the contents of any textbox in an HTML form.

Properties Of HTML Objects

Just like real world objects, HTML objects have a number of propertiesthat determine the behavior of that object. An object’s properties can be referenced as:
ObjectName.PropertyName

For example, a textbox can have properties like name, sizeand so on.

Methods of HTML Objects

As seen, properties determine the state of an object. While building interactive web pages an object’s properties need to be set dynamically, i.e. while the object is in use. Thus all object based programming environments must have facilities to setor getthe value of object properties. This allows program code to control the state of the object at run time.

Methodsof an object are used to set or get a value of an object’s property. Thus determining how an object behaves. An object’s methods can be referenced as:
ObjectName.MethodName

Using JavaScript it is possible to use an object’s built-in methods and manipulate the object’s properties at run time. This gives a great deal of creative control to web page developers when web pages have to be created on demand.

Once JavaScript code accepts client side input and / or reads a client’s Browser parameters, on demand web pages can be structured and sent to the Browser from any Web Server.

pdf icons text icons

Change Paragraph Font Size

FOCUS

Our aim is to change the background color of a DIV, which must be done on click of a command button.

The id of the DIV whose paragraph font size must be changed on click of a command button is main.

HTML Code Snippet

 
<div id="main" class="main">
  <p>Welcome to my web site</p>
  <p>We sell all the widgets you need.</p>
</div>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td>
      <input type="button" id="cmdChangeFontSize" 
      name="cmdChangeFontSize" value="Change paragraph font size" 
      onclick="changefontsize();" />
    </td>
  </tr>
</table>
 

Javascript Code Snippet

 
<script type="text/javascript">
  function changefontsize()
  {
    var i = "";
    var paragraphs = "";
    paragraphs = document.getElementsByTagName("p");
    for(i=0; i<paragraphs.length; i++)
    {
    paragraphs[i].style.fontSize = '2em';
    }
  }
</script>
 

How the DIV’s paragraph font size is changed:

When the command button whose id is cmdChangeFontSize is clicked a user defined Javascript method changefontsize(); is invoked.

When changefontsize(); is invoked a built in Javascript method getElementsByTagName("p") is passed the name of the DIV. Hence the variable paragraphs will now hold a handle to the DIV whose id=main.

The Javascript code is contained in the function changefontsize();

In this Javascript codespec the built in function getElementsByTagName("p") is passed the HTML tag p. Since there are multiple occurrences of the HTML tag p the handle to a collection of those HTML elements in the DOM is returned and will be available in the memvar paragraphs. A collection of HMTL element is always an array.

Hence the memvar paragraph holds the handle to the HTML p tag array.

paragraphs = document.getElementsByTagName("p");

Now the content within all the <p></p> tags have to have their font size increased to 2em.

Hence we will have to loop through HTML p tags array, and for each occurrence of the HTML tag p change the content fontsize to 2em.

Since the memvar paragraphs holds the handle to the HTML p tag array paragraphs.length will return the number of records held in the HTML p tag array. Now a simple for loop is used to step through the records of the HTML p tag array and change their content font size to 2em. Take a look at the Javascript code snippet below.

for(i=0; i<paragraphs.length; i++)
{
paragraphs[i].style.fontSize = '2em';
}

The Complete Code Snippet

 
<html>
 
<head>
<title>Second HTML DOM Example</title>
<script type="text/javascript">
function changefontsize()
{
  var i = "";
  var paragraphs = "";
  paragraphs = document.getElementsByTagName("p");
  for(i=0; i<paragraphs.length; i++)
  {
    paragraphs[i].style.fontSize = '2em';
  }
}
</script>
</head>
 
<body>
<div id="main" class="main">
  <p>Welcome to my web site</p>
  <p>We sell all the widgets you need.</p>
</div>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td>
      <input type="button" id="btn2" name="fontsize"
      value="Change paragraph font size" onclick="changefontsize();" />
    </td>
  </tr>
</table>
</body>
</html>
 
 
OSV Newsletter


Receive HTML?

NOTE: To prevent subscription to the OSV newsletter, uncheck the checkbox above.
Guest Blog for OSV
Free Ebook Download
LinkShare_180x150
Artisteer - DNN Skin Generator
Tapestry Theme - A Tumblog-Style Theme for Wordpress