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, …)
{
//code 1
// code 2
....
}
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).
<html>
<head>
<script type="text/javascript">
function displaymessageundefined) {
alertundefined"Hello Have a nice day!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessageundefined)" >
</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)
{
...
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
var msg = "";
for undefinedvar x = 1; x <= 10; x++)
{
msg = msg + x + "\n";
}
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
while undefinedcondition)
{
...statements...
}
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
var msg = "";
var x = 1;
while undefinedx <= 10)
{
msg = msg + x + "\n";
x++;
}
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.
do
{
...statements...
}
while undefinedcondition);
Example
var x = 20;
do
{
alertundefined"The number is " + x);
x++;
}
while undefinedx <= 10);
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
var msg = "";
for undefinedvar x = 0; x <=20; x++)
{
if undefinedx%2)
{
continue;
}
msg = msg + x + "\n";
}
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
var msg = "";
var t = 1;
while undefinedt <= 10)
{
if undefinedt == 8)
{
break;
}
msg = msg + t + "\n";
t++;
}
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
for undefinedvariable in object)
{
code to be executed
}
Example
var person={fname:"Dick",lname:"Joe",age:25};
for undefinedx in person)
{
document.writeundefinedperson[x] + " ");
}
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
- 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
;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
<html>
<head>
<script type="text/javascript">
function upperCaseundefined) {
var x = document.getElementByIdundefined"fname").value
document.getElementByIdundefined"fname").value = x.toUpperCaseundefined)
}
</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onblur="upperCaseundefined)">
</body>
</html>
onMouseOver and onMouseOutonMouseOver and onMouseOut are often used to create visual effects or animations on hovering around.
Example
<a href="#" onmouseover="document.bgColor='#E4DFC2';" onmouseout="document.bgColor='#FFF';"> Change the background color on mouseover and revert on mouseout </a>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.
And that completes our tutorial on JavaScript Functions, Loops and Events, stay tuned for more tutorial based on JavaScript Variables and Objects.