sap4help@gmail.com +91 8956877466
This website is always under updation with new contents
JavaScript Tutorials
Introduction
Js comment
Variable
Global variables
Operators
ControlStatement
Switch
Loop
for loop
while loop
for in loop
Functions
Parameter Functions
Mouse Over
Javascript Object
Date
String
Escape Represents
Number
Boolean
Object
Array
Java Browser objects
Window Object
History Object
Navigator Object
Screen object
Document object
getElementById
getElementByTagName
innerhtml
innerText
Form validation
JavaScript
Loops

Repeat loops in real life generally mean the repetition of a series of steps until some condition is met, thus enabling you to break out of that loop. Such was the case earlier in this chapter when you looked through a bushel of tomatoes for the one that came closest to your ideal tomato. The same can be said for driving around the block in a crowded neighborhood until a parking space opens up.

A repeat loop lets a script cycle through a sequence of statements until some condition is met. For example, a JavaScript data validation routine might inspect every character that you enter into a form text field to make sure that each one is a number. Or if you have a collection of data stored in a list, the loop can check whether an entered value is in that list. Once that condition is met, the script can then break out of the loop and continue with the next statement after the loop construction.

The most common repeat loop construction used in JavaScript is called the for loop. It gets its name from the keyword that begins the construction. A for loop is a powerful device because you can set it up to keep track of the number of times the loop repeats itself. The formal syntax of the for loop is as follows:


There are four types of loops in JavaScript.
  1. for loop
  2. while loop
  3. do-while loop
  4. for-in loop
1. for loop

Javascript for loop repeats the statement till condition is true.

Syntax
for (initialization; condition; increment)  
{  
    // body of if  
}  
Ex: WAP in javascript for in loop
<html>
<body>
<script type ="text/javascript">
varaproperty;
	document.write("Navigator object properties<br/>");
	
	for (aproperty in navigator)
	   {
	document.write(aproperty);
		document.write("<br/>");
	   }
	document.write("Exiting from the Loop");
	</script>
	</body>
</html>	

2. while loop

Javascript while loop repeats the statement till condition is true. But it checks condition at beginning.

Syntax
while(condition)
{
	// Body
}
example
html>
<body>
<script type ="text/javascript">
var count = 0;
document.write("starting Loop ");

while(count < 10)
	{
	document.write("current count :" + count +"<br/>");
	count++;
	}
	document.write("Loop stopped");
	</script>
	</body>
</html>	

3. do while loop

Javascriptdo while loop repeats the statement till condition is true. But it checks condition at last.

Syntax
do{
	//body
}while(condition);
Ex: WAP in javascript for do while loop
<html>
<body>
<script type ="text/javascript">
	var count = 0;
	document.write("starting Loop" + "<br/>");
	do
	  {
	document.write("current count" +count+ "<br/>");
	count++;
	  }
	while(count < 5)
	document.write("Loop stopped");
	</script>
</body>
</html>

4. for in loop

JavaScript for in loop is used to repeats the properties of an object.

Syntax
for (property in object)
	   {
	    //body
	   }
Ex: WAP in javascript for in loop
<html>
<body>
<script type ="text/javascript">
varaproperty;
	document.write("Navigator object properties<br/>");
	
	for (aproperty in navigator)
	   {
	document.write(aproperty);
		document.write("<br/>");
	   }
	document.write("Exiting from the Loop");
	</script>
	</body>
</html>	

Functions

You saw a preview of the JavaScript function. A function is a definition of a set of deferred actions. Functions are invoked by event handlers or by statements elsewhere in the script. Whenever possible, good functions are designed for reuse in other documents. They can become building blocks you use over and over again.

If you have programmed before, you can see parallels between JavaScript functions and other languages’ subroutines. But unlike some languages that distinguish between procedures (which carry out actions) and functions (which carry out actions and return values), only one classification of routine exists for JavaScript.

A function is capable of returning a value to the statement that invoked it, but this is not a requirement. However, when a function does return a value, the calling statement treats the function call like any expression—plugging in the returned value right where the function call is made. I will show some examples in a moment.

Formal syntax for a function is as follows:
functionfunctionName ( [parameter1]...[,parameterN] ) 
{
statement[s]
}
Ex:WAP in javascript for function
<html>
<head>
<script type ="text/javascript">
functionsayHello(name ,age)
     {
	document.write(name + "is"+age+"year old");
	 }	
	</script>
