mercredi 24 juillet 2013

JavaScript Confirm box

JavaScript Confirm is also a type of a popup box. It is used to ask user to confirm a certain requested action. If user confirms it, the browser proceeds and performs that action.

For example you ask the Browser to delete a picture from your facebook profile. A confirm box will pop up asking you to confirm the action "Are you sure to delete the file?", You can proceed by pressing OK Button or Cancel if you mistakently pressed the delete button or just changed your mind.
Syntax

confirm("message");
Example 1

In the example below, we are displaying a warning message to the user. If she chooses ok, she will be redirected to the main page, however she can also choose to click cancel.

We can later add more functionality to the script below using the If statement, to redirect those who click 'OK' to the site's main page, while do not load the page for those who choose to cancel. However since this lesson is part of Javascript basics, we only explain the basic use of confirm box here. We will deal with the IF part in later lessons on Conditional statements.

javascript confirm box

In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it jsconfirm. This function will launch the confirm box whenever it is called.

We also programmed the button to call the function jsconfirm whenever the button is pressed(the button press event captured using Onclick event handler).
You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS Confirm Box</title>

<script type="text/javascript">
function jsconfirm()
{
confirm("Warning! The Content of this site may be disturbing to some viewers" + '\n' + "Viewer Discretion Is Advised");
}
</script>
</head>

<body>
<p>Click Here to Enter the site</p>

<input type="button" onclick="jsconfirm()" value="Enter Site" />
</body>
</html>
Result

When the button is pressed, the popup box will appear.

js confirm

NOTE: After you press ok, nothing will happen, because as mentioned above, in this example we are not telling the browser about what to do with the input taken.

PopUp Box Message Line Break '\n'

If the message is too lengthy, it will be put into the next line, however we can also enter a line break '\n' to manually enter a line break in the popup window message as in the example above.
JavaScript Confirm and the Boolean Values (Advance topic)

This part of the lesson explains a slightly advanced topic and also makes use of the conditional statements. If you are taking this course step by step from the beginning, you can skip this part and maybe later refer to it after we have covered the conditional statements.

In JavaScript a confirm OK pressed is equal to a boolean 1 or 'TRUE' and a confirm Cancel is equal to a boolean 'False'.
Example

In the example below, we will use the Confirm command as a condition in a Conditional statement. So if OK is pressed it will mean that the condition has been met OR is true.

js confirm code

We did not mention any event with the confirm command, so the confirm box will pop up with page load.

Javascript confirm conditional

If the condition is true, i.e. OK has been pressed in the confirm popup box, it will execute the command in the brackets. It will pop up an alert

js confirm boolean true

If the condition is False, i.e. Cancel has been pressed in the confirm popup box, it will execute the command in the brackets after the ELSE. It will pop up a different alert as specified in the code.

js confirm boolean false

JavaScript Prompt box /Window

JavaScript Prompt is also a type of a popup box. It is used to ask(prompt) user for certain input, which then javascript uses for certain operations and decision making. For example, ask visitor to enter age, before she can be allowed to enter a site which is restricted for those under 13. Syntax prompt ("message", "default value"); Example 1 In the example below, we are prompting the visitor to enter her age. We can later add more functionality to the script below using the If statement, to redirect those above 13 to the site's main page, while deny entrance to those under 13. However since this lesson is part of Javascript basics, we only explain the use of the prompt box to take input, what we later do with that input, is a part of later lessons. js prompt In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it jsprompt. This function will launch the JS Prompt box whenever it is called. We also programmed the button to call the function jsprompt whenever the button is pressed(the button press event captured using Onclick event handler). You can Copy Paste the code below into a new html file. JS PopUp Boxes

Clicking the Button below will launch an alert box.

Result When the button is pressed, the popup box will appear. Here we chose the click button event to launch the box, we can also program to launch the prompt box on any other event, like simple page load. javascript prompt window NOTE: After you press ok, nothing will happen, because as mentioned above, in this example we are not telling the browser about what to do with the input taken. Example 2- Making use of the input value In this example, we will use a simple code to work with the input taken. prompt user 1. We defined a function called jsprompt2. This function not only makes use of the prompt command to ask for input, but will also assign the input value to a variable called visitorname. 2. Then the function will display the customized welcome message on the screen with the value of the variable we named visitorname(the value user entered in the prompt). 3. We placed a button on the page and programmed it to call the function jsprompt whenever the button is pressed(the button press event captured using onclick). Result When Ok is pressed. prompt result NOTE: In this example, we also mentioned a default Value for the prompt box input, so when the box pops up, by default the value 'Visitor' is already there. User can click in the box and enter her own name however. You can Copy Paste the code below into a new html file. JS Prompt Box

