HTMLStarter.com
HTML, CSS, JavaScript for beginners - Interactive Training

Introduction to Javascript

Javascript (NOT Java!) is a programming language that needs only a browser to run and a simple text editor (like notepad) to write. Programmers like to call it a scripting language, maybe since it is simply interpreted by the browser (not compiled into an .exe file) and cannot be used to produce software. Otherwise, it can be as object oriented as any high level language, it also has many of their functionalities. However, because of security reasons, its output and input are limitted only to and from the browser (unless it is used on the server as a server-side script).

On this page...

What does Javascript do?

Simply put, it responds to a user's action such as clicks or mouse-overs on an element. The response may be as trivial as changing the color of an element, or as complex as solving systems of non-linear differential equations and displaying the result. As a web designer, you can use Javascript to enhance the appearance, functionality, and interactivity of your web page using such elements as drop-down menus, tooltips, calendars, slide shows or other dynamic content displayers. Or, you may design full-fledged special web pages and widgets like games, puzzles, mortgage calculators, unit converters, equation solvers, etc.

The Very Basics of Javascript

Let's start with a simple exaple. Click on the output button of the following code.

Using the Javascript alert()
Code<button onclick="alert('Hello there!')">Click here</button>
Output


In this example, we used the button tag as our element, onclick="" as an attribute, and alert() as a Javasript command. So far we saw only attributes that modify the appearance of an element, but there are also attributes which, when used in conjunction with Javascript, respond to actions based on the script code. The most commonly used are onclick="", oncdblclick="", onmouseover="", onmouseout="". Their names are self-descriptive of their functions, for example, onmouseover() responds when the mouse is placed ove the element. Now, let's break down our simple code.

onclick=""
1. This sends a message to a Javascript code when the user clicks on the element (here, the element is a button)
2. Place Javascript commands, separated by semi-colons(;), within the quotes.
3. You can use single-quotes instead of double quotes.

alert()
1. This is a Javascript command (or statement) that displays an alert box, nothing more -- just click the OK button of the alert box to close it.
2. Within the parenthesis place what ever message you want to display in single- or double-quotes.
3. Don't confuse the quotes!! If you use single-quotes for onclick, then use double-quotes for the alert, and vise-versa.

Javascript variables, constants, opertors, expressions, statements

A variable is a means of storing data for later use. It is just a name, such as x, x1, y, myIncome, etc., that is created by the programmer to hold data values. For example, the variable x may hold a numeric value of 100, a string value of "Joe", or a boolean value of either true or false. Variable names are case-sensitive -- x an X are completely different variables.
A constant is a variable whose value doesn't change within the program. A string constant is placed inside single- or double quotes.
An operator is a symbol or string that performs a manipulation of certain data. Basic operators are addition, subtraction, multiplication, division, and assignment. These operatotr in Javascript are, respectively, +, -, *, /, =.
The + operator is obviously used to add numbers, but it is also used to cocatenate (join) strings. For instance, "They call me " + "Mr. Tibbs" will result in a single string "They call me Mr. Tibbs".
An expression manipulates variables and constants with help of operators, like x + x1.
The asignment operator ( = ) stores data into a variable. This is done by placing the variable on the left of the equal sign and an expression to its right. For example, x = 25.6 + y;, is a statement that adds 25.6 to the value stored in the variable y and stores the result in the variable x. A series of Javascript statements are separated by semi-colons ( ; ). And a group of statements are placed within curly brackets ( { } )

Now, practice using the alert command to see if you can write correct Javascript expressions. Note that what actually goes inside the parenthesis of alert is an expression. So, the rule is
alert(expression)

Interactive Exercise

Below, in the 'Coding Area', there are a series of Javascript statements that assign values to variables and also an alert statement. Change the expression inside the alert (or add more alerts) and click on the 'Show alert' button to see if you have corectly written an expressions. If there is an error, a message will be displayed at the bottom. You czn copy and pate the Exercise Hints to try them.

Coding AreaExercise Hints
.

Try the following. If ERROR occurs, investigate the cause and correct it.

alert(s + s1 + "Joe")
alert("x times y " + s1 +" "+ x*y)
alert("x * y = " + xy)
alert("y/x = " y/x)
alert(x+y)
alert("x + y = " + x + y)
Alert(x+y)
alert("x + y = " + (x + y))
alert(x + y = (x + y))
alert('Tim Tibow ' + S1 + ' ' + S)

TOP

Using Javascript with Forms

In programming, we do not assign values to variables such as we did for x=100 in the above example. Instead, values are input by the user so that computations can be general. In order to be able to receive user input, we have to use forms and you may wish to review the construction of forms. Let's now see this in action through a percent calculator example. In this example, when a user enters an item quantity and a total quantity, the program calculate what the percent of the total is the item. For example, if the item quantity is your rent and the total quantity your monthly income, then the program computes what percent of your income goes to rent.

Using Javascript with Forms - Percent calculator
CodeOutput
<form name="form1">
Item quantity: <input type="text" name="Iqty" />
Total quantity: <input type="text" name="Tqty" />
Percent = <input type="text" name="Perc" readonly />
<button onclick = "document.form1.Perc.value=document.form1.Iqty.value / document.form1.Tqty.value * 100 + '%'; return false">Calculate Percent</button> <input type="reset">
Item quantity:
Total quantity:
Percent =

First off, we used five form elements, three text type inputs and two buttons, with names assigned to the form itself as well as to the form elements that require a name. Now, in Javascript, the value of a form element is accessed by takig a path to the form element as document.form1.Iqty.value. What this means is "within this document find a form named form1, then inside that form find a form element named Iqty, and get or modify the value (content) this form element."