</head>
<body>
<p> Click the following button to call the function</p>
	<form>
	<input type ="button" onclick="sayHello('ashish',25)" value ="say hello">
	</form>
	</body>
	</html>

Ex: WAP in javascript for parameter function
<html>
<head>
<script type="text/javascript">
		function concatenate(first, last)
		 {
		var full;
		full = first + last;
		return full;
		 }
		functionsecondfunction()
		  {
		var result;
		result = concatenate('ashu','gadpayle');
		document.write(result);
		  }
		</script>
	</head>
	<body>
	<form>
		<input type ="button" onclick="secondfunction()" value="call function">
		</form>
	</body>
	</html>

Ex: WAP in javascript for mouse over function
<html>
<head>
<script text ="text/javascript">
	function over()
	  {
	document.write("mouse over");
	  }
	
	function out()
	   {
	document.write("mouse out");
	   }
	</script>
	</head>
	
	<body>
	<p> Bring your mouse inside the division to see the result </p>
	
	<div onmouseover ="over()" onmouseout="out()">
	<h2> this is the inside the division </h2>
	</div>
	</body>
	</html>

Javascript Object
Date

Javascript can handle basic data types like numbers (all treated as 64-bit floating point values), boolean values (true or false) and strings. Complex or compound data types can also be handled as objects or arrays. Objects are not C++/Java classes, they act as associative arrays with arbitrary data values and arbitrary names. Javascript 1.2 added support for regular expressions as a specialised data type.

Ex:WAP in javascript for Date()
<body>
<script type="text/javascript">
vardt = Date();
document.write("Date and time:"+dt);
</script>
</body>

String

Not all character sets are supported by all browsers, although ECMA-262 requires Javascript to support the full 16-bit Unicode set. If you need to use Unicode, check browser compatibility before implementing the Javascript. Special characters can be "escaped" to change the meaning of the character within the string.


Escape Represents
\bBackspace
\fForm Feed
\nNew line
\rCarriage Return
\tTab
\'Apostrophe or single quote that does not terminate the string.
\"Double quote that does not terminate the string.
\\Single backslash character
\dddCharacter with Latin-1 encoding specified by three octal digits/td>
\xddCharacter with Latin-1 encoding specified by two hexadecimal digits
\uddddCharacter with Unicode encoding specified by four hexadecimal digits

Number

Numbers in Javascript are all floating point values - whole numbers (integers) are not a separate type. Very large or very small values use an optional exponent syntax: 6.02e23

Hexadecimal or octal notation can be used to refer to an integer value, but Javascript will convert to a decimal floating point value: Octal: 0377 = 255

Hexadecimal: 0xFF = 255


Boolean

Use the keywords true and false to set variables as boolean data type.

var bool = true;

Object

An object can contain any number of properties of any type. Use the .operator to access a named property of an object. (In the code above, Math.pow() is used to access an object method.

obj.x = 1;
obj.y = 2;

Array

Javascript arrays are a form of object that uses numerical values for property names - as the object is normally an associative array anyway, this gives you a normal array, just like in C, PHP Java etc. To create an array, just use numerical values for the property names:

a[0] = 1;
a[1] = a[0] *2;

Java Browser objects

The lowest common denominator document object hierarchy that is implemented in all scriptable browsers. Notice that the window object is the topmost object in the entire scheme. Everything you script in JavaScript is in the browser’s window.


Window objects

At the very top of the document object hierarchy is the window object. This object gains that exalted spot in the object food chain because it is the master container for all content you view in the Web browser. As long as a browser window is open—even if no document is loaded in the window—the window object is defined in the current model in memory.

In addition to the content part of the window where documents go, a window’s sphere of influence includes the dimensions of the window and all of the “stuff” that surrounds the content area.

The area where scrollbars, toolbars, the status bar, and (non-Macintosh) menu bar live is known as a window’s chrome. Not every browser has full scripted control over the chrome of the main browser window, but you can easily script the creation of additional windows sized the way you want and have only the chrome elements you wish to display in that subwindow.


The History Object

Another object that doesn’t have a physical presence on the page is the history object. Each window maintains a list of recent pages that the browser has visited. While the history object’s list contains the URLs of recently visited pages, those URLs are not generally accessible by script due to privacy and security limits imposed by browsers. But methods of the history object allow for navigating backward and forward through the history relative to the currently loaded page.


The JavaScript navigator object is the object representation of the client internet browser or web navigator program that is being used. This object is the top level object to all others.

Most Navigator objects have corresponding HTML tags. Refer to the appropriate object section for more information.

  • MimeType - Allows access to information about MIME types supported by the browser.
  • plugin - Access to information about all plugins the browser supports. <EMBED>
  • window - The browser frame or window.
  • embeds - Allows access to embedded plug ins.

  • Screen object

    A Screen object, automatically created by the JavaScript runtime engine, returns information on the display screen's dimensions and color depth.

    This object is has no programmatic use; it used purely to get information about the client's screen capabilities such as width , height , color-depth etc


    Document object

    The document object holds the real content of the page. Properties and methods of the document object generally affect the look and content of the document that occupies the window. Only more recent browsers (IE4+ and NN6+) allow script access to the text contents of a page once the document has loaded. However, as you saw in your first script of Chapter 3, the document.write() method lets a script dynamically create content as the page loads. A great many of the document object’s properties are established by attributes of the <BODY> tag. Many other properties are arrays of other objects in the document.

    Accessing a document object’s properties and methods is straightforward, as shown in the following syntax examples:

    [window.]document.PropertyName
    [window.]document.MethodName([parameters])

    The window reference is optional when the script is accessing the document object that contains the script. If you want a preview of the document object properties of the browser you’re using, enter document into the bottom text box of The Evaluator Jr. and press Enter/Return. The object’s properties and current values appear in the Results box.


    getElementById

    Have you ever tried to use JavaScript to do some form validation? Did you have any trouble using JavaScript to grab the value of your text field? There's an easy way to access any HTML element, and it's through the use of id attributes and the getElementById function.

    If you want to quickly access the value of an HTML input give it an id to make your life a lot easier. This small script below will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.

    JavaScript Code:
    <script type="text/javascript">
    functionnotEmpty(){
    	varmyTextField = document.getElementById('myText');
    	if(myTextField.value != "")
    		alert("You entered: " + myTextField.value)
    	else
    		alert("Would you please enter some text?")		
    }
    </script>
    <input type='text' id='myText' />
    <input type='button' onclick='notEmpty()' value='Form Checker' />

    getElementsByTagName

    The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. Consequently, there is no need to call several times Element.getElementsByTagName() with the same element and arguments.

    Syntax
    elements = element.getElementsByTagName(tagName)

    Js innerhtml property

    The innerHTML property can be used to modify your document's HTML on the fly.

    When you use innerHTML, you can change the page's content without refreshing the page. This can make your website feel quicker and more responsive to user input. The innerHTML property is used along with getElementById within your JavaScript code to refer to an HTML element and change its contents. The innerHTML property is not actually part of the official DOM specification. Despite this, it is supported in all major browsers, and has had widespread use across the web for many years. DOM, which stands for Document Object Model, is the hierarchy that you can use to access and manipulate HTML objects from within your JavaScript.

    The innerHTML Syntax
    document.getElementById('{ID of element}').innerHTML = '{content}';

    Js innerText property

    JavascriptinnerText property in mozilla does not work, there is an alternative to get the innerText. JavascriptinnerText property doesn’t work in Mozilla Firefox.

    So if you are writing document.getElementById(“elementID”).innerText then it might work and give you some value in IE but you will get undefined value in Mozilla Firefox. So can we use innerHTML property instead of innerText?

    JavascriptinnerHTMLpropety gives the html tags along with the text, so if you are using innerHTML then you need to remove all the HTML tags to get the actual text. Instead of using innerHTML you can use textContent, which works in Mozilla Firefox (not in IE). So to use this property you need to do a check (for making it work both in IE and FireFox) which is:

    functiongetInnerText(elementID)
    {
    if(typeOf(document.getElementById(elementID).innerText) != "undefined")
       {
    returndocument.getElementById(elementID).innerText;
       }
    else
       {
    returndocument.getElementById(elementID).textContent;
       }
    }

    JavaScript form validation
    Ex :WAP in JavaScript to check password
    <html>
    <head>
    <script>
    functionformvalid(passw)  
       {  
          // JavaScript Document
    
    varpassw=/^[A-Za-z]\w{7,14}$/;  
    if(passw.value.match(passw))   
                   {   
    alert('Correct, try another...')  
    return true;  
                   }  
    else
                   {   
    alert('Wrong...!')  
    return false;  
                   }  
                 }  
    </script>
    </head>
    
    <body>
    <form name="reg" onsubmit="return formvalid()">
    
    <h3> Enter password </h2>
    
    <input type ="text" name="passw">
    <input type="submit" name="submit">
    </form>
    </body>

    For accessing computer programs go to TECHNOLOGY