Javascript
Javascript
Javascript
JavaScript is a scripting language developed by Netscape. Netscape navigator it was originally codenamed "LiveWire" but Netscape later licensed the name JavaScript from Sun. Although Java and JavaScript have similar name, they are different languages and are used to solve different problems.Scripting language provides another way to activate the web pages, make them dynamic, which can change their appearance, contents etc at run time. It is an object-based language that offers cross platform operations across the span of www. The object-based nature of JavaScript offers programmers significant power and flexibility through the ability to create functions and new objects. Performing certain processing functions at the client side - such as form validation and data retrieval from local data arrays - reduces the burden imposed on the server side and can provide a sense of greater responsiveness to a user viewing an HTML document enhanced with JavaScript. JavaScript is interpreted by Web Browsers and does not need any compiler. It is used for Client Side Scripting embedded with HTML code. To embed JavaScript code in HTML, <SCRIPT> tag is used in <HEAD> section or <BODY> section.
Types of Scripts
Immediate Scripts
Immediate Script is the term to indicate lines of JavaScript that not only run when the browser loads the document, but also influence the layout of the page. Such Scripts are placed in <BODY> sections <HTML><HEAD></HEAD> <BODY> <SCRIPT> // Script that produces content for the body </SCRIPT> </BODY> </HTML>
Deferred Scripts
A deferred script is one that the browser sees when the document loads, but the wording of the script tells the browser not to anything with the code other than to be aware that it exists. Such script sections usually consist of small groups of script lines. Adding a deferred script to the Head Block prepares the brewer to respond to user interaction later. <HTML> <HEAD> <SCRIPT> function abc() { // Script that initializes items for user-driven actions } </SCRIPT> </HEAD> <BODY> </BODY> </HTML>
Hybrid Scripts
These scripts are used in designing pages, which require both immediate and deferred scripts. The immediate script lines help to create the contents of the page while the deferred script lines react to the user's actions once the page has been fully loaded. [1] <SCRIPT LANGUAGE="JavaScript" SRC="filename.js"></SCRIPT> [2] <SCRIPT LANGUAGE="JavaScript"> // Script goes here </SCRIPT> [3] <HTML><HEAD> <SCRIPT Language="JavaScript"> var hello="Welcome to JavaScript"; </SCRIPT>
<NOSCRIPT> Sorry! Your browsers does not support JavaScript </NOSCRIPT> </HEAD> <BODY> <SCRIPT Lanaguage="JavaScript"> document.write(hello); </SCRIPT> </BODY> </HTML>
Note :
[1] Some browsers don't support JavaScript, the actual script is defined within the comment tag i.e. "<!--" and "-->", so than such browsers can ignore JavaScript and not display it as text. e.g. <SCRIPT Language="JavaScript"> <!-function Hello() { alert("Welcome to World of JavaScript"); } //--> </SCRIPT> JavaScript is a case sensitive language It is the default scripting language for Netscape Navigator and Internet Explorer. If you are not specifying Language attribute, it will still work.
[2] [3]
<NOSCRIPT> Tag
<NOSCRIPT> and </NOSCRIPT> tags are used to inform those browsers that can't or won't process JavaScript. The HTML instructions contained inside these tags are displayed by JavaScript challenged and JavaScript capable browsers that have an option to disable JavaScript. E.g. <HEAD> <SCRIPT> // script coding </SCRIPT> <NOSCRIPT> // no scripting text </NOSCRIPT> </HEAD>
Variables
Variables is name given to some memory location to store values temporarily. Each variable has name. Variable names in JavaScript, can begin with alphabet (A through Z and a through z) or underscore (_) character or ($) sign. The rest of the characters may be letters, digits (0 through 9) or underscore. E.g. name, total_amout etc. its
Variable Types
Unlike C/C++ or Java, JavaScript does not require specification of data type contained in a variable. It has variant data type define by var command. The same variable can contain different type of values among Integers, Floating point numbers, Boolean values, Strings or Null. The JavaScript interpreter maintains a record of the type of value contained in the variable. E.g. var name="Hello"; var total=789;
Type conversion
JavaScript has the capability to convert values automatically from one type to another, when
used
in expression. JavaScript provides some pre-defined functions for explicit type conversion like eval(), parseInt() and parseFloat().
eval() function can be used to convert string value or expression to a numeric value. Example <html><head> <script> var exp=prompt("Please enter an epression",""); alert("Result of Expression "+exp + " is " + eval(exp)); </script> <body></body> </html> parseInt() function converts a string to an Integer value. It returns 0 if the string does not begin with and integer or else, returns the first integer contained in the string. Example <html> <head> <script> function factorial(n) { var f=1; for(var i=1;i<=n;i++) f=f*i; return f; } var a=parseInt(prompt("Enter a Number","")); var fact=factorial(a); alert("Factorial of "+a + " is "+fact); </script> </head> <body></body> </html> parseFloat() function is very similar to the parseInt() function. It return the first floating point number contained in as string or else, returns 0 if the string does not begin with a valid floating point number. JavaScript Comments JavaScript uses similar syntax for comments as C/C++ and Java. You can use // or /* and */ combination can be used for comments. JavaScript Built-in Functions alert(string or variable) - To give a message dialog box prompt("message","default value") - To give a message and get value in the form of string and pass is to some variable confirm("message") - Used to confirm something from user by giving a confirmation dialog box with command buttons Ok and Cancel. It returns boolean value, true or false which can be used in conditional statements. Example <html> <head> <title>Using Built-in Functions</title> </head> <body> <script language="JavaScript"> alert("Welcome to JavaScript"); var name=prompt("Please Enter your name",""); if(confirm("Should I wish you")) {
alert("Dear "+name+" Thanks for Using JavaScipt"); } else { } </script> </body> </html>
Using Arrays
Array is a kind of variable which can store multiple value differentiated by index number. Arrays can be fixed, dynamic or dense. arrayName=new Array(numberOfElements); //fixed array arrayName=new Array(); //dyanamic array. Allows any number of elements
arrayName= [value1,value2,valuen]; // dense array or arrayName=new Array(value1,value2,.,valuen); Example 1 var num=new Array(10); // only 10 elements allowed num[0] to num[9] var n=new Array(); //any number of elements var data=[Amit kumar,4000,false,new Array(3)); data[3][0]=90; data[3][1]=30; data[3][2]=50; Example 2 <html><head> <script> var n=new Array(); n[0]="Rajesh"; n[1]="Amit Kumar"; n[2]="Bhuvnesh Sharma"; var colors=["Red","Green","Blue"]; document.write("Array elements are <br>"); for(var i=0;i<n.length;i++) document.write("<font color='"+colors[i] + "'>"+n[i]+"</font><br>"); document.write("Whole Array is " + n +"<br>"); document.write("Sorted Array is " + n.sort()); </script> </head><body></body> </html> Output is :
Logical Operators
Comparison Operators
Strictly equal to (===) and strictly not equal to (!==) operators does not perform type conversions. Example 1 <script> var a=56; var b="56"; if(a==b) alert("equal"); //result else alert("not equal"); </script> Example 2
<script> var a=56; var b="56"; if(a===b) alert("equal"); else alert("not equal"); //result </script>
String operators
+
String concatenation
& And | Or ^ Exclusive Or << Left Shift >> Right Shift >>> Zero-fill right shift Examples <html><head> <script> document.write("5 & 13 = " + (5&13) + "<br>"); document.write("5 | 13 = " + (5|13)+ "<br>"); document.write("5 << 3 = " + (5<<3) + "<br>"); document.write("120 >> 2 = " + (120>>2) + "<br>"); </script> </head> <body></body> </html>
Assignment Operators
= += -= *= /= %= <<= >>= >>>= &= |= ^= Equal to
Ternary Operator
?: condition ? value1 : value2 This operator is ternary operator since it takes three operators - a condition to be evaluated and two alternative values to be returned based on the truth and falsity of the condition.
Special Operators
The comma (,) operator The delete operator - used to delete property of an object or an element at an array index The new operator - used to create instance of an object type The typeof operator - returns a string value that identifies the type of an operand. E.g. a=typeof 14; //The value assigned is "number" The void operator - does not return a value. It is typically used with the JavaScript. Example <script> var a=4>6; alert(typeof a);
</script>
Operator Precedence
the
The precedence of the operator determines which operations are evaluated before others during parsing and execution of complex expression. Precedence Operator 1 parenthesis (), function call or array subscript [] 2 !, ~, - (unary), ++, --, typeof, new, void, delete 3 *, /, % 4 +, -(binary) 5 <<, >>, >>> 6 <, <=, >, >= 7 ==, !=, ===, !== 8 & 9 ^ 10 | 11 && 12 || 13 ?: 14 =, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |= 15 comma (,) operator For a precedence level, precedence is Left to Right.
Note :
Conditional Statements
if statement
Used to test the given condition, if condition is true the execute the statement written within the block otherwise execute the statement written in else block. Syntax [a] if (condition) [d] if(condition1) { { statements; statements; } } [b] if(condition) else if(condition2) { { statements; statements; } } else ...... { ...... statements; else } { statements; } [c] if(condition) { if(condition) { statements; } } Examples Ex1. Get two numbers and show greatest of that numbers. <script language="javascript"> var n1=prompt("Please enter first number ",""); var n2=prompt("Please enter second number",""); n1=parseFloat(n1); n2=parseFloat(n2);
if(n1>n2) alert(n1+" is greater"); else alert(n2+" is greater"); </script> Ex2. Get three numbers and find smallest of three numbers. <script language="javascript"> var n1=prompt("Please enter first number ",""); var n2=prompt("Please enter second number",""); var n3=prompt("Please enter third number",""); n1=parseFloat(n1); n2=parseFloat(n2); n3=parseFloat(n3); if(n1>n2) if(n1>n3) alert(n1+" is greatest"); else alert(n3+" is greatest"); else if(n2>n3) alert(n2+" is greatest"); else alert(n3+" is greatest"); </script>
switch statement - To execute the commands given in the case depending on the value of the
variable Syntax switch(variable) { case value1 : statements;break; case value2 : statements;break; ................. ................. default : statements; }
n1=parseFloat(n1); n2=parseFloat(n2); n3=parseFloat(n3); var g=n1>n2 ? (n1>n3 ? n1 : n3) : (n2 > n3 ? n2 : n3); alert(g + " is greatest"); </script>
Iterations or Loops
[1] for loop
for(initilization;condition;updateStatement) { statements; } while loop - pre-condition check while(condition) { statements; } do-while loop - post-condition check, Executes at least once do { statements; }while(condition);
[2]
[3]
Other commands
break command - Used to break the loop or switch statements continue command - Used to skip the commands written below continue and go back to the start of loop Example <script language="javascript"> // print all even numbers between 1 to 100 for(var i=1;i<=100;i++) { if(i%2!=0) continue; document.write(i + "<br>"); } </script>
objects that provide access to the Web Page and the HTML elements it contains. These objects are used to update and interact with the loaded Web page. screen object event object navigator object plugin object plugins array mimeType objcet mimeTypes array history frame frames
window
document element object location object image object images array applet object applets array link object links array anchor object anchors array form object forms array checkbox object radio object text object textarea object password object hidden object submit object reset object button object select object option object
Other Predefined Objects Math Object String Object Array Obect Date Object Function Object Each object can have Propterties, Methods and Events attached with it. Properties defines behaviour of the object like color, size etc, methods defines actions taken by the object and events are particular instance to perform a task like click, dblClick, mouseMove, mouseDown etc.
document Object
Properties of document object bgColor - Background Color fgColor - Foreground (text) Color title - Title of Web Page linkColor - Color of links alinkColor - Color of Active Links vlinkColor - Color of Visited Links Methods of document object write() - to write some content on WebPage writeln() - to write contents on WebPage with Line Break close() - close the document Sub-Objects of document object Links[] anchors[] forms[] document.formName document.forms[number] elements[] sub-object type property value property text object value button object value checkbox checked radio object document.forms[0].groupName.length Find No. of radio buttons document.forms[0].groupName[0].checked document.forms[0].groupName[0].value select object document.forms[0].selectName.selectedIndex document.forms[0].selectName.options[n].text string on screen document.forms[0].selectName.options[n].value hidden string images[] applets[] embeds[] Example 1 <script> function clearTextboxes() { var form=window.document.forms[0]; for(var I=0;I<form.elements.length;I++) { if (form.elements[I].type=text) form.elements[I].value=; } }
</script> Example 2 Working with radio buttons <html><head><script> function sexCheck() { var form=document.forms[0]; for(var i=0;i<form.sex.length;i++) if(form.sex[i].checked) break; alert("You are "+form.sex[i].value); } </script> </head> <body> <form> Sex<input type="radio" name="sex" value="Male">Male <input type="radio" name="sex" value="Female">Female <br><input type="button" value="Test" onClick="sexCheck()"> </form></body></html> Example 3 Navigating with select object <html><head><script> function goThere() { var list=document.forms[0].urlList; location=list.options[list.selectedIndex].value; } </script> </head> <body><form> Select URL to go : <select name=urlList onChange=goThere()> <option selected value=index.htm>Home Page <option value=store.htm>Store Information <option value=http://www.yahoo.com>Search the Web </select> </form> </body></html>
navigator Object
Like window object , it is a top-level object in the browser hierarchy. Properties of navigator object appCodeName appName appVersion connectionSpeed onLine cpuClass plateform cookieEnabled userAgent Example of appName <html><head> <script> var nv=navigator.appName; if (nv=="Microsoft Internet Explorer") document.location.href="ie.htm"; else if (nv=="Netscape") document.location.href="nn.htm";
screen Object
To get information about screen of client Properties of screen object height width colorDepth availHeight availWidth Example 1 <html><head> <script> with(document) { write("Width : " +screen.width + "<br>"); write("Height : " +screen.height + "<br>"); write("availWidth : " +screen.availWidth+ "<br>"); write("availHeight : " +screen.availHeight + "<br>"); write("Color : " +screen.colorDepth); } </script> </head> <body></body> </html> Example 2 <html><head></head> <body> <img name="img1"> <script> if (screen.availHeight>=480) document.images['img1'].src="om1.jpg"; else document.images['img1'].src="om2.jpg"; </script> </body> </html>
window Object
Properties of window object closed defaultStatus length - Number of frames in window name - Name of the window object status Sub-Objects of window object document frames history location Methodss of window object alert(text) blur()
clearInterval(interval) clearTimeout(timer) close() confirm(text) focus() open(url,name[,options]) prompt(text,defaultValue) scroll(x,y) setInterval(expr, milleseconds) setTimeout(expr,milliseconds) moveTo(x,y) resizeTo(width,height) Example 1 : setTimeout() and clearTimeout() mehods <html><head> <script> var i=0; var timer; var colors=new Array("Red","Green","Blue"); function changeColor() { document.bgColor=colors[i++]; if (i==colors.length) i=0; timer=setTimeout("changeColor()",1000); } function stop() { clearTimeout(timer); } changeColor(); </script> </head> <body> <input type="button" value="Start" onClick="changeColor()"> <input type="button" value="Stop" onClick="stop()"> </body> </html> Example 2 open() and close() methods, status and defaultStatus properties <html><head> <script> var newWin window.defaultStatus="Using window object methods"; function makeNewWin() { newWin=open("","myWin","width=300,height=300"); } function closeNewWin() { if(newWin) newWin.close(); } </script> </head> <body><form> <input type="button" value="Create New Window" onClick="makeNewWin()" onMouseOver="window.status='Click to create a new window'"> <input type="button" value="Close Window" onClick="closeNewWin()"
onMouseOver="window.status='Click to close the created window'"> </form></body></html> Example 3 Writing output to new window <html><head> <script> var newWin function table() { var n=parseInt(document.f.num.value); newWin=open("","tablewin","width=300,height=400"); with(newWin.document) { write("<h1 style='color:red;font-size:40pt'>Table of "+n+"</h1>"); for(var i=1;i<=10;i++) write(n + " * " + i + " = " +i*n + "<br>"); write("<input type='button' value='Close' onClick='window.close()'>"); } } </script> </head> <body> <h1>General Programs</h1> <form name="f"> Number <input type="text" name="num" size="5"><br> <input type="button" value="Table" onClick="table()"> </form> </body></html> Example 4 : Using moveTo() and resizeTo() <html><head><script> function fullScreen() { this.moveTo(0,0); this.resizeTo(screen.availWidth,screen.availHeight) } </script></head> <body><form> <input type="button" value="Maximize Window" onClick="fullScreen()"> </form></body></html> Example 5 : Diverting output to new window <html><head> <script> var newWin function table() { var n=parseInt(document.f.num.value); newWin=open("","tablewin","width=300,height=400"); with(newWin.document) { write("<h1 style='color:red;font-size:40pt'>Table of "+n+"</h1>"); for(var i=1;i<=10;i++) write(n + " * " + i + " = " +i*n + "<br>"); write("<input type='button' value='Close' onClick='window.close()'>"); } } </script> </head><body>
<h1>General Programs</h1> <form name="f"> Number <input type="text" name="num" size="5"><br> <input type="button" value="Table" onClick="table()"> </form> </body></html>
location Object
Properties of location object href URL to navigate hash anchor to navigate host hostname pathname port protocol search Methods of location object reload() http://www.abc.com:80/promos/products.htm#vcr protocol http hostname www.abc.com port 80 host www.abc.com:80 pathname /promos/products.htm hash #vcr href http://www.abc.com:80/promos/products.htm#vcr
Example
history Object
Date Object It provides a common set of methods for working with date and time.
Methods of Date object getDate() getDay() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getYear() getFullYear() toString() Constructors of Date object Date() Date(datString) Date(milliseconds) Date(year, month, day, hour, minutes, seconds, milliseconds) Date(Month dd, yyyy) Date(Month dd,yyyy hh:mm:ss)
Syntax objectName = new Function(arugments, body); <script> cb = new Function(n , return n*n*n); document.write(Cube of 5 is : + cb(5) + <br>); document.write(Cube of 7 is : + cb(7) ); </script>
Math Object Provides a standard library of mathematical constants and functions. Constants are defined as properties and functions are defined as methods.
Properties of Math object E Eulers Constant i.e. 2.718281828459045 LN2 The natural log of 2 LN10 The natural log of 10 LOG2E The base 2 log of e LOG10E The base 10 log of e PI The value of PI i.e 3.141592653589793 SQRT2 The square root of 2 Methods of Math object abs(x) acos(x) asin(x) atan(x) ceil(x) floor(x) sin(x) cos(x) tan(x) exp(x) log(x) max(x,y) min(x,y) Absolute value
Returns the least integer that is greater than or equal to x Returns the greatest integer that is less than or equal to x Sine of x Cosine of x Tangent of x ex Natural log of x Maximum of x and y Minimum of x and y
xy Returns random number between 0 and 1 Returns x rounded to closest integer Returns square root of x
Example of random() function <html> <script> function timer() { var x=Math.random()*100; var y=Math.random()*100; var d=new Date(); var time=d.getHours()+":"+d.getMinutes()+":"+d.getSeconds(); t.innerHTML="<span style='position:absolute;left:"+x+";top:"+y +"'>"+time+"</span>"; } setInterval("timer()",1000); </script> <body> <span id="t"></span> </body> </html>
String Object The String object type allows strings to be accessed as objects. String type objects can be created in two ways variable= text or variable=new String(text)
Properties of String object length Methods of String object charAt(index) charCodeAt(index) indexOf(pattern) indexOf(pattern,startIndex) lastIndexOf(pattern) lastIndexOf(pattern,startIndex) split(separtor) subString(startIndex) subString(startIndex) toLowerCase() toUpperCase() toString() Example <script> function showText(text) { document.write(text + <br>); }
s= new String(We are Indians); showText(s = +s); showText(s.charAt(1) = + s.charAt(1)); //e showText(s.charCodeAt(1) = +s.charCodeAt(1)); //101 showText(s.toLowerCase()); showText(s.toUpperCase()); </script>
with Statement
It is provided as a convienance to eliminate retyping the name of an object that is to be referenced in a series of property references and method invocations. Syntax is with ( variableName or objectName) { statements; } Example with (document) { write(<h1>Welcome to World of JavaScript</h1>); write(<hr><font color=red>We want to learn it</font>); }
Creating Functions
Function is a set of statement defined under a single name. Functions are created using function command. Syntax is function functionName([parameters]) { statements; [return value or variable;] } Example 1 function factorial(n) { var f=1; for(var I=1;I<=n;I++) f=f*I; return f; } Example 2 function sqrt2() { return Math.sqrt2; }
Objects can be created using functions only. Properties of an object are defined with the function and value is passed using this operator. this operator represents the current object. Syntax is function objectName(parameters) { this.propertyName=parameter; } Instance of such objects can be created using new operator. Syntax is variable = new objectName(values);
Example <html><head> <script> function employee(name,basic) { this.name=name; this.basic=basic; } function net(basic) { //da - 25% hra - 30% pf-12% var netsalary = basic + 0.25*basic + 0.3*basic - 0.12*basic; return netsalary; } var n=new Array(); n[0]=new employee("Amit Kumar",4000); n[1]=new employee("Rajesh Verma",6000); n[2]=new employee("Sanjay Sharma",6500); n[3]=new employee("Vineet Gupta",5600); n[4]=new employee("Rajesh Saxena",4500); document.write("<pre>"); with(document) { write("Name\t\t\tBasic\t\tNet Salary<br>"); for(var i=0;i<n.length;i++) write(n[i].name+"\t\t"+n[i].basic+"\t\t"+net(n[i].basic)+"<br>"); } </script> <body></body>
</html>
Output is :
Deleting Properties
Properties of an object can be deleted using delete operator. delete objectName.propertyName; eg. delete emplyee.basic;
Events describe actions that occur as the result of user interaction with a Web page or other browser-related activities. Eg when user clicks a hyper link or button, enters data in the form. The browser waits for events to occur, and when they do, it performs whatever processing is assigned to those events. The processing is performed in response to the occurrence of an event is known as event handling. The code that performs this processing is called an event handler. Here are a few things you can do with events using JavaScript event handlers Display a dialog box when user moves the mouse over a link Validate the data a user has just entered into a form Load and display an animation sequence when a user clicks a button. Interact with Java Applets and browser Plug-ins JavaScripts event-handling features are what enables JavaScript to create Web pages that come alive and interact with Web users.
HTML Elements
all elements link image area document body window, frameset,frame form text field password field text area button submit reset radio button checkbox selection
HTML Tags
various tags <A></A> <IMG> <AREA> <BODY></BODY> <BODY>,<FRAME>, <FRAMESET> <FORM> <INPUT TYPE=text> <INPUT TYPE=password> <TEXTAREA> <INPUT type=button> <INPUT type=submit> <INPUT type=reset> <INPUT type=radio> <INPUT type=checkbox> <SELECT></SELECT>
JavaScript Event
mouseMove click, dblClick, mouseDown, mouseUp, mouseOver, mouseOut, keyDown, keyUp, keyPress abort, error, load, keyDown, keyUp, keyPress mouseOver, mouseOut, dblClick load, unLoad blur, error, focus, load, unLoad, move, resize, dragDrop submit, reset blur, focus, change, select blur, focus blur, focus, change, select, keyDown, keyUp, keyPress click, blur, focus, mouseDown, mouseUp click, blur, focus click, blur, focus click, blur, focus click, blur, focus blur, focus, change
Some new attributes are added with HTML tags to use events. on is added before the event name to use an event eg onClick, onLoad, onDblClick, onMouseOver etc