So, what the script inside the onclick does is: divide what the user entered inside the 'Iqty' element by what he/she entered in the 'Tqty' element, multiply by 100, concatenate with the string "%", and put the result in the 'Perc' element. The last statement, 'return false' is just to please some stupid browsers such as Firefox, and it is not part of the program we are dealing with here.

Note that we added a reset button just to show its application -- it clears all values. Also, we added 'readonly' attribute to the 'Perc' element since no input should be entered there.

TOP

Introduction to Javascript Functions

Let us modify the onclick part of the above example as follows.

onclick = "document.form1.Perc.value = calcPercent(document.form1.Iqty.value, document.form1.Tqty.value) + '%';

We are sending two arguments, namely, the item quantity and the total quantity values, to a percent calculator function called calcPercent, and using the returned value to be entered into the 'Perc' element. Indeed, we don't have such a function yet, so we have to create it (define it).

A Javascript function is an independent program, with some name, that performs specific operations and returns a result. A function is normally placed in the <head>...</head> section of the document and has the folloing format.

function function-name(arguments) {
  function operations with at least one return statement
}

Thus, our pecentage calculator function would be,

function calcPercent(a,b) {
  return (a / b * 100);
}

You can give any name to a function, we named ours calcPercent, it may take 0 or more arguments, ours takes two. The most important purpose of creating a function is that you don't have to repeat the same operation over and over again. For instance, if you need to calculate percentage at different parts of your program, or if you need to do so in any other of your documents, all you have to do is call your function by the statement calcPercent(x,y). Note that the arguments sent to the function depend on your program, in our example, they were the values entered in the form elements, in other programs they can be like (x,y) or (malePopulation, totalPopulation), and so on.

Pre-defined functions

There are some operations, especially mathematical, that are so frequently used that every programming language has to integrate pre-defined functions for them. Examples are logarithm, square root, sine, cosine,tangent, etc. Javascript's functions for maths have Math. prefix. For example, Math.sin(x) computes and returns the sine of the angle x given in radians. One such function that we can use in our example program is Math.round(); it rounds a number to the nearest integer. So, if you don't want all the long digits after the decimal point, you can re-write the statement as

onclick = "document.form1.Perc.value = Math.round( calcPercent(document.form1.Iqty.value, document.form1.Tqty.value) ) + '%';

This gives the result a better look, but all results less than 1% will be displayed as 0%. Don't place Math.round() in the calcPerc() function; it will work fine, but the function will loose its generality and precision when the result is used in other computations.

TOP

Introduction to Javascript Conditional Statements

Conditional statements are a group of statements that will be executed if only certain conditions are satisfied. In order to write conditional statements, we need to know how the conditions themselves are specified.

Conditions are stated by means of logical expressions, which evaluate to either true or false. The expression (x > 0) is a logical expression and evaluate to true if the variable x has a positive number stored in it; otherwise, it evaluates to false. The 'greater than' ( > ) symbol is called a logical operator. Other common logical oerators are >= (greater than or equal to), < (less than), <= (less than or equal to), == (equal to), != (not equal to), && (logical AND), || (logical OR)

A common Javascript Conditional Statement is formed if and has the following form,

if ( condition ) statements to be executed if condition evaluates to true

Example, to alert the user if she/he entered a negative number:
if( document.form1.Iqty.value <= 0 ) alert("Invalid number")

You can also add statments to be executed otherwise, that is, if the condition evaluates to true. This is done by adding else. The syntax`is,

if ( condition ) statements for true; else statements for false;

Example, to prevent division by zero:
if( y == 0 )
alert("Denominator cannot be zero");
else
alert("x / y = " + x/y);

Note that as long as you don't carry "open quotations" to the next line, you can write statements in new lines. If multiple statements are to be executed, include the group inside { }. As a matter of fact, a good practice is to use the curly brackets whether they are required or not. And use a little indentation too. The following and the above are exactly the same, but this one is more readable.
if( y == 0 ) {
  alert("Denominator cannot be zero");
}
else {
  alert("x / y = " + x/y);
}

TOP

Introduction to Javascript Loops

Looping is a repeated execution of the same statements by varying the contol variable. The most common looping is done by the for loop, however, while loop is quite useful too.

Let's see the for loop with help of an example. We want to compute the square roots of integers from 0 to 5

for( i = 0; i<=5; i++ ) alert("Root of " + i + " is " + Math.sqrt(i))

The variable 'i' is called the control variable, you can use any variable. i=0 is the initial value of i, if you want to start from 2, just make it i=2. i<=5 means that the loop is to continue as long as i is less than or equal to 5. i++ means increase i by 1 after each loop. You may copy this line and paste it in the alert interactive execise to see it in action.

Now, let's seethe same program by using while loop.

i = 0;
while( i<=5 )  {
  alert("Root of " + i + " is " + Math.sqrt(i));
  i++
}

In this case, the initialization is done before the loop. Also, an incrementing statement must be included inside the loop; otherwise, the loop continues forever and your computer gets stuck. Since we have two statements inside the loop, we must use the curly braces.

There still another loopin mechanism called the do..while loop.

i = 0;
do
{

  alert("Root of " + i + " is " + Math.sqrt(i));
  i++
}
while( i<=5 )

TOP

Javascript in conjunction with styles can be effectively used to make web pages dynamic and interactive. This technique is known as DHTML and will be the our next subject.

 

Send This SITE To A Friend   |  Add to favorites   |  Terms of service   |  Privacy statement   |  Contact us
Copyright © 2009-2012 HTMLStarter.com