Programming Tutorials on XHTML, CSS, JavaScript, JQuery, JSON, Python, Django, Amazon Web Services, ASP.NET, Web Forms, and SQL
Friday, June 29, 2012
Java Script Tutorial 25 : JavaScript RegExp Object
A regular expression (RegExp) is an object that describes a pattern of characters. When you search in a text, you can use a pattern to describe what you are searching for. A simple pattern can be one single character. A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more.
Regular expressions are used to perform powerful pattern-matching and search-and-replace functions on text. Syntax of RegExp is as follow :
var patterntxt=new RegExp(somepattern,modifiers);
or
var patt=/somepattern/modifiers;
In above code, somepattern specifies the pattern of an expression. modifiers specify if a search should be global, case-sensitive, etc.
RegExp Modifiers are used to perform case-insensitive and global searches. For example we use i modifier for case-insensitive matching and g modifier for global match. Global match means, find all matches rather than stopping after the first match. For example
var str1 = "This is some text.";
var pattern = /some text/i;
document.write(str1.match(pattern));
The result of above case-sensitive search will be : some text
The test() method searches a string for a specified value, and returns true or false, depending on the result. For example
var pattern=new RegExp("s");
document.write(pattern.test("The sun rises in the east"));
Result of above code will be "true", as it contains the "s" string.
The exec() method searches a string for a specified value, and returns the text of the found value. It return null, in case no match found. For example
var pattern=new RegExp("s");
document.write(pattern.exec("The sun rises in the east."));
Result of above code will be "s", as it contains the "s" string.
Java Script Tutorial 24 : JavaScript Math Object
The Math object allows you to perform mathematical tasks. The Math object includes several mathematical constants and methods. Syntax for using properties/methods of Math is as follows:
var x=Math.PI;
var y=Math.sqrt(16);
There is eight mathematical constants in JavaScript that can be accessed from the Math object. These mathematical constants are :
E
PI
square root of 2
square root of 1/2
natural log of 2
natural log of 10
base-2 log of E
base-10 log of E.
We can call/reference these constants from JavaScript as below:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
There are many mathematical methods also available in JavaScript. For example Math.round() is used to round a number, e.g
document.write(Math.round(9.8));
Result of above code will be : 10
Math.random() method of the Math object is used to generate random numbers. For example
document.write(Math.random());
Result of above code can be anything between 0 and 1.
We can set the limit of random number generation( by using arguments ). For example, the following code return random number between 0 and 20.
Math.random()*21)
To generate random number from 0 and 100 change 21 to 101.
var x=Math.PI;
var y=Math.sqrt(16);
There is eight mathematical constants in JavaScript that can be accessed from the Math object. These mathematical constants are :
E
PI
square root of 2
square root of 1/2
natural log of 2
natural log of 10
base-2 log of E
base-10 log of E.
We can call/reference these constants from JavaScript as below:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
There are many mathematical methods also available in JavaScript. For example Math.round() is used to round a number, e.g
document.write(Math.round(9.8));
Result of above code will be : 10
Math.random() method of the Math object is used to generate random numbers. For example
document.write(Math.random());
Result of above code can be anything between 0 and 1.
We can set the limit of random number generation( by using arguments ). For example, the following code return random number between 0 and 20.
Math.random()*21)
To generate random number from 0 and 100 change 21 to 101.
Thursday, June 28, 2012
Java Script Tutorial 23 : JavaScript Boolean Object
The JavaScript Boolean object represents two values, "true" or/and "false". We can create a Boolean object in javascript as follows :
var myBooleanObj=new Boolean();
Javascript boolean object will set to false, if we do not set its initial value or has one of the following values:
0
-0
null
""
false
undefined
NaN
It will be true for any other value.
Java Script Tutorial 22 : JavaScript Array Object
An array is a special variable, which can hold more than one value, at a time. For example, if you have a list of items, storing the country names in single variables could look like as follow :
var country1="Pakistan";
var country2="USA";
var country3="Russia";
An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own ID so that it can be easily accessed. We can defined array in following ways :
var country=new Array();
country[0]="Pakistan";
country[1]="USA";
country[2]="Russia";
or
var country=new Array("Pakistan","USA","Russia");
or
var country=["Pakistan","USA"," Russia"];
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. For example
document.write(country[1]);
Result of above code will be : USA
To modify a value in an existing array, just add a new value to the array with a specified index number:
country[1]="Germany";
This code change the value USA to Germany inside array object.
document.write(country[0]);
Now It will result as : Germany
Java Script Tutorial 21 : JavaScript Date Object
The JavaScript Date object is used to work with dates and times. Date objects are created with the Date() constructor. We can initiate date by four ways:
- new Date()
- new Date(milliseconds)
- new Date(dateString)
- new Date(year, month, day, hours, minutes, seconds, milliseconds)
We can operate a number of methods after creating a date object. These method allow you to get and set value of year, month, day, hour, minute, second, and milliseconds of the object. All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
For example
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
Set/Manipulate Dates :
We can easily manipulate the date by using the methods available for the Date object. For example
var myDateobj=new Date();
myDateobj.setFullYear(2011,0,15);
Adding days to a date shifts the month or year, the changes are handled automatically by the Date object itself.
Compare Two Dates :
We can also use Date object to compare two dates. For example
var y=new Date();
y.setFullYear(2110,0,16);
var current = new Date();
if ( y > current )
{
alert("Current Date is before 16th January 2110");
}
else
{
alert("Current Date is after 14th January 2100");
}
Java Script Tutorial 20 : JavaScript Objects
JavaScript is an Object Based Programming language, and allows you to define your own objects and make your own variable types.
An object is just a special kind of data. An object has properties and methods. We can create our own objects in java script, which will be discussed in future tutorials.
Properties :
Properties are the values associated with an object. For example
<script type="text/javascript">
var txt="This is text.";
document.write(txt.length);
</script>
In above code, txt is an object and length is its property. Result displayed in browser will be : 13
Methods :
Methods are the actions that can be performed on objects. For example
<script type="text/javascript">
var txt="This is Text";
document.write(txt.toUpperCase());
</script>
In above code txt is an object and toUpperCase() is method. Result displayed in browser will be :
THIS IS TEXT
Tuesday, June 26, 2012
Java Script Tutorial 19 : JavaScript Special Characters
In JavaScript, Special characters can be added to a text string by using the backslash sign. For example we want to display following text in JavaScript code.
var txt="This "This is a "big" Apple.";
In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to:
This is a
We must place a backslash (\) before each double quote in "big" to solve this problem. This result string will look like this :
var txt="This "This is a \"big\" Apple.";
After executing in browser, it will display string as :
This is a "big" Apple.
There are many other special characters that can be added to a text string with the backslash sign, these are :
\' ( single quote )
\" ( double quote )
\\ ( backslash )
\n ( new line )
\r ( carriage return )
\t ( tab )
\b ( backspace)
\f ( form feed )
Java Script Tutorial 18 : JavaScript Throw
JavaScript throw statement allows you to create an exception. If you use this statement together with the try .. catch statement, you can control program flow and generate error messages. The exception can be a string, integer, Boolean or an object. Syntax of throw is as:
throw exception
For example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 2 and 5:","");
try
{
if(x>5)
{
throw "Error 1";
}
else if(x<2)
{
throw "Error 2";
}
}
catch(err)
{
if(err=="Error 1")
{
document.write("The value is higher then 5.");
}
if(err=="Error 2")
{
document.write("The value is lower then 2.");
}
}
</script>
</body>
</html>
Java Script Tutorial 17 : JavaScript Try .. Catch
JavaScript try .. catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax of JS try .. catch is :
try
{
// code
}
catch()
{
// Handle errors
}
For example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var txt="";
function Showmessage()
{
try
{
adddlert("JS try .. catch testing ....");
}
catch(err)
{
txt="There was an error on this page.";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="Click to View message" onclick="Showmessage()" />
</body>
</html>
try
{
// code
}
catch()
{
// Handle errors
}
For example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var txt="";
function Showmessage()
{
try
{
adddlert("JS try .. catch testing ....");
}
catch(err)
{
txt="There was an error on this page.";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="Click to View message" onclick="Showmessage()" />
</body>
</html>
Friday, June 22, 2012
Java Script Tutorial 16 : JavaScript Events
Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Following are some events we use in javascript.
onLoad and onUnload :
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. In following example the validateEmail() function will be called whenever the user changes the content of the field.
<input type="text" size="30" id="email" onchange="validateEmail()" />
onSubmit :
The onSubmit event is used to validate ALL form fields before submitting it. In following example, the validateForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function validateForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled.
<form method="post" action="mypage.htm" onsubmit="return validateForm()">
onMouseOver :
The onmouseover event can be used to trigger/call a function when the user mouses over an HTML element.
- A mouse click
- A web page loading
- Mousing over
- Selecting an input field
- Submitting an HTML form
- A keystroke
onLoad and onUnload :
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. In following example the validateEmail() function will be called whenever the user changes the content of the field.
<input type="text" size="30" id="email" onchange="validateEmail()" />
onSubmit :
The onSubmit event is used to validate ALL form fields before submitting it. In following example, the validateForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function validateForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled.
<form method="post" action="mypage.htm" onsubmit="return validateForm()">
onMouseOver :
The onmouseover event can be used to trigger/call a function when the user mouses over an HTML element.
Java Script Tutorial 15 : JavaScript Functions
Function :
A function is a block of code that executes only when you tell it to execute. It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function. Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made. Syntax to write a function is as follows :
function functionname()
{
some code
}
The word function must be written in lowercase letters. Example of JavaScript function is below.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myfunc()
{
alert("Called by JS Function!");
}
</script>
</head>
<body>
<button onclick="myfunc()">Click Me !</button>
</body>
</html>
Function with Arguments :
When you call a function, you can pass along some values to it, these values are called arguments or parameters. These arguments can be used inside the function. You can send as many arguments as you like, separated by commas (,). Declare the argument, as variables, when you declare the function. Syntax to write function with arguments is as follow :
function myfunc(var1,var2)
{
some code here.
}
For example
<script type="text/javascript">
function myFunction(var1,var2)
{
alert("you passed " + var1 + ", and " + var2);
}
</script>
<button onclick="myfunc('isb','pak')">Click Me !</button>
Functions With a Return Value :
Sometimes you want your function to return a value back to where the call was made. This is possible by using the return statement. When using the return statement, the function will stop executing, and return the specified value. Syntax of function with return value is as follow :
function myfunc()
{
var y=10;
var z=5;
return y+z;
}
The function above will return the value 15. The function-call will be replaced with the returnvalue. For example
var x=myfunc();
After executing function "myfunc", value of x will be 15. The return value of function can be directly written into html elements. For example
document.getElementById("id").innerHTML=myfunc();
The return statement is also used when you simply want to exit a function.
Thursday, June 21, 2012
Java Script Tutorial 14 : JavaScript For .. In
The for .. in statement loops through the properties of an object. Syntax of for .. in is as follow :
for (variable in object)
{
code to be executed
}
For example
var person={fname:"waqas",lname:"ali",age:23};
for (y in person)
{
txt=txt + person[x];
}
The result of above code will be
waqasali23
for (variable in object)
{
code to be executed
}
For example
var person={fname:"waqas",lname:"ali",age:23};
for (y in person)
{
txt=txt + person[x];
}
The result of above code will be
waqasali23
Java Script Tutorial 13 : JavaScript Break and Continue
The break Statement :
The break statement will break the loop and continue executing the code that follows after the loop.For example, in following code, for loop will stop its execution when value of i equal to 3, and code continue execution after this for loop.
for (i=0;i<7;i++)
{
if (i==3)
{
break;
}
y=y + "The number is " + i + "<br />";
}
The result of above code will be :
The number is 0
The number is 1
The number is 2
The continue Statement :
The continue statement will break the current loop and continue with the next value. For example, in following code the for loop skip its iteration at value equal to 3 and then continue its execution normally.
for (i=0;i<=7;i++)
{
if (i==3)
{
continue;
}
y=y + "The number is " + i + "<br />";
}
The result of above code will be :
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
Java Script Tutorial 12 : JavaScript While Loop
The while Loop :
The while loop loops through a block of code while a specified condition is true. Syntax of while loop is as follow :
while (variable<endvalue)
{
code to be executed
}
For example
while (i<3)
{
y=y + "The number is " + i + "<br />";
i++;
}
The above while loop will run when value of i less then 3, and it will stop working when it is exceed or equal to 3.
The do .. while Loop :
The do .. while loop is a variant of the while loop. This loop will execute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax of do .. while loop is as follow :
do
{
code to be executed
}
while (variable<endvalue);
For example
do
{
y=y + "The number is " + i + "<br />";
i++;
}
while (i<3);
The above loop will run once before checking condition, and then it will check condition every time, and run only if condition met.
Java Script Tutorial 11 : JavaScript For Loop
When you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform tasks. There are two different kind of loops, we use in JavaScript, these are as follows :
The for Loop :
The for loop is used when you know in advance how many times the script should run. Syntax of for loop is as follow :
for ( variable = startvalue; variable<endvalue;variable = variable + increment)
{
code to be executed
}
For example
for (i=0; i<3; i++)
{
y=y + "The number is " + i + "<br />";
}
This for loop runs 3times, and write results in every new line. The result of above code will be :
The number is 0
The number is 1
The number is 2
- for
- while
The for Loop :
The for loop is used when you know in advance how many times the script should run. Syntax of for loop is as follow :
for ( variable = startvalue; variable<endvalue;variable = variable + increment)
{
code to be executed
}
For example
for (i=0; i<3; i++)
{
y=y + "The number is " + i + "<br />";
}
This for loop runs 3times, and write results in every new line. The result of above code will be :
The number is 0
The number is 1
The number is 2
Java Script Tutorial 10 : JavaScript Popup Boxes
There are three kind of popup boxes in JavaScript
An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax of Alert Box is as follows :
For example
Confirm Box :
A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax of Confirm Box is as follows :
For example
Prompt Box :
A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax of Prompt Box is as follows :
For example
To display line breaks inside a popup box, use a back-slash followed by the character n. For example
- Alert box
- Confirm box
- Prompt box
An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax of Alert Box is as follows :
For example
Confirm Box :
A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax of Confirm Box is as follows :
For example
Prompt Box :
A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax of Prompt Box is as follows :
For example
To display line breaks inside a popup box, use a back-slash followed by the character n. For example
Java Script Tutorial 9 : JavaScript Switch Statement
The switch statement are used to perform different action based on different conditions. The switch statement can be replaced by performing many if-then-else-if conditions, but when the answer of an evalution can give you many different answers, the switch-case statement can be more efficient. Syntax of switch statement is as follow :
switch(x)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if x is different from case 1 and 2
}
The value of the variable x will be compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. For example
switch ( day )
{
case 0:
y="Sunday";
break;
case 1:
y="Monday";
break;
case 2:
y="Tuesday";
break;
}
If the value of variable day is 0 then result will be "Sunday", and result will be "Monday" and "Tuesday" if values will be 1 and 2 respectively.
We use the default keyword to specify what to do if there is no match. For example, there is no value equal to 0, 1 or 2, then write a default message, for example write "friday".
switch ( day )
{
case 0:
y="Sunday";
break;
case 1:
y="Monday";
break;
case 2:
y="Tuesday";
break;
default:
y="Friday";
}
If there is no match found then result will be "friday".
Java Script Tutorial 8 : If Else Statements
Conditional statements are used to perform different actions based on different conditions. In JavaScript we have the following conditional statements.
- if statement
- if...else statement
- if...else if....else statement
- switch statement
If Statement :
We use the if statement to execute some code only if a specified condition is true. Syntax of if statement is as follow :
if (some condition)
{
code to be executed if condition is true
}
For example
if (number<33)
{
x="failed";
}
If value of variable number is less then 33 then result will be "failed".
If .. else Statement :
We use the if else statement to execute some code if a condition is true and another code if the condition is not true. Syntax for this is as follows :
if (some condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
For example
if ( number < 33 )
{
y="failed";
}
else
{
y="passed";
}
If the value of variable number less then 33 then result will be "failed", otherwise result will be "passed".
If .. else if .. else Statement :
We use the if else if else statement to select one of several blocks of code to be executed. Syntax for this is as follow
if (condition 1 here)
{
code to be executed if condition1 is true
}
else if (condition 2 here)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
For example
if (number>90)
{
y="Passed : Excellent Result";
}
else if (number<33)
{
y="failed";
}
else
{
y="passed";
}
If the value of variable number will be greater then 90 then result will be "Passed : Excellent Result". if value will be less then 33 then result will be "failed", otherwise (when value will be between 33 and 90 ) result will be "passed".
Wednesday, June 20, 2012
Java Script Tutorial 7 : Comparison and Logical Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values. Comparison operators can be used in conditional statements to compare values and take action depending on the result. There are many Comparison operators used in javascript, some of these are below :
Logical operators are used to determine the logic between variables or values. We can use following logical operators in java script.
&& ( and )
|| ( or )
! ( not )
conditional operator : JavaScript contains conditional operator that assigns a value to a variable based on some condition. Syntax of this conditional operator is as below.
somevariablename = (put condition here) ? value1 : value2
If condition meets then output 'll be 'value1', and if condition doesn't meet then output 'll be 'value2'.
Operator Symbol | Uses/Description |
---|---|
= = | is equal to |
= = = | is exactly equal to (value and type both) |
! = | is not equal |
> | is greater than |
< | is less than |
> = | is greater than or equal to |
< = | is less than or equal to |
Logical operators are used to determine the logic between variables or values. We can use following logical operators in java script.
&& ( and )
|| ( or )
! ( not )
conditional operator : JavaScript contains conditional operator that assigns a value to a variable based on some condition. Syntax of this conditional operator is as below.
somevariablename = (put condition here) ? value1 : value2
If condition meets then output 'll be 'value1', and if condition doesn't meet then output 'll be 'value2'.
Tuesday, June 12, 2012
Java Script Beginner Tutorial 6 : JavaScript Operators
JavaScript operators are used to perform operations on JavaScript variables. The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. For example
x = 3;
y = 4;
z = x + y;
The output 'll be equal to 7.
Arithmetic operators are used to perform arithmetic between variables and/or values. There are many arithmetic operators, we use in JavaScript, for example
+ ( used for addition), - ( used for subtraction ),
* ( used for multiplication ), / ( used for division ),
% ( used for modulus ), ++ ( used for increment ) and
-- ( used for decrement )
Assignment operators are used to assign values to JavaScript variables. These assignments operators can be used in JavaScript :
= , += , -= , *= , /= and %=
The + operator can also be used to add string variables or text values together. For example
str1 = "This is ";
str2 = "a fox";
str3 = str1 + str2;
The output 'll be "This is a fox."
If you add a number and a string, the result will be a string. For example
x = "this is a string" + 10 ;
The output 'll be "this is a string10".
x = 3;
y = 4;
z = x + y;
The output 'll be equal to 7.
Arithmetic operators are used to perform arithmetic between variables and/or values. There are many arithmetic operators, we use in JavaScript, for example
+ ( used for addition), - ( used for subtraction ),
* ( used for multiplication ), / ( used for division ),
% ( used for modulus ), ++ ( used for increment ) and
-- ( used for decrement )
Assignment operators are used to assign values to JavaScript variables. These assignments operators can be used in JavaScript :
= , += , -= , *= , /= and %=
The + operator can also be used to add string variables or text values together. For example
str1 = "This is ";
str2 = "a fox";
str3 = str1 + str2;
The output 'll be "This is a fox."
If you add a number and a string, the result will be a string. For example
x = "this is a string" + 10 ;
The output 'll be "this is a string10".
Saturday, June 9, 2012
Java Script Beginner Tutorial 5 : Java Script Variables
JavaScript variables are used to hold values or expressions. A variable can have a short name e.g x or y etc, or it can have more descriptive name, for example firstname or city. There are some rules for naming JavaScript variables, these are below.
- Variable names are case sensitive, y and Y are two different variables. (as JavaScript is case-sensitive, so variable names are also case-sensitive.)
- Variable names must begin with a letter, the $ character, or the underscore character.
JavaScript Variables Declaration :
Creating new variable in JavaScript is most often referred to as "declaring" a variable. Variables are declared in JavaScript using var keyword, e.g var cityname; To assign a value to the variable, we use the = sign, e.g cityname="NYC"; However, we can also assign a value to the variable when we declare it, e.g var cityname="NYC";
To assign a text value to a variable, put quotes around the value. While assigning a numeric value to a variable, do not put quotes around the value, if you put quotes around a numeric value, it will be treated as text. If you redeclare a JavaScript variable, it will not lose its value.
If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. e.g cityname="NYC"; will declare the variable carname as a global variable if it does not already exist.
Local JavaScript Variables :
A variable declared within a JavaScript function becomes local and can only be accessed within that function. Local variables can be with the same name in different functions, because local variables are only recognized by the function in which they are declared. Local variables are deleted as soon as the function is completed.
Global JavaScript Variables :
Variables declared outside a function, become Global, and all scripts and functions on the web page can access it. Global variables are deleted only when you close the page.
JavaScript Arithmetic :
You can do arithmetic operations with JavaScript variables ( as we do with algebra ). For example
y=3;
x=y+4;
Friday, June 8, 2012
Java Script Beginner Tutorial 4 : Java Script Comments
JavaScript comments can be used to make the code more readable. Comments are not executed by JavaScript. There are two ways for commenting JavaScript Code. These are as follows
Single line comments :
Single line comments start with //. For example, we use single line comments to explain the code.
// Edit paragraph on page load
document.getElementById("Parag").innerHTML="This paragraph added using JS.";
Single line comment can be used to prevent the execution of one of the code lines, for example
//document.getElementById("p1").innerHTML="paragraph 1 text here";
document.getElementById("p2").innerHTML=" paragraph 2 text here ";
First code line 'll not be executed by browser.
JavaScript Multi-Line Comments :
Multi line comments start with /* and end with */.
For example
/*
The JS code below will
Edit paragraph,
having id "parag".
*/
document.getElementById("Parag").innerHTML="This paragraph added using JS.";
Multi-line comments can used to prevent the execution of a code block. For example
/*
document.getElementById("p1").innerHTML="paragraph 1 here";
document.getElementById("p2").innerHTML=" paragraph 2 here ";
*/
Comments can be placed at the end of a code line as well. For example
var str="My name is Waqas."; // declare a variable and assign a value to it
str= str + "I am JS developer"; // concatenate string to variable.
Single line comments :
Single line comments start with //. For example, we use single line comments to explain the code.
// Edit paragraph on page load
document.getElementById("Parag").innerHTML="This paragraph added using JS.";
Single line comment can be used to prevent the execution of one of the code lines, for example
//document.getElementById("p1").innerHTML="paragraph 1 text here";
document.getElementById("p2").innerHTML=" paragraph 2 text here ";
First code line 'll not be executed by browser.
JavaScript Multi-Line Comments :
Multi line comments start with /* and end with */.
For example
/*
The JS code below will
Edit paragraph,
having id "parag".
*/
document.getElementById("Parag").innerHTML="This paragraph added using JS.";
Multi-line comments can used to prevent the execution of a code block. For example
/*
document.getElementById("p1").innerHTML="paragraph 1 here";
document.getElementById("p2").innerHTML=" paragraph 2 here ";
*/
Comments can be placed at the end of a code line as well. For example
var str="My name is Waqas."; // declare a variable and assign a value to it
str= str + "I am JS developer"; // concatenate string to variable.
Monday, June 4, 2012
Java Script Beginner Tutorial 3 : Where to place JS
There are different ways, we can place Java Script code inside web page. These are as follows
JavaScript in <body>
JavaScript in <head>
Using an External JavaScript
JavaScript in <body> :
Java Script code can be placed in <body> tag. It is placed at the bottom of the page to make sure all the elements are loaded completely. If Java Script code executed before entire page loaded then it may cause problem, e.g trying to change content of some element ( say <p> ) , which is not loaded yet, can cause problem. For example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="content">A Paragraph</p>
<script type="text/javascript">
document.getElementById("content").innerHTML="Edited using JavaScript";
</script>
</body>
</html>
If we place <p> tag after Java Script code then definitely it cause problem.
JavaScript Functions and Events :
If we want to execute a JavaScript when an event occurs, such as when a user clicks a button then we 'll put the script inside a function. Functions are normally used in combination with events. For example, in following code, JS function named "myFunction" 'll be called on button click event. ( This is also example of Java Script in <head> )
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
document.getElementById("content").innerHTML="Edited using JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="content">A Paragraph</p>
<button type="button" onclick="myFunction()">Click Me !!!</button>
</body>
</html>
You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
Using an External JavaScript :
JavaScript can also be placed in external files. External JavaScript files often contain code to be used on several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag. For example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="myScript.js"></script>
</body>
</html>
The script will behave as it was located in the document, exactly where you put it.
JavaScript in <body>
JavaScript in <head>
Using an External JavaScript
JavaScript in <body> :
Java Script code can be placed in <body> tag. It is placed at the bottom of the page to make sure all the elements are loaded completely. If Java Script code executed before entire page loaded then it may cause problem, e.g trying to change content of some element ( say <p> ) , which is not loaded yet, can cause problem. For example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="content">A Paragraph</p>
<script type="text/javascript">
document.getElementById("content").innerHTML="Edited using JavaScript";
</script>
</body>
</html>
If we place <p> tag after Java Script code then definitely it cause problem.
JavaScript Functions and Events :
If we want to execute a JavaScript when an event occurs, such as when a user clicks a button then we 'll put the script inside a function. Functions are normally used in combination with events. For example, in following code, JS function named "myFunction" 'll be called on button click event. ( This is also example of Java Script in <head> )
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFunction()
{
document.getElementById("content").innerHTML="Edited using JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="content">A Paragraph</p>
<button type="button" onclick="myFunction()">Click Me !!!</button>
</body>
</html>
You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.
Using an External JavaScript :
JavaScript can also be placed in external files. External JavaScript files often contain code to be used on several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag. For example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="myScript.js"></script>
</body>
</html>
The script will behave as it was located in the document, exactly where you put it.
Sunday, June 3, 2012
Java Script Beginner Tutorial 2 : How To Use
JavaScript is typically used to manipulate existing HTML elements. The HTML "id" attribute is used to identify HTML elements. The document.getElementById() method will access the HTML element with the specified id. For Example, in following code, the browser will access the HTML element with id="content", and replace the content with "Edited using JavaScript ".
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="content">My First Paragraph</p>
<script type="text/javascript">
document.getElementById("content").innerHTML="Edited using JavaScript";
</script>
</body>
</html>
The HTML <script> tag is used to insert a JavaScript into an HTML document. Inside the <script> tag use the type attribute to define the scripting language (e.g type="text/javascript"). The <script> and </script> tells where the JavaScript starts and ends. The lines between the <script> and </script> contain the JavaScript and are executed by the browser:
Browsers that do not support JavaScript, will display JavaScript as page content. To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript. Add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, as follows
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("content").innerHTML="Edited using JavaScript";
//-->
</script>
</body>
</html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.
The following example writes a <p> element into the HTML document:
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<script type="text/javascript">
document.write("<p>Added using JavaScript</p>");
</script>
</body>
</html>
The problem here is that, the entire HTML page will be overwritten if document.write() is used inside a function. So we must use document.getElementById() to avoid overwritten entire HTML page.
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="content">My First Paragraph</p>
<script type="text/javascript">
document.getElementById("content").innerHTML="Edited using JavaScript";
</script>
</body>
</html>
The HTML <script> tag is used to insert a JavaScript into an HTML document. Inside the <script> tag use the type attribute to define the scripting language (e.g type="text/javascript"). The <script> and </script> tells where the JavaScript starts and ends. The lines between the <script> and </script> contain the JavaScript and are executed by the browser:
Browsers that do not support JavaScript, will display JavaScript as page content. To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript. Add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, as follows
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("content").innerHTML="Edited using JavaScript";
//-->
</script>
</body>
</html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.
The following example writes a <p> element into the HTML document:
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<script type="text/javascript">
document.write("<p>Added using JavaScript</p>");
</script>
</body>
</html>
The problem here is that, the entire HTML page will be overwritten if document.write() is used inside a function. So we must use document.getElementById() to avoid overwritten entire HTML page.
Subscribe to:
Posts (Atom)