Plz Click the Button and enter your name

Example 3- Another example of the JavaScript PopUp box making use of Loops is presented at a later lesson at- JavaScript For Loops

JavaScript Alerts PopUp Box

Alert is a way of passing on some information to the page user/visitor OR simply it alerts the user about a certain event. Event like Page load, button click, form submit, clicked inside a field etc. See JavaScript Events for more.

The Alert command launches a PopUp box containing some text message for the visitor. The user is required to acknowledge the receipt of information usually by pressing a 'OK' button that appears in the box.
Syntax

Alert ("message");

Example

javascript alert box

In the example above, we put a Button on a simple web page. Besides we defined a function in the head section of the page, and named it js_alert. This function will launch the alert box whenever it is called.

We also programmed the button to call the function js_alert whenever the button is pressed(the button press event captured using Onclick event handler).
You can Copy Paste the code below into a new html file.

<html>
<head>
<title>JS PopUp Boxes</title>
<script type="text/javascript">

function js_alert()
{
alert("This is your first alert box");
}

</script>
</head>

<body>
<p>Clicking the Button below will launch an alert box.</p>

<input type="button" onclick="js_alert()" value="Launch Alert Box" />

</body>
</html>


Result

alert box in chrome

Note that the alert box appears as a separate small size window in Chrome browser.

JavaScript PopUp Boxes / Windows

What is a PopUp Box/ window?

A PopUp box is a small message box window that appears(pops up) in your browser in response to a certain Event like Page load, button click, form submit, clicked inside a field etc. See JavaScript Events for more.

The main types of Javascript popup boxes

    Alert Box- Give some info to user
    Prompt Box - Ask user to input some value like name, age etc.
    Confirm Box- Confirm before proceeding with a request ex- delete a file.

Popup boxes appear differently in different browsers.
PopUp Box as it appears in FireFox

In Mozilla Firefox 5.0, the JavaScript Popup box appears in the center of page. But unlike IE and Chrome, the box does not appear as a separate movable window. you cannot click and drag it across the screen.

JS popup box firefox
JS PopUp Box Appears in Internet Explorer 8

You can click and hold down the mouse key as shown in the screenshot below and drag the popup window across the screen.

javascript popus in internet explorer

Note the Yellow symbol, that is an IE 8 symbol for Alerts.

JavaScript PopUp Box / Window Appears in Google Chrome

alert box in chrome
PopUp Boxes Sytntax

We will deal with practical examples of popup windows in the next lesson, however the general syntax is

command name ("text message");
PopUp Box Message Line Break

If the message is too lengthy, it will be put into the next line, however we can also enter a line break '\n' to manually enter a line break in the popup window message. Example in Lesson on JS Confirm box

Syntax- Defining Function in Javascript

There are certain elements that need to be defined for a function to work.
Syntax

function nameoffunction (var1, var2 ...........)
{
Code to be executed
}
Lets look at each of those parts

    First comes the reserve word 'function' .this is to tell the interpreter/browser that we are defining a function and the following code is part of this function. NOTE : If you recall lessons on basics- javascript is a case sensitive language, so writing it Function or FUNCTION will cause errors.
    Give the function a name ex. 'myresults' or any other suitable name that also gives some meaning to the purpose of the function i.e. the task it performs.
    Variables- values of these variables are generally provided by the user on the page where function is called.
    Curly Braces { } to mark the start and end of the executable code.
    Code- Instructions on what to do with those variable values and how to display the results.

Example- JS Function

Functions are used in a variety of places in the website, most commonly with JS events. We will study events in detail in later lessons. First, lets look at a simpler example.

Step 1- Declare the function

We declared a function and named it 'contact'. This contains our lenghty contact info, we wish to display it multiple times on our page. NOTE- the example is to explain the concept to you in simple terms.(Real world application- you wish to display the info at end of every page- function kept in external JS file

declaring a Javascript function

    We declared a funciton in the head section of the page and named it 'contact'.
    No variables were required for this simple operation, so the ( ) are empty.
    In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
    Where the function is called, javascript write a message on screen.

Step 2- Call the Function

Call the function by its name where it is required.

calling javascript function

    We wished to call the function in the body tag, where we wanted it to display the contact info.
    Then we called the function again, no repitition of the lenghty message.

Result

function result


Example 2- Defining Function and using with Events

This is the most common use of functions. The function is called to execute its code, when a certain event occurs. Like when you click the buttons in the example below, it will display a JS Confirm message.

Step 1- Declare the function

declare function

    We declared a funciton in the head section of the page and named it 'welcome'.
    No variables were required for this simple operation, so the ( ) are empty.
    In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
    When the function is called, javascript should popup a 'Confirm Box' displaying a particular message.

Step 2- Call the Function

Call the function by its name where it is required.



js calling function

    We created some form buttons within the body and associated a mouse event with them.
    Whenever these buttons are clicked (JS onclick event), browser should run the function called 'welcome'.

Note- in the example above, we have used the function thrice while the code is written in the head section of the page only once. This saves repitition and enforces consistency.

What is a Function in JS ?

A function is a block of code that performs a certain specialized task. The benefit is that instead of writing that code over and over again on every web page it is needed, you can simply refer to that block of code(function) and instruct it to perform the task.

For example- sometimes you need to count the number of spaces in paragraphs, and programming is needed to calculate that. There are three ways to achieve this objective

Method # 1 -Write the coding yourself and paste the whole code, everywhere it is required. Lot of repitition.

Method # 2- Write the coding yourself, give that block of code a name and place it in a separate file. Now on any page it is required, call it by its name to perform the required task.

Method # 3- If available, Use a predefined function, those created by others or come pre-loaded with the programming language or software. Have you Noticed the 'Word Count' feature in Microsoft Word? every time you use that, at the backend a function is called.

You will come across many pre built functions in JS and other programming languages. For examples, string functions for calculating lenght of a word.

Example of a mathematical function-A Mathematical Function for calculating power of a number. 8 ^ 3 is the simple instruction you will give, at the backend code will be 8 x 8 x 8 and there will be instructions in the function on how to display result on screen. like instead of simple dispalying result 512, it can be programmed to output 'The answer to your question is 512 my liege!"
Basic Function Types

    Built-in Functions- preloaded in javascript interpreters, you don't need to define them.
    User defined functions- Ones you can specify by encapsulating some code in a block and giving that block a name.

Our main focus in this chapter will be Custom/User defined Functions

JavaScript OnClick Event

This event handler is used to instruct the browser on What action to take when a certain object is clicked.

If the concept of events is new to you, it is recommened that you first see lesson on What are Javascript events
Syntax

onclick="functionname( )"

The name of function that has to be called when this event occurs.
NOTE: Simple Js code can also be written here instead of calling function, but standard practice with events is to use them with functions.

Step 1- Declare the function

declare function

    We declared a funciton in the head section of the page and named it 'welcome'.
    No variables were required for this simple operation, so the ( ) are empty.
    In the Curly Braces, we wrote instructions on what to do when the function is called by its name from anywhere in the page.
    When the function is called, javascript should popup a 'Confirm Box' displaying a particular message.

Step 2- Call the Function

Call the function by its name where it is required.



js calling function

    We created some form buttons within the body and associated a mouse OnClick event with them.
    Whenever these buttons are clicked, browser will detect the event and run the function called 'welcome'.

JavaScript OnMouseout Event

This event handler is used to instruct the browser on What action to take when mouse cursor is moved away from an object on the page. It is generally used in combination with OnMouseover Event which we studied in the previos lesson.

If the concept of events is new to you, it is recommened that you first see lesson on What are Javascript events
Syntax

onmouseout="functionname( )"

The name of function that has to be called when this event occurs.
NOTE: Simple Js code can also be written here instead of calling function, but standard practice with events is to use them with functions.
Example

In this example, we have an image. When mouse is moved over the image, it will be replaced by another image (done using mouse over event). Now When the mouse moves out, it will replaced with yet another image- this part will be handled by the OnMouseOut event handler.

javascript image
Code Used and Explanation

JS mouse out event handler

    We have an image named 'js_image.jpg'. It has two event handlers. OnMouseover to replace it with one image when mouse is moved over it. And onmouseout event handler to change image back to the previos one when mouse is moved away from the image.
    We instructed in the attribute that when the onmouseout event activity is detected on this image, the browser should call the function called mouseoutlesson()
    We also assigned an ID to the element i.e. the image.

Now the Function explained

    We declared a function and named it 'mouseoutlesson'
    What that function does is, it locates the element having the ID 'samp'
    With the element located, it finds its attribute 'src' and changes its value back to 'images/js_image.jpg"

Note-The value of this attribute when the page loaded was 'images/js_image.jpg'. On mouse over, a function is executed, the value changes and thus a different image appears on the page. On Mouse OUt, another function is called and the value again changes as we instructed in the function.

JavaScript OnMouseover Event

This event handler is used to instruct the browser on What action to take when mouse cursor is moved over an object on the page.

If the concept of events is new to you, it is recommened that you first see lesson on What are Javascript events
Syntax

onmouseover="functionname( )"

The name of function that has to be called when this event occurs.
NOTE: Simple Js code can also be written here instead of calling function, but standard practice with events is to use them with functions.
Example

In this example, we have an image. When mouse is moved over the image, it will be replaced by another image. This has been done using JS Onmouseover event handler.

javascript image
Code Used and Explanation

code used in mouse over event handler

    We have an image named 'js_image.jpg' within the body of our page.
    We inserted a onmouseover event handler along with its attributes.
    We instructed in the attribute that when the onmouseover event activity is detected on this image, the browser should call the function called mouselesson()
    We also assigned an ID to the element i.e. the image.

Now the Function explained

    We declared a function and named it 'mouselesson'
    What that function does is, it locates the element having the ID 'samp'
    With the element located, it finds its attribute 'src' and changes its value to 'images/javascript_mouse_over.jpg"

Note-The value of this attribute when the page loaded was 'images/js_image.jpg'. When the function is executed, the value changes and thus a different image appears on the page.

How to change the image back when the mouse leaves it ? For that we will use another event handler called OnMouseOut.

JavaScript Mouse Events

JS Mouse events are those associated with some mouse activity by user. The programmer can tell the browser what to do when that event occurs.

Events are captured and subsequent actions defined using JavaScript Functions. If you do not have a concept of what functions are, it is recommended that you first take a look at lesson on JavaScript Functions - Click Here
JS OnMouseOver Event

The event occurs when mouse is pointer is moved over a certain object (to which the onmouseover command has been applied).

Example

javascript image
JS OnMouseOut Event


JS OnMouseDown Event


JS OnMouseUp Event


JS OnMouseMove Event

JavaScript Events

What is a Javascript Event?

An event is an action or a happening that browser can detect. For example a button placed on a webpage is clicked, some text is selected, pressing a keyboard button, mouse pointer is moved over to a picture. Whenever these and such other actions occur, Javascript code in the browser is able to detect the event and thus the proceeding action can be programmed- i.e. javascript programmer can tell the browser about what to do when a certain event occurs.

Generally events refer to some action by the user/visitor of the webpage however loading of a picture on a webpage or loading of a new webpage are also happenings that browsers recognize as events.

The actions to proceed the event are usually coded in the form of functions(will study them later in this course). A simple intro to a function is that it is a block of code lines that perform a specific task/function. A single function can be used on many pages throughout the site.

JS Events and Browser Compatibility issues


List of JavaScript Events

There are many types of javascript events. We will cover most of them in this course.

    JavaScript Mouse Events

        OnMouseOver
        OnMouseOut
        OnMouseMove
        OnMouseup
        OnMousedown

    JavaScript Mouse Click Events

        Onclick
        Ondblclick
        Oncontextmenu - (right click)

    JavaScript Keyboard Events
        OnKeydown
        OnKeypress
        OnKeyup

    Form and Field Events

        OnClick
        OnSelect
        OnSubmit
        OnBlur
        OnFocus
        OnChange
        OnReset

    Window Events

        OnError- When an error occurs in loading of page or elements within it.
        Onload- When a page is loaded
        OnUnload- When a user leaves or closes a page
        OnAbort
        OnBlur
        OnScroll
        OnFocus
        OnMove
        OnResize

We will look at examples of each one of the frequently used events mentioned above in the coming lessons.

IMPORTANT NOTE: We have mentioned all the events generally used. However if you are a beginner, you might find all this information on JS events overwhelming. In that case, you can study only the most generally used events.
List of Most Frequently used JS Events

    Onsubmit
    Onclick
    OnMouseOver

JavaScript Switch

It performs the same function as the else if statement in the last lesson. It basically deals with multiple scenarios and tests various conditions.

A condition in a switch statement is refered to as a CASE. If case is true-execute a block of code, if it is False see if any other case is true. If any other case is true, execute a block of code, repeat the process until find a true case / condition.

If none of the cases mentioned are true, will tell the browser what to do by using simply DEFAULT. default performs the same function as else.

JavaScript Else If statement

It tells the computer of actions to take in multiple possible scenarios (more than two). i.e. What to do if condition is true, if it is False see if any other condition is true. If another condition is true, execute a block of code, repeat the process until find a true condition.

If none of the conditions mentioned are true, will tell the browser what to do by using simply ELSE.
Else If statement SYNTAX

if (Condition)
{
Block of code to be executed, if condition is True
}

else if
{
Block of code to be executed, if condition is True
}

else if
{
Block of code to be executed, if condition is True
}

else
{
Block of code to be executed, if condition is True
}

If a condition is TRUE, the code is executed and the browser skips the ELSE part moves to the next line in the HTML document.

If the condition is FALSE, then it moves to see if any other condition is true and execute its code

If all conditions are False, the code in the else block is executed.

Example
We have a site for displaying semester results of students when they log in to the site.

Possible Scenarios

    Passed
    Failed
    Absent
    Any other problem due to which result could not be displayed.

if (status = passed)
{
"Congratulations, you have passed and been promoted to the next level "
}

else if (status = failed)
{
"Sorry. You failed the exam. Contact the administration department for further info"
}

else if (status = absent)
{
"Sorry. You did not appear in the exam. Contact the administration for the retake procedure"
}

else
{
"There was an unspecified error with your result. Contact the administration to sort it out and obtain your result"
}

NOTE: IF Else is genearlly used when there are two possible scenarios. Either condition can be TRUE and if it is FALSE there is only one alternate scenario. What if the person has not passed, but the alternate scenarios are either "Failed" or "Did not appear". To handle that we use IF ELSE .... IF ELSE which we will see in next lesson.

JavaScript Else statement

It tells the computer of actions to take in both the scenarios. i.e. What to do if condition is true and what to do if it is False. If a certain condition is true, execute a block of code, if false- execute another block of code mentioned.

IF Else is genearlly used when there are two possible scenarios. Either condition can be TRUE and if it is FALSE there is only one alternate scenario. Example below will clarify it, and also see the note below.
If statement SYNTAX

If (Condition)

{
Block of code to be executed, if condition is True
}

Else

{
Block of code to be executed, if condition is True
}

If the condition however is TRUE the code is executed and the browser skips the ELSE part moves to the next line in the HTML document.

If the condition is FALSE, then it executes the block of code in the ELSE part and then moves to the next lines in the html document.

Example
We have a site for displaying semester results of students when they log in to the site. What instructions to give to the student incase she has passed and what in other scenarios.

Possible Scenarios

    Passed
    Failed

If (status = passed)
{
"Congratulations, you have passed and been promoted to the next level "
}

Else
{
"Sorry. You could not pass the exam. Contact the administration department for further info"
}

NOTE: IF Else is genearlly used when there are two possible scenarios. Either condition can be TRUE and if it is FALSE there is only one alternate scenario. What if the person has not passed, but the alternate scenarios are either "Failed" or "Did not appear". To handle that we use ELSE Ifwhich we will see in next lesson.

JavaScript If statement

This statement is simply used to tell the computer 'What to do in case of a certain situation". If a certain condition is true, execute a block of code. By 'condition being TRUE' it is meant that the mentioned condition is being met.
if statement SYNTAX

if (Condition)

{
Block of code to be executed, if condition is True
}

LOWER CASE???

If the condition however is TRUE the code is executed and the browser moves to the next line in the HTML document.

If the condition is FALSE, then it simply moves to the next lines



Example
We looked at a simple example in the previous lesson. we will now write that example in JavaScript code.

If (gender = male)

JavaScript Conditional Statements

In programming, we often need to give computer the intelligence to take decisions in different situtations. If a certain condition is met, perform an action, if another condition is met perform the another specified operation. These are referred to as conditional statements-example below will clarify it.

Example
When customers come to our fashion website, they have to enter name and select Gender. Based on the Gender information receive, through programming we give computer the intelligence to decide whether to Greet the Visitor as Madam or Sir.

Condition 1- Gender = Male
Condition 2- Gender = Female

How we program it into the computer

We tell the computer the list of Conditions and the actions to perform if a condition is met.

IF Gender is male , greet the visitor as 'Dear Sir. Welcome to the site'
IF Gender is female, greet the visitor as 'Dear Madam. Welcome to the site'

The thing is we cannot have a person sitting with a computer and everytime someone visits the site, the operator types in the Dear sir greeting or Dear madam greeting Programming lets us automate such operations. Computer decides and computer types the greeting.
Conditional statements used in JavaScript

We will be covering the following conditional statements used in JavaScript

    If statement
    If else statement
    If else ... If else statements
    Switch statement

We will look at each one of these in detail and with practical examples in the coming lessons.

Conditional Statements table. Differences

Javascript Array

Array is a special kind of variable that can hold multiple values. If you recall the lesson on JS variables, we explained that variable is a container of a value.

Lets use analogy of a box. A simple variable is a box that holds one item like box containing a large chocolate cake. Now imagine array as a box that has many subdivisions and each compartment has a pastry of a different flavor.

    Box compartment 1 holds value = strawberry flavor
    Compartment 2 value= Vanilla and so on

Practically Array is many variables within one.
Why do we need Javascript Arrays / Advantages of using Arrays

    When we have to loop through many variables, it is much simpler to reference sub container id (usually called index) numbers instead of individual variable names. For example- looping through marks of students to check the highest score. Either write individual variable names OR array name 'student' and id 1 to 50. easier to loop through digits 1 to 50 than text names.
    All the data in the array is of same type like text, numerical etc. so it is easier to work with.

Syntax Define / Create Array- Method 1

First create an array, then assign values to its individual indexes.

var arrayname = new Array ();
arrayname[0] = "value";
arrayname[1] = "value";
arrayname[2] = "value";
arrayname[3] = "value"; And so on

Notice that the subcontainer IDs start from 0
Example

js array

Notice how we referred to the 3rd index the array using the document.write command to display it on browser screen.
Syntax Create Array- Method 2

Create an array and assign value in the same statement / command

var arrayname = new Array("value", "value", "value");
Example

javascript define array example

Both Methods are valid. Use the one you find easier and faster.

JavaScript Variable Types by Scope

Another way variables are classified in Javascript are by Scope. i.e. whether the variable is usable only within a function or throughout the whole page.

The two types are

    Local Variable
    Global Variable

Local Variable

A local variable is one that is declared / Created within a function in Javascript. It is usable only within that function, in other words has a local scope. Such variables are deleted, once the function has been executed.
Global Variable

All the variables that are not declared within a function are called Global variables. Can be used anywhere throughout the page and any function or other code can alter its value i.e. they have a global scope.

JavaScript While Loop

In JavaScript, WHILE loop has same function as the FOR loop. The Syntax however is bit different. The WHILE Loop will check if a condition is being met, if yes then it will execute the code lines specified within the Brackets, else it will stop the looping process.

The counter variable must be incremented within the code lines to enable the while command to work properly. Unlike the FOR loop, the syntax does not provide a special spot for specifying the increment.

The initial value of the variable must also be specified before the While command.
Syntax

While(Condition)
{
code lines to be executed
}
Simple JavaScript While Loop Example

We will use the same example as used in the last lesson. Here we will achieve the same objective with While Loop instead of the FOR loop. It will help you easily compare both.

Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results.
Js While Loop

Step 1- We declared a variable called 'a' and assigned it a value of 5.
Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run.
Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below.
Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter.
Step 5- After printing it will increment the value of variable counter and then go back to top of the loop command. Note that unlike the For Loop example in the last lesson, we enter the increment code within the code to be executed.
STEP 6- When the counter variable value becomes 11 and the loop goes back to top, the condition becomes FALSE as 11 is neither 10 nor less than it. So the loop will no longer be executed.

First time the code is executed, 5 x 1 and the result is a *5 which is five.

Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10.

While loop result


Example-
Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants

Much similar to the example above. Just that here we will ask the user to enter a number through a Prompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example.

Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a.


javascript while loop

Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2.
Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops.
Result

A popup box will prompt the user to enter a number.

popup box JS for loops

JavaScript For Loop

The JavaScript FOR loop is the simplest and most frequently used looping command. It simply executes a block of code until a certain condition is met. On every cycle/loop, it will first check if the specified condition is true, if yes then it will execute the block of code within the curly brackets. Syntax For (Counter variable name and initial value ; Condition ; Increment;) { code lines to be executed } Initial value of the counter variable- Starting value. Condition- to keep looping until the condition is true OR in other words stop as soon as condition gets False. Increment- How to increment the value of counter variable on every loop. Simple JavaScript For Loop Example Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results. javascript for loop example Step 1- We declared a variable called 'a' and assigned it a value of 5. Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run. Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below. Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter. First time the code is executed, 5 x 1 and the result is a *5 which is five. Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10. for loop result Example- Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants Much similar to the example above. Just that here we will ask the user to enter a number through a Prompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example. Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a. advance for loop Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2. Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops. Result A popup box will prompt the user to enter a number. popup box JS for loops

JavaScript While Loop

In JavaScript, WHILE loop has same function as the FOR loop. The Syntax however is bit different. The WHILE Loop will check if a condition is being met, if yes then it will execute the code lines specified within the Brackets, else it will stop the looping process. The counter variable must be incremented within the code lines to enable the while command to work properly. Unlike the FOR loop, the syntax does not provide a special spot for specifying the increment. The initial value of the variable must also be specified before the While command. Syntax While(Condition) { code lines to be executed } Simple JavaScript While Loop Example We will use the same example as used in the last lesson. Here we will achieve the same objective with While Loop instead of the FOR loop. It will help you easily compare both. Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results. Js While Loop Step 1- We declared a variable called 'a' and assigned it a value of 5. Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run. Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below. Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter. Step 5- After printing it will increment the value of variable counter and then go back to top of the loop command. Note that unlike the For Loop example in the last lesson, we enter the increment code within the code to be executed. STEP 6- When the counter variable value becomes 11 and the loop goes back to top, the condition becomes FALSE as 11 is neither 10 nor less than it. So the loop will no longer be executed. First time the code is executed, 5 x 1 and the result is a *5 which is five. Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10. While loop result Example- Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants Much similar to the example above. Just that here we will ask the user to enter a number through a Prompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example. Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a. javascript while loop Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2. Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops. Result A popup box will prompt the user to enter a number. popup box JS for loops table result for Javascript for loop

JavaScript Variable Types by Scope

Another way variables are classified in Javascript are by Scope. i.e. whether the variable is usable only within a function or throughout the whole page.

The two types are

    Local Variable
    Global Variable

Local Variable

A local variable is one that is declared / Created within a function in Javascript. It is usable only within that function, in other words has a local scope. Such variables are deleted, once the function has been executed.
Global Variable

All the variables that are not declared within a function are called Global variables. Can be used anywhere throughout the page and any function or other code can alter its value i.e. they have a global scope.

JavaScript Variables naming Conventions

In javascript programming, it is useful to give meaningful variable names that are easier to remember, recall and understand. Instead of calling the variable that holds country names 'x', we called it 'countryname', this helps in better programming as when working with thousand of lines of codes, you will forget what x refered to. but the word countryname will tell you what the variable actually holds.
Basic Rules

    It can contain letters, numbers and some symbols.
    First character of the variable name should be a letter or an underscore. It cannot start with a number.

What cannot be used as Variable names

    Javascript reserved words like var, with , .. etc that are used by javascript as commands
    Variables names cannot contain blank spaces. if you want to separate words in a variable name, used Underscore '_' Ex. 'student_age'
    Ampersand & or the Percent sign % cannot be used.
    Variable name cannot start with a number however in later characters(after first one), numbers can be used.

Case Sensitivity
In javascript variable names are case sensitive. Variable names 'studentage', 'Studentage' and 'STUDENTAGE' are considered different variables. Although the letters are same but the case is different in all the three names.
Hungarian notation
JavaScript tutorials

Advance user concept- (you can skip this Paragraph if you want to).
Although variable types are not declared in javascript, it is good programming practice to add a prefix to the variable name describing the type of data you wish to assign with the data. For example, variable studentage will be assigned a numeric value. So we might want to name it num_studentage

a Variable student name that will hold string(text) data might be called str_studentname

JavaScript Variables

Variables are an important concept of computer programming in general.
What are Variables?

If you recall school algebra, there were 'x' and 'y'. Sometimes x had a value of 1, you could add 2 to the value of x and then its value became 3. Thus the value of the letter x varied or changed over time. Though back in school it did not make much sense to why we were using X and Y, why all that much algebra? what was the use? Well in programming you will find them to be very useful.


Simply put, a variable is a container of a value. This container has a name, that we call 'variable name' A variable is represented by a letter like 'x' or any other variable name like combination of letters ex 'customername'. Its value can vary.

Imagine an empty box. If you put carrots in it, it is a box of carrots. At another time it may contain potatoes and then it is a box of potatoes. The contents of the box changes or varies at different instances of time. This box or container has a name like 'smallbox'.
Variables in Programming

In Programming, Variables can hold values or expressions(combination of values and variables joined by operators like +, - , etc). Values can be numbers, text and many other kinds of values.

Example customername = 'Jessica', employeesalary = 60,000
The variable customername has a text value containing customer name, while the variable employeesalary has a numeric value of 60,000.

monthlysalary = employeesalary / 12
The value of the variable monthly salary has a value in the form of an expression. divide employeesalary by 12 (no. of months) and you will get the value for this variable.
Why do we use Variables

We use variables to store data. When we need to use that data in calculations or other purposes, we can refer to the data by referring to its container(variable name) instead of writing the data values themselves. In other words variables represent data.
For example

On top right section of every page of our company website we need to display the total number of Desktop Computers we have sold to date. One way to do it is to change the value of total sales every morning on every page of the website. The other way is to refer to the variable 'Total sales' on every page and update the value of the variable 'total sales' in the system memory, and every webpage thus automatically displays the current value of the Total sales by extracting the information from the main system memory.

If you are still not fully clear about variables, don't worry. You will better understand their use as use them in examples in the lessons ahead. Above description is sufficient foundation knowledge and you can move on.
Declaring a Variable in Javascript

To Create / Declare variables in Javascript, we use the var command.

SYNTAX

var variable_name;

There are two ways to declare a variable.

1. Just declare a variable (assign it a value later)
var countryname; This will create a variable called 'countryname' without assigning value to it.

2.Declare a Variable and also assign value to it.
var countryname = "Australia";


JavaScript in External file. Link JS to HTML

As noted in the previous lesson, Javascript can also be put into an external file and the Html page that we wish to use the Javascript code on, is linked to that external file.

It works in a similar way as CSS code is put in External Style sheets.
Advantages of placing Javascript code in External File

    Security and Privacy- Competitors and Hackers cannot see the code. The external file can be blocked from public view.
    Reusability- The same code can be used on multiple pages and
    Easy Updating- In case of updating the JS code, it has to be done only in the external file instead of all the individual pages.

How to link the Javascript and Html files?
STEP 1- Create JavaScript external file

Create a new file, write in the Javascript code and SAVE AS it with .JS extension.

javascript external file

The external file will just contain the javascript code and not the html <script> </script> tags.

js code external

STEP 2- Link html to Javascript File
Use the Script tags, however instead writing in the code specify the location of the file that contains the code. Path of the file is defined with 'src'
In the example below the JS file was in the same folder as the html file. If folders are different, appropriate path needs to be defined.

<html>
<head>
<title> JavaScript in external file</title>

<script type="text/javascript" src=sample.js>

</script>
</head>
<body>

</body>
</html>


STEP 3- Load the html file which will call Javascript
Open the html file in a browser.

Result.
javascript html link result

Embedding JavaScript code in HTML documents

javaScript code can be included in simple html documents. To enable browser to differentiate between html and Javascript code, JS code is placed within script tags.

OPENING TAG <script type = "text/javascript">

Javascript commands go between these tags.

ENDING TAG </script>
Javascript in HTML Example

In this example we will use a very basic Javascript command called 'document.write' . This command is used to output/display some text, number, result or value of a variable on screen. For example, Browser calculates the price after 10% discount. In order to display that value on the screen, document.write command has to be used. We will however use a very simple output for this example.

<html>
<head>
<title> My first Javascript Page </title>

<script type="text/javascript">

document.write("Welcome to my first page");

</script>
</head>
<body>

</body>
</html>

In the example above, you can see how we can insert javascript within an html document. This simple document.write code will output/display the text on the screen of the browser.

NOTE: Some users prefer to put Javascript coding within the html <head> </head> tags , while some prefer body tags. You can place it in either location or also some code in head while other bit of code in the body.
Result- How to write Javascript in html

Here is how it will appear in the browser

Javascript code in html page

Apart from writing JAVASCRIPT in html documents, it can also be put it a separate file. 

Editor Software Required for JavaScript

Although javascript can be written simply in a notepad file, using an editing software helps in many ways like there are line numbers, error checking, different font color for javascript, css and html codes etc.
Adobe DreamWeaver CS5

The Professional Web development standard is the Adobe Dreamweaver, which supports various web scripting and programming languages including javascript, php, ASP and CSS. However Adobe Dreamweaver is pretty expensive and often students and beginners avoid buying it while in the learning phase. It typically costs $400 or above. To learn more about Dreamweaver. Official Dreamweaver site.
Komodo Edit- Open Source and FREE
An excellent alternate software for students and Freelancers is Komodo Edit. We strongly recommend using it instead of working simply on a windows notepad. Komodo Edit although Free and OpenSource is a powerful and efficient tool for coding in JavaScript.

STEP 1- Click on the link to go to Official Komodo site and download the software. Download Komodo Edit
The file size is about 43MB and will take 6-10 mins to download on a 1Mbps speed connection.

STEP 2- Go to the folder where you downloaded the file and click to run the setup and Install Komodo Edit on your PC.

komodo edit setup wizard

STEP 3- From file menu click New to start a new document

javascript editor new file