yeasir007

Wednesday, November 21, 2012

JavaScript Basic for the beginner



JavaScript fundamental tutorial for the beginner:


What Is JavaScript?
 JavaScript is the scripting language of the Web. JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and much more. JavaScript’s official name is ECMAScript which is developed and maintained by the ECMA International organization and invented by Brendan Eich.It’s a lightweight programming language and usually embedded directly into HTML pages. JavaScript is an interpreted language that means scripts execute without pre­liminary compilation.



How To Put a JavaScript into an HTML Page?
The following example shows how to use JavaScript to write text on a Web page.
<html>
 <body>
    <script type="text/javascript">
    document.write ("Hello World!");
    document.write ("<h1>Hello World!</h1>");
    </script>
   </body>
 </html>

OUTPUT:




The document.write command is a standard JavaScript command for writing output to a page. When you types the document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line. If we had not typed the <script> tag, the browser would have treated the document.write (“Hello World!”) command as pure text and would just write the entire line on the page, as shown:



Where to Put the JavaScript?
Java script may be placed into <body></body>,<head></head>,external file or  in both.
    <html>
    <head>
    <script type="text/javascript"> 
    function message(){
    alert("This alert box was called with the onload event");
    }
    </script>
    </head>
    <body onload="message()">
    <script type="text/javascript">
    document.write("This message is written by JavaScript"); </script>
    </body>
    </html>

If you want to run the same JavaScript on several pages without having to write the same script on every page, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. External script cannot contain <script> tag.
      <html>
    <head>
    <script type="text/javascript" src="abc.js"></script>
    </head>
    <body onload="message()">
    //------------//
    </body>
    </html>


JavaScript Statements:
A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do. The following JavaScript statement tells the browser to write “Hello World” to the Web page:
document.write("Hello World");
It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice.

JavaScript Comments:
JavaScript comments can be added to explain the JavaScript script or to make the code more readable. Single line comments start with //. Multiline comments start with /* and end with */.
     <html>
    <body>
    <script type="text/javascript">
    /* The code below will write
        one heading and two paragraphs
    */
    document.write ("<h1>This is a heading</h1>"); 
    document.write ("<p>This is a paragraph.</p>"); 
    document.write ("<p>This is another paragraph.</p>"); //It's a single line comments
    </script>
    </body>
    </html>





JavaScript variables:
JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like nickName. There are 59 reserved words that are not legal variable names. Rules for JavaScript variable names:
Ø  Variable names are case sensitive (x and X are two different variables).
Ø  Variable names must begin with a letter, the underscore character, or a dollar sign. (The $ character is used primarily by code-generation tools.)
Ø  Subsequent characters may be letter, number, underscore, or dollar sign.
If you declare a variable within a function, the variable can be accessed only within that function. When you exit the function, the variable is destroyed. These vari­ables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.If you declare a variable outside a function, all the functions on your page can access it. These variables are called global variables.The lifetime of these variables starts when they are declared and ends when the page is closed.
    <html>
    <body>
    <script type="text/javascript">
    var nickName ="SP";
    document.write (nickName); 
    document.write ("<br />"); 
    firstname="SweetPaglee";
    document.write (nickName); </script>
    </body>
    </html>

    OUTPUT: 
    SP
    SweetPaglee 

Declaring (Creating) JavaScript variables:
Creating variables in JavaScript is most often referred to as “declaring” variables. You can declare JavaScript variables with the var statement:
var x;
var nickName;
After the declaration shown, the variables are empty. (They have no values yet.)However, you can also assign values to the variables when you declare them:
var x=5;
var nickName ="SweetPaglee";
After the execution of the preceding statements, the variable x will hold the value 5, and nickName will hold the value SweetPaglee.
Assigning values to Undeclared JavaScript variables:
If you assign values to variables that have not yet been declared, the variables will automatically be declared.The following statements:
x=5;
nickName ="SweetPAglee";
have the same effect as these:
var x=5;
var nickName ="SweetPAglee";

 Redeclaring JavaScript variables:
If you redeclare a JavaScript variable, it will not lose its original value.
Var   x  =   5 ;
var x;
After the execution of the preceding statements, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.
JavaScript Arithmetic:
As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;
JavaScript Arithmetic Operators:
Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y = 5, the following table explains the arithmetic operators.
Operator
Description
Example
Result
+
Addition
x = y+2
x = 7
-
Subtraction
x = y-2
x = 3
*
Multiplication
x = y*2
x = 10
/
Division
x = y/2
x = 2.5
%
Modulus (division remainder)
x = y%2
x = 1
++
Increment
x = ++y
x = 6
--
Decrement
x = --y
x = 4

JavaScript Assignment Operators:
Assignment operators are used to assign values to JavaScript variables. Given that x = 10 and y = 5, the following table explains the assignment operators:
Operator
Example
Same As
Result
=
x = y

x = 5
+=
x+ = y
x = x+y
x = 15
-=
x- = y
x = x-y
x = 5
*=
x* = y
x = x*y
x = 50
/=
x/ = y
x = x/y
x = 2
%=
x% = y
x = x%y
x = 0


The + Operator Used on Strings:
The + operator also can be used to concatenate string variables or text values together. To concatenate two or more string variables together, use the + operator:
txt1= "What a very";
txt2= "nice day";
txt3= txt1+txt2;
After the execution of the preceding statements, the variable txt3 contains “What a verynice day”. To add a space between the two strings, insert a space into one of the strings:
txt1= "What a very ";
txt2= "nice day";
txt3= txt1 + txt2;
Or insert a space into the expression:
txt1= "What a very";
txt2= "nice day";
txt3= txt1 + " " + txt2;
After the execution of the preceding statements, the variable txt3 contains: What a very  nice day


Adding Strings and Numbers
The rule is as follows: If you add a number and a string, the result will be a string! Your results are shown :
     
     <html>
    <body>
    <script type="text/javascript"> 
    x=5+5;
    document.write(x);
    document.write("<br/>");
    x="5"+"5";
    document.write(x);        
    document.write("<br/>");
    x=5+"5";      
    document.write(x);        
    document.write("<br/>");
    x="5"+5;      
    document.write(x);        
    document.write("<br/>");
   </script>       
   <p>The rule is: If you add a number and a string, the result will be a string.</p>
   </body>
   </html>




Comparison operators:
Comparison operators are used in logical statements to determine equality or differ­ence between variables or values. Given that x = 5, the following table explains the comparison operators:
operator
Description
Example
==
is equal to value...is equal to value
x == 8 is false
===
is exactly equal to value and type
x === 5 is true
x === “5” is false
!=
is not equal
x! = 8 is true
> 
is greater than
x > 8 is false
< 
is less than
x < 8 is true
>=
is greater than or equal to
x >= 8 is false
<=
is less than or equal to
x <= 8 is true

Logical operators:
Logical operators are used to determine the logic between variables or values. Given that x = 6 and y = 3, the following table explains the logical operators:
operator
Description
Example
&&
and
(x < 10 && y > 1) is true
||
or
(x == 5 || y == 5) is false
!
not
!(x == y) is true

Conditional operator:
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. The syntax is as follows:
VariableName = (condition)? value1:value2
Ex: greeting = (visitor =="SP")?"Dear SweetPaglee ":"Dear ";
If the variable visitor has the value of "SP", then the variable greeting will be assigned the value "Dear SweetPaglee” else it will be assigned "Dear".
Conditional Statements:
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. JavaScript has the following conditional statements:
Ø  if statement. Use this statement to execute some code only if a specified condi­tion is true.
Ø  if...else statement. Use this statement to execute some code if the condition is true and another code if the condition is false.
Ø  if...else if. ... else statement. Use this statement to select one of many blocks of code to be executed.
Ø  switch statement. Use this statement to select one of many blocks of code to be executed.

Use the if .... else if... else statement to select one of several blocks of code to be executed.
     <html>
    <body>
    <script type="text/javascript">
    var d = new Date();
    var time = d.getHours();
    if (time<10){
    document.write ("<b>Good morning</b>");
    }
    else if (time>=10 && time<16){
    document.write ("<b>Good day</b>");
    }
    else{
    document.write ("<b>Hello World!</b>");
    }
    </script>
    <p>
    This example demonstrates the if..else if ... else statement. </p>
    </body>
    </html>



The for Loop:
The for loop is used when you know in advance how many times the script should run. The syntax is as follows:
     for (var=startvalue;var<=endvalue;var=var+increment)
    {
     //code to be executed
    }

The while Loop:
The while loop loops through a block of code a specified number of times or while a specified condition is true. The syntax is as follows:
    while (var<=endvalue)
    {
     //code to be executed
    }

The do ... while Loop:
The do ... while loop is a variant of the while loop. This loop will execute the block of code once, and then it will repeat the loop as long as the specified condi­tion is true. The syntax is as follows:
     do
    {
     //code to be executed
    }
    while (var<=endvalue);
The following example uses a do ... while loop. The do ... while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested.
The break Statement:
The break statement will terminate execution of the loop and continue executing the code that follows after the loop (if any).
   <html> 
  <body> 
  <script type="text/javascript">
  var i=0;
  for (i=0;i<=10;i++)
  {
   if (i==3){
    break; }
   document.write("The number is " + i);
   document.write("<br/>");
  }
  </script>
  <p>Explanation: The loop will break when i=3.</p>
  </body>
  </html>




The continue Statement:
The continue statement will terminate the current iteration and restart the loop with the next value.
   <html>
  <body> 
  <script type="text/javascript">
  var i=0;
  for (i=0;i<=10;i++){
  if (i==3){
  continue;
  }
  document.write("The number is " + i);
  document.write("<br />");
  }
  </script>
  <p>Explanation: The loop will break the current loop and continue with the next value when i=3.</p>
  </body>
  </html>







JavaScript for...in Statement:
The for...in statement loops through the elements of an array or through the properties of an object. The syntax is as follows:
    for (variable in object)
    {
     //code to be executed
    }
The code in the body of the for...in loop is executed once for each element/property.
  <html>
 <body> 
 <script type="text/javascript">
 var x;
 var myArray = new Array();
 myArray [0] = "Nashra";
 myArray [1] = "Misha";
 myArray [2] = "Angir";
 for (x in myArray )
 {
  document.write(myArray[x] + "<br/>");
 }
 </script>
 </body>
 </html>

 OUTPUT :
 Nashra
 Misha
 Angir

JavaScript switch Statement:
Use the switch statement to select one of many blocks of code to be executed. The syntax is as follows:
 switch(n) {
 case 1:
   execute code block 1
   break; 
 case 2:
   execute code block 2
   break; 
 default:
   code to be executed if n is different from case 1 and 2
 }
This is how it works: First we have a single expression n (most often a variable) that is evaluated once. The value of the expression is then 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.
popup Boxes:
 JavaScript has three types of popup boxes: alert box, confirm box, and prompt box.
Alert Box:
An alert box is often used when you want to display information to the user. When an alert box pops up, the user will have to click OK to proceed. The syntax is as follows: alert ("some text");
<html>
 <head>
 <script type="text/javascript">
 function show_alert(){
 alert("Hello! I am an alert box!");
 } 
 </script>
 </head>
 <body>
 <input type="button" onclick="show_alert()" value="Show alert box" />
 </body>
 </html>





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. The syntax is as follows: confirm ("some  text") ;
<html>
<head>
<script type="text/javascript">
function show_confirm(){
var r=confirm("Press a button!");
if (r ==true){
alert("You pressed OK!");
}
else{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm () " value="Show a confirm box" />
</body>
</html>






Prompt Box:
A prompt box is often used if you want the user to input a value while on a page or from 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. The syntax is as follows: prompt ("some  text" ,   "default value")  ;
<html>
<head>
<script type="text/javascript">
function disp_prompt (){
var fname=prompt("Please enter your name:","Your name")     
document.getElementById("msg").innerHTML="Greetings, " + fname
}
</script>
</head> 
<body>
<input type="button" onclick="disp_prompt () " value="Display a prompt box"/><br/><br/>
<div id="msg"></div>
</body>
</html>
How to Define a JavaScript Function:
A function contains code that will be executed by an event or by a call to the func­tion.You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). The syntax is as follows:
function functionname(var1,var2,...,varX)
 {
   //some code
 }
The parameters var1, var2, and so on, are variables or values passed into the function. The { } defines the start and end of the function. Do not forget about the importance of capitalization in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs. Also note that you must call a function with the exact same capitalization as in the function declaration.
<html>
   <head>
   <script type="text/javascript">
   function myfunction(txt){
   alert(txt);
   }
   </script>
   </head>
   <body>
       <form>
       <input type="button" onclick="myfunction('Hello')" value="Call function">
       </form>
       <p>By pressing the button above, a function will be called with "Hello" as a parameter. The function will alert the parameter.</p>
     </body>
     </html>
   





The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement.
<html>
   <head>
   <script type="text/javascript">
   function product(firstNumber,secondNumber){
     return firstNumber*secondNumber;
   }
   </script>
   </head>
   <body>
     <body>
     <script type="text/javascript"> document.write(product(4,3)); </script>
     <p>The script in the body section calls a function with two parameters (4 and 3).        </p>
     <p>The function will return the product of these two parameters.</p>

     </body>
   </html>





Some common JavaScript event name:
Ø  onLoad and onUnload
Ø  onFocus, onBlur, and onChange
Ø  onSubmit
Ø  onMouseOver,onMouseOut,onClick
The try...catch statement:
The try...catch statement enables you to trap errors that occur during the execu­tion of a block of code. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.
<html>
   <head></head>
   <body>
   <script type="text/javascript">
   var x=prompt("Enter a number between 0 and 10:","");
   try {
   if (x>10) {
    throw "Err1";
   }
   else if(x<0) {
    throw "Err2";
   }
   else if(isNaN(x)) {
    throw "Err3";
   }
   }
   catch(er){
   if(er =="Err1"){
    alert("Error! The value is too high");
   }
   if(er =="Err2"){
    alert("Error! The value is too low");
   }
   if(er =="Err3"){
    alert("Error! The value is not a number");
   }
  }
 </script>
 </body>
 </html>

Insert Special Characters:
The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string. Look at the following JavaScript code:
Var txt= " Do you know who is "SweetPaglee" "; document.write(txt);
In JavaScript, a string is started and stopped with either single or double quotes. This means that the preceding string will be chopped to Do you know who is.
To solve this problem, you must place a backslash (\) before each double quote in SweetPaglee. This turns each double quote into a string literal:
Var txt= " Do you know who is \"SweetPaglee\" "; document.write(txt);
JavaScript will now output the proper text string: Do you know who is "SweetPaglee"
Here is another example:
document.write ("SweetPaglee \& Me!");
 The previous example will produce the following output: SweetPaglee & Me!
The following table lists other special characters that can be added to a text string with the backslash sign:

Code
Outputs
\’
single quote
\”
double quote
\&
ampersand
\\
backslash
\n
new line
\r
carriage return
\t
tab
\b
backspace
\f
form feed


Next post will be JavaScript Object and advance JavaScript. Thank you.








No comments:

Post a Comment

Thanks for your comments