Learning JavaScript Basics from Scratch Functions, Loops and Events.
Welcome AJAX tutorials, today we will be learning the basics of JavaScript Functions loops and Events using Visual Studio 2010 and ASP.NET 4.0
Functions
JavaScript Function is nothing but it is a reusable code-block that is executed when the function is called. Function is defined in the head section of the code. The syntax of function is as follows:
function fname(prameter1,parameter2, …)
Example:
Loops
Javascript like any other programming language provides us with loops. Statements placed inside loops are executed a set number of times or even infinitely. We’ll first have a look at the for loop .
Here is the syntax of a for loop:
for (Initialization statements; Condition; Updation statements)
When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns ‘true’, the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns ‘false’ and the loop stops.
• The initialization statements are executed once; only when the for loop is encountered.
• After execution of initialization statements, the condition is evaluated.
• After every iteration, the updation statements are executed and then the condition is checked.
Example
alert(msg);
This will display digits 1 to 10 in a alert box
While Loop
The while loop is much simpler than the for loop. It consists of a condition and the statement block.
Here is the syntax for while loop
As long as the condition evaluates to ‘true’, the program execution will continues to loop through the statements. If the condition in while evaluates to ‘false’ at the very beginning, the loop is skipped altogether and program execution starts at the statement immediately following the loop.
Example
alert(msg);
This loop will display digits 1 to 10 in an alert box.
Do While Loop
The do-while loop is a modified version of the while loop. Here, the condition is placed at the end of the loop and hence, the loop is executed at least once.
Example
In the code above, the value of variable x is 20, hence the condition evaluates to ‘false’. However, the loop is executed once since the condition is presented at the end of the loop and not at the beginning.
Break and continue Statements For Loops
JavaScript provides commands through which iterations of a loop can be skipped or stopped. These commands are most commonly used along with an if statement inside the loop.
• continue: causes the iteration to be skipped
• break: causes the loop to stop and program execution to begin at the statement immediately following the loop.
Example
alert(msg);
This will display only the even numbers between 1 to 20, skipping the odd numbers. The condition in if checks for a remainder when variable x is divided by 2. Thus, for odd numbers, the condition will be ‘true’ and the loop will be skipped because of continue.
And break statement will stop the loop iteration process and execute the statements after.
Example
alert(msg);
Here the loop will exit when the value of variable t equal to 8. So this will display digits from 1 to 7.
JavaScript For…In Statement
The for…in statement loops through the properties of an object.
Syntax
Events & Event Handlers
• Every element on a web page has certain events which can trigger invocation of event handlers
• Attributes are inserted into HTML tags to define events and event handlers
Examples of events
We’ll see some basic functions and their examples
onload & onUnload Events
The onload and onUnload events are triggered when the user enters or leaves the page.
The onload event is often used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.
Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.
onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Example
Example Onblur
onMouseOver and onMouseOut
onMouseOver and onMouseOut are often used to create visual effects or animations on hovering around.
Example
When you pass the mouse cursor over the link above, the background color of the document is changed. And when you take the mouse out of the link, the background is changed to white which is the original in this context.
Examples.zip
Functions
JavaScript Function is nothing but it is a reusable code-block that is executed when the function is called. Function is defined in the head section of the code. The syntax of function is as follows:
function fname(prameter1,parameter2, …)
We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers, and they now offer cloud hosting!
While defining JavaScript functions it’s important to remember that the keyword function should be in lowercase otherwise JavaScript won’t understand it as function. If you write function in uppercase the code will generate error. In the JavaScript semicolon is optional but it’s better to put semi-colon as part of best practices. All the JavaScript code is written inside the curly braces. You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).Example:
Code Block
Default.aspx
<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello Have a nice day!") } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" > </form> </body> </html>
Loops
Javascript like any other programming language provides us with loops. Statements placed inside loops are executed a set number of times or even infinitely. We’ll first have a look at the for loop .
Here is the syntax of a for loop:
for (Initialization statements; Condition; Updation statements)
When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns ‘true’, the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns ‘false’ and the loop stops.
• The initialization statements are executed once; only when the for loop is encountered.
• After execution of initialization statements, the condition is evaluated.
• After every iteration, the updation statements are executed and then the condition is checked.
Example
Code Block
Default.aspx
var msg = ""; for (var x = 1; x <= 10; x++) { msg = msg + x + "\n"; }
This will display digits 1 to 10 in a alert box
While Loop
The while loop is much simpler than the for loop. It consists of a condition and the statement block.
Here is the syntax for while loop
As long as the condition evaluates to ‘true’, the program execution will continues to loop through the statements. If the condition in while evaluates to ‘false’ at the very beginning, the loop is skipped altogether and program execution starts at the statement immediately following the loop.
Example
Code Block
Default.aspx
var msg = ""; var x = 1; while (x <= 10) { msg = msg + x + "\n"; x++; }
This loop will display digits 1 to 10 in an alert box.
Do While Loop
The do-while loop is a modified version of the while loop. Here, the condition is placed at the end of the loop and hence, the loop is executed at least once.
Example
Code Block
Default.aspx
var x = 20; do { alert("The number is " + x); x++; } while (x <= 10);
Break and continue Statements For Loops
JavaScript provides commands through which iterations of a loop can be skipped or stopped. These commands are most commonly used along with an if statement inside the loop.
• continue: causes the iteration to be skipped
• break: causes the loop to stop and program execution to begin at the statement immediately following the loop.
Example
Code Block
Default.aspx
var msg = ""; for (var x = 0; x <=20; x++) { if (x%2) { continue; } msg = msg + x + "\n"; }
This will display only the even numbers between 1 to 20, skipping the odd numbers. The condition in if checks for a remainder when variable x is divided by 2. Thus, for odd numbers, the condition will be ‘true’ and the loop will be skipped because of continue.
And break statement will stop the loop iteration process and execute the statements after.
Example
Code Block
Default.aspx
var msg = ""; var t = 1; while (t <= 10) { if (t == 8) { break; } msg = msg + t + "\n"; t++; }
Here the loop will exit when the value of variable t equal to 8. So this will display digits from 1 to 7.
JavaScript For…In Statement
The for…in statement loops through the properties of an object.
Syntax
Code Block
Default.aspx
for (variable in object) { code to be executed } Example var person={fname:"Dick",lname:"Joe",age:25}; for (x in person) { document.write(person[x] + " "); }
• Every element on a web page has certain events which can trigger invocation of event handlers
• Attributes are inserted into HTML tags to define events and event handlers
Examples of events
- A mouse click
- A web page or an image loading
- Mousing over a hot spot on the web page
- Selecting an input box in an HTML form
- Submitting an HTML form
- A keystroke
- onabort – Loading of an image is interrupted
- onblur – An element loses focus
- onchange – The content of a field changes
- onclick – Mouse clicks an object
- ondblclick – Mouse double-clicks an object
- onerror – An error occurs when loading a document or an image
- onfocus – An element gets focus
- onkeydown – A keyboard key is pressed
- onkeypress – A keyboard key is pressed or held down
- onkeyup – A keyboard key is released
- onload – A page or an image is finished loading
- onmousedown – A mouse button is pressed
- onmousemove – The mouse is moved
- onmouseout – The mouse is moved off an element
- onmouseover – The mouse is moved over an element
- onmouseup – A mouse button is released
- onreset – The reset button is clicked
- onresize – A window or frame is resized
- onselect – Text is selected
- onsubmit – The submit button is clicked
- onunload – The user exits the page
We’ll see some basic functions and their examples
onload & onUnload Events
The onload and onUnload events are triggered when the user enters or leaves the page.
The onload event is often used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.
Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.
onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
Example
Code Block
Default.aspx
<input type="text" size="30" id="email" onchange="checkEmail()">;
We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers, and they now offer cloud hosting!
The checkEmail() function will be called whenever the user changes the content of the field.Example Onblur
Code Block
Default.aspx
<html> <head> <script type="text/javascript"> function upperCase() { var x = document.getElementById("fname").value document.getElementById("fname").value = x.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()"> </body> </html>
onMouseOver and onMouseOut
onMouseOver and onMouseOut are often used to create visual effects or animations on hovering around.
Example
Code Block
Default.aspx
<a href="#" onmouseover="document.bgColor='#E4DFC2';" onmouseout="document.bgColor='#FFF';"> Change the background color on mouseover and revert on mouseout </a>
We stand behind Server Intellect and their support team. They offer dedicated servers, and they are now offering cloud hosting!
And that completes our tutorial on JavaScript Functions, Loops and Events, stay tuned for more tutorial based on JavaScript Variables and Objects.Examples.zip
