Anda di halaman 1dari 44

Javascript Short Notes What is javascript?

Scripting language Interpreted language (Can be run without being compile) External & Internal Javascript a. External <script type=text/javascript src=xxx.js></script> b. Internal <script>..</script

Javascript Statements a. Used to give command to the browser b. Tell the browser what to do c. Example:document.write(Hello Dolly);

Javascript codes a. Sequence of javascript statements b. Example: document.write(Hello); document.write(Dolly); document.write(!);

Javascript blocks a. Grouped javascript statements, Starts with { and end with } b. Example: { document.write(Hello); document.write(Dolly); document.write(!); }

Javascript Comments a. Used to explain javascript and make it readable b. Starts with //. For example :: //ini merupakan bahagian heading or /*Ini merupakan Bahagian heading*/ c. Javascript comments are also used to disable the activation of the code. For example :: /* document.write(Haikal); document.write(Danial);*/

Variables a. Variables are the container for storing information. Example : x+y=z / z=x-2 / y=x+y b. Rules: 1. Case sensitive (y are not same as Y) 2. Must always begin with letter or underscore c. Examples: <script type=text/javascript> Var first=mike; document.write(My name is +first); document.write(<br/>); first=Mamat; document.write(My name is +first); </script>

Arithmetic Operators

a. = operator is used to assign value to javascript b. + operator is used to add the value together Operator Description + Addition Subtract * Multiplication / Division % Modulus ++ Increment -Decrement

Example x=y+2 x=y-2 x=y*2 x=y/2 x=y%2 x=y++ x=y--/x=--y

c. The operator + can also be used in strings for example Txt 1= what a vary; Txt 2=nice day; Txt 3=txt 1++txt 2; |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Caution! If we place to the number, the number will transform to be a string. For example: [Wrong] 5+5 the output will become 55 [True] 5+5 the output will become 10

Comparision & Logical Operator This is used for test weather true or false Given that x=5 Operator Description == Is equal to === != > < >= <= Is exactly equal to Is not equal Is greater than Is less than Is greater and equal to Is less and equal to

Example x==8 is false x==5 is true x===5 is true x===5 is false x!=8 is true x>3 is true x<20 is true x>=10 is false x<=0 is true

How to use it? a. Comparisons operators can be used in conditional statements to compare value and take action depending to the result

b. Example, if (age<18) document. write (Too Young!) Logical Operator Used to determine logic between variables and value. Given that x=6 and y=3 Operator Description && And || Or ! Not

Example (x<10&&y>1) is true (x==5||x==7) is false !(x==5) is true

Conditional Operator a. Used to assign a value to a variable based on some condition. b. Syntax:: Variablename= (condition)? value1:value2 c. Example:: greeting= (visitor==PRES)?Dear president:Dear;

Javascript if..else statements Conditional statements are used to perform different actions based on different condition

If statements a. Used to execute some code only if the specific condition is true. b. Syntax : if (condition) { The code will be executed if the condition is true } c. Example: if (x<=100) { document.write(the number is less than 100) }

Ifelse statements a. Used to execute some code if a condition is true and another code if the condition is not true b. Syntax: if (condition) { Code to be executed } else { Code to be execute }

ifelse ifelse statements a. Used to select one of several blocks of code to be executed. b. Syntax: if (condition) { Code to be executed } else if { Code to be executed } else { Code to be executed } c. Example: if (time<=12 && time>=0) { document.write (Good Morning!); } else if (time<=13 && time>=23) { document.write (Good Afternoon!); } else { document.write (Theres only 24 hours in a day!); }

Switch a. Select one of many block of codes to be executed b. Syntax: switch (n) { case1: Execute code block 1 break; case2: Execute code block 1 break; default: Code to be executed if answer is else than 1 and 2 } c. Example Redirection Script:
Var dateobj=new Date() Var today=dateobj.getDay() switch (today) { case1: window.location=Monday.html break; case2: window.location=Tuesday.html break; case3: window.location=Wednesday.html

break; case4: window.location=Thursday.html break; case5: window.location=Friday.html break; case6: window.location=Saturday.html break; case7: window.location=Sunday.html break; }

Javascript popup boxes Alert Boxes a. Used to make sure the information comes trough the user b. Example: alert (Contoh Ayat);

Confirm boxes a. Used if you want the user to verifying or accepting something b. If the user click ok the box returns true, if the user click cancel the result returns false c. Syntax: confirm (contoh text) d. Example: var ask= confirm(please choose); if (ask==true) { document.write (Saya cintakan kamoo); }

else { document.write (Ooh Tidakkkk!!!); }

Functions a. Used to keep the browser from executing a script when the page loads b. The code will be executed by an event or call to that function c. Syntax: function functionname (var1,var2,,var x) { Some code } d. Syntax (without parameter): function functionname () { Some code } e. The return statements is used to specify the value is return from the function

f. Function example: 1st example <html> <head> <script type=text/javascript> Function myfunction () { alert(Hello); } </script> <body> <form> <input type=buttononclick=myfunction()value=call function> </form> </body> </html> (By pressing button, the function will call the function)

2nd example (By pressing the button, function with arguments will be called ) <html> <head> <script type=text/javascript> Function myfunction () { alert(txt); } </script>

<body> <form> <input type=buttononclick=myfunction(hello)value=call function> </form> </body> </html>

3rd example (Function return a text) <html> <head> <script type=text/javascript> Function myfunction () { return(Hello, Have a nice day); } </script> <body> <script type=text/javascript> document.write(myfunction()) </script> </body> </html>

4th example (Function with arguments that returns value) <html>

<head> <script type=text/javascript> function product (a,b) { return(a*b); } </script> </head> <body> <script type=text/javascript> document.write (product 4,3); </script> </body> </html>

Javascript for Loop In Javascript, loop are used to execute some block of code a specific number of times or while specific condition is true There are two different type of loops: For:: Loops through a block of code a specific number of times While:: Loops through a block of code while a specific condition is true

For Loop a. Syntax for FOR LOOP for (var=start value);var<=end value;var+increament) b. Example <script type=text/javascript> var i=0; for (i=0;i<=10;i++) { document.write(The number is +i); } </script>

While Loop a. Syntax: while (var<=endvalue) { Code to be executed } b. Example: <script type=text/javascript> var i=0; while (i<=10) { document.write (The number is +i+<br/>);

i=i+1; } </script>

DoWhile Loop a. This loop always execute a block of code once and repeat it as long as the specific condition is true b. Syntax:: Do { Code is executed } while (var<=endvalue); c. Example:: <script type=text/javascript> var i=0; do { document.write (The number is +i+<br/>); i=i+1; } while (i<=10) </script>

Javascript Break and Continue a. There are two special statements that can be used inside the loop, breaks and continue. b. Break 1. Break command will break the loop and continue executing the loop that follows after the loops (if any) 2. Example::

<script type=text/javascript> var i=0; for(i=0;i<=10;i++) { if (i==3) { break; } document.write (The number is +i); } while (i<=10) </script> c. Continue 1. The continue command will break the current loop and continue with next value 2. Example:: <script type=text/javascript> var i=0; for (i=0;i<=10;i++) { if (i==3) { Continue; } document.write (The number is +i) } </script>

Javascript forin statement a. Syntax:: for (variable in object) { Code to be executed

} b. Example <script type=text/javascript> var x; var mycar=newArray(); mycars[0]=Saab; mycars[1]=Volvo; mycars[2]=BMW; for (x in mycars) { document.write (mycars[x]); } </script>

Javascript Events
Events: a. Events are the actions that can be detected by Javascript b. Every element on a webpage has certain events which can trigger javascript functions for example: A mouse click A web browser or an image loading Mousing over a hot spot on the web page Selecting an input box in an html form Submitting an HTML form A keystroke Onload and on Unload a. This events are triggered when the user enter or leaves the pages

b. Often used to check the visitors browser type and browsers version and load the proper version of webpage based on information c. Example for onload events: In this example the text "Page is loaded" will be displayed in the status bar:
<html> <head> <script type="text/javascript"> function load() { window.status="Page is loaded"; } </script> </head> <body onload="load()"> </body> </html>

d. Example for onUnload events: In this example an alert box will be displayed when the page is closed:
<body onunload="alert('The onunload event was triggered')"> </body>

onFocus , onBlur and onChange a. This events are often used in combination with validation of form field b. Example for onFocus In this example the background color of the input fields change when they get focus:
<html> <head> <script type="text/javascript"> function setStyle(x) { document.getElementById(x).style.background="yellow"; } </script> </head> <body> First name: <input type="text" onfocus="setStyle(this.id)" id="fname"> <br /> Last name: <input type="text" onfocus="setStyle(this.id)" id="lname">

</body> </html>

c. Example for onBlur In this example we will execute some JavaScript code when a user leaves an input field:
<html> <head> <script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value; document.getElementById("fname").value=x.toUpperCase(); } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()"> </body> </html>

d. Example for onChange In this example we will execute some JavaScript code when a user changes the content of an input field:
<html> <head> <script type="text/javascript"> function upperCase(x) { var y=document.getElementById(x).value; document.getElementById(x).value=y.toUpperCase(); } </script> </head> <body> Enter your name: <input type="text" id="fname" onchange="upperCase(this.id)"> </body> </html>

onSubmit a. This event is used to validate ALL form fields before submitting it. b. Example for onSubmit In this example an alert box will be displayed when the user clicks on the submit button:
<html> <head> <script type="text/javascript"> function welcome() { alert("Welcome " + document.forms["myform"]["fname"].value + "!") } </script> </head> <body> What is your name?<br /> <form name="myform" action="submit.htm" onSubmit="welcome()"> <input type="text" name="fname" size="20"> <input type="submit" value="Submit"> </form> </body> </html>

onMouseOver and onMouseOut a. These events are often used to create animated buttons. b. Example for onMouseOver In the following example we will display an alert box when the user moves the mouse pointer over the image:
<img src="image_w3default.gif" alt="W3Schools" onmouseover="alert('Visit W3Schools!')" />

The output of the code above will be:

c. Example for onmouseout

In the following example we will display an alert box when the user moves the mouse pointer away from the image:
<img src="image_w3default.gif" alt="W3Schools" onmouseout="alert('Visit W3Schools!')" />

d. Example for onmouseup In this example an alert box is displayed when the mouse button is released after clicking the picture:
<img src="image_w3default.gif" onmouseup="alert('You clicked the picture!')">

e. Example for onmousemove In the following example we will display an alert box when the user moves the mouse pointer over the image:
<img src="image_w3default.gif" alt="W3Schools" onmousemove="alert('Visit W3Schools!')" />

f. Example for onmousedown In this example an alert box is displayed when clicking on the picture:
<img src="image_w3default.gif" onmousedown="alert('You clicked the picture!')">

Others a. Onreset The onreset event occurs when the reset button in a form is clicked. In this example the form changes back to the default values and displays an alert box when the reset button is clicked:
<form onreset="alert('The form will be reset')"> Firstname: <input type="text" name="fname" value="John" /> <br /> Lastname: <input type="text" name="lname" /> <br /><br /> <input type="reset" value="Reset">

</form>

b. Onresize The onresize events occurs when a window or frame is resize In this example an alert box will be displayed when a user tries to resize the window:
<body onresize="alert('You have changed the size of the window')">

c. Onselect The onselect events occurs when text is selected in a text or text area field In this example an alert box will be displayed if some of the text is selected:
<form> Select text: <input type="text" value="Hello world!" onselect="alert('You have selected some of the text.')"> <br /><br /> Select text: <textarea cols="20" rows="5" onselect="alert('You have selected some of the text.')"> Hello world!</textarea> </form>

Hint: Select all+copy d. Onabort The onabort event occurs when loading of an images is aborted In this example we will call a function if the loading of the image is aborted:
<html> <head> <script type="text/javascript"> function abortImage() { alert('Error: Loading of the image was aborted'); } </script> </head> <body> <img src="image_w3default.gif" onabort="abortImage()"> </body> </html>

e. Ondblclick The ondblclick event occurs when an object gets double-clicked

In this example the second field changes according to the first field when you double-click on the button:
<html> <body> Field1: <input type="text" id="field1" value="Hello World!"> <br /> Field2: <input type="text" id="field2"> <br /><br /> Click the button below to copy the content of Field1 to Field2. <br /> <button ondblclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy Text</button> </body> </html>

f. Onerror event The onerror event is trigged when an error occurs loading a document or an image In this example an alert box will be displayed if an error occurs when loading an image:
<img src="image.gif" onerror="alert('The image could not be loaded.')">

g. onKeyUp event The onkeyup event occurs when a keyboard key is released When typing letters in the input field in the following example, the letters will change to uppercase (one by one):
<html> <head> <script type="text/javascript"> function upperCase(x) { var y=document.getElementById(x).value; document.getElementById(x).value=y.toUpperCase(); } </script> </head> <body> Enter your name: <input type="text" id="fname" onkeyup="upperCase(this.id)"> </body> </html>

Javascript TryCatch Statement


a. The trycatch statement allows us to test a block of code for error b. Syntax:
Try { //Run some code here } catch(err) { //Handle errors here

c. Example
<html> <head> <script type="text/javascript"> var txt=""

function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>

Javascript throw Statement


a. The throw statement allows you to create an exception b. Syntax:
throw(exception)

c. Example:
<html> <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"; } catch(er)

{ if(er=="Err1") alert("Error! The value is too high"); if(er == "Err2") alert("Error! The value is too low"); } </script> </body> </html>

Javascript The onerror Event


a. Using the onerror event is the old standard solution to catch errors in a web page b. Syntax:
onerror=handleErr function handleErr(msg,url,l) { //Handle the error here return true or false }

c. Example:
<html> <head> <script type="text/javascript"> onerror=handleErr; var txt=""; function handleErr(msg,url,l) {

txt="There was an error on this page.\n\n"; txt+="Error: " + msg + "\n"; txt+="URL: " + url + "\n"; txt+="Line: " + l + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); return true; } function message() { adddlert("Welcome guest!"); } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>

Javascript Special Characters


a. In javascript, we can add special characters to a text string by using the backslash sign

Javascript Objects Introduction


Object Oriented Programming

a. Javascript is an object oriented programming which allows you to define your own objects and make your own variable types Javascript string object: a. The string object is used to manipulate a stored piece of text b. Example 1: The following example uses the length property of the string object to find the length of a string

var txt="Hello world!"; document.write(txt.length);


The code above will result in the following output:

12

c. Example 2: The following example uses toUppercase() method of the String object to convert a string to uppercase var txt="Hello world!"; document.write(txt.toUpperCase()); The code above will result in the following output: HELLO WORLD!

The String Object The String object let's you work with text. Syntax for creating a String object: var myStr=new String(string); String Object Properties Property constructor length prototype String Object Methods Method anchor() big() blink() bold() charAt() charCodeAt() concat() fixed() fontcolor() fontsize() fromCharCode() indexOf() italics() lastIndexOf() link() match() replace() search() slice() small() split() strike() sub() substr() substring() sup() Description Creates an HTML anchor Displays a string in a big font Displays a blinking string Displays a string in bold Returns the character at a specified position Returns the Unicode of the character at a specified position Joins two or more strings Displays a string as teletype text Displays a string in a specified color Displays a string in a specified size Takes the specified Unicode values and returns a string Returns the position of the first occurrence of a specified string value in a string Displays a string in italic Returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string Displays a string as a hyperlink Searches for a specified value in a string Replaces some characters with some other characters in a string Searches a string for a specified value Extracts a part of a string and returns the extracted part in a new string Displays a string in a small font Splits a string into an array of strings Displays a string with a strikethrough Displays a string as subscript Extracts a specified number of characters in a string, from a start index Extracts the characters in a string between two specified indices Displays a string as superscript Description A reference to the function that created the object Returns the number of characters in a string Allows you to add properties and methods to the object

toLowerCase() toUpperCase() toSource() valueOf()

Displays a string in lowercase letters Displays a string in uppercase letters Represents the source code of an object Returns the primitive value of a String object

Javascript Date Object a. The date object is used to work with dates and times b. The following code will create a Date object called mydate Var myDate=new Date()

c. Example 1 (display clock): <html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); } function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body>

</html>

d. Example 2 (Get Todays Day) <html> <body> <script type="text/javascript"> var d=new Date(); var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; document.write("Today it is " + weekday[d.getDay()]); </script> </body> </html> e. Example 3(Return todays date and time) <html> <body> <script type="text/javascript"> document.write(Date()); </script> </body> </html>

b. Complete data object reference Date Object Properties Property constructor prototype Date Object Methods Method Date() getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCMonth() getUTCFullYear() getUTCHours() Description Returns today's date and time Returns the day of the month from a Date object (from 1-31) Returns the day of the week from a Date object (from 0-6) Returns the year, as a four-digit number, from a Date object Returns the hour of a Date object (from 0-23) Returns the milliseconds of a Date object (from 0-999) Returns the minutes of a Date object (from 0-59) Returns the month from a Date object (from 0-11) Returns the seconds of a Date object (from 0-59) Returns the number of milliseconds since midnight Jan 1, 1970 Returns the difference in minutes between local time and Greenwich Mean Time (GMT) Returns the day of the month from a Date object according to universal time (from 1-31) Returns the day of the week from a Date object according to universal time (from 0-6) Returns the month from a Date object according to universal time (from 0-11) Returns the four-digit year from a Date object according to universal time Returns the hour of a Date object according to universal time (from 0-23) Description Returns a reference to the Date function that created the object Allows you to add properties and methods to the object

getUTCMinutes() getUTCSeconds() getUTCMilliseconds() getYear() parse() setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime()

setUTCDate() setUTCMonth() setUTCFullYear() setUTCHours() setUTCMinutes() setUTCSeconds() setUTCMilliseconds() setYear() toDateString() toGMTString() toLocaleDateString() toLocaleTimeString()

Returns the minutes of a Date object according to universal time (from 0-59) Returns the seconds of a Date object according to universal time (from 0-59) Returns the milliseconds of a Date object according to universal time (from 0-999) Returns the year, as a two-digit or a three/four-digit number, depending on the browser. Use getFullYear() instead !! Takes a date string and returns the number of milliseconds since midnight of January 1, 1970 Sets the day of the month in a Date object (from 1-31) Sets the year in a Date object (four digits) Sets the hour in a Date object (from 0-23) Sets the milliseconds in a Date object (from 0-999) Set the minutes in a Date object (from 0-59) Sets the month in a Date object (from 0-11) Sets the seconds in a Date object (from 0-59) Calculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 Sets the day of the month in a Date object according to universal time (from 1-31) Sets the month in a Date object according to universal time (from 0-11) Sets the year in a Date object according to universal time (four digits) Sets the hour in a Date object according to universal time (from 0-23) Set the minutes in a Date object according to universal time (from 0-59) Set the seconds in a Date object according to universal time (from 0-59) Sets the milliseconds in a Date object according to universal time (from 0-999) Sets the year in the Date object (two or four digits). Use setFullYear() instead !! Returns the date portion of a Date object in readable form Converts a Date object, according to Greenwich time, to a string. Use toUTCString() instead !! Converts a Date object, according to local time, to a string and returns the date portion Converts a Date object, according to local time, to a string and

toLocaleString() toSource() toString() toTimeString() toUTCString() UTC() valueOf()

returns the time portion Converts a Date object, according to local time, to a string Represents the source code of an object Converts a Date object to a string Returns the time portion of a Date object in readable form Converts a Date object, according to universal time, to a string Takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time Returns the primitive value of a Date object

Javascript Array a. The array object is used to store multiple values in a single variable b. Syntax: var example=new Array(); c. To insert values into an array, just use : var example=new Array(); example[0]="Saab"; example[1]="Volvo"; example[2]="BMW";

d. To access an array, index number starts with 0: document.write(example[0]);


The output are: Saab

e. To modify value in an existing array, just add a new value to the array with specific index number: example[0]="Proton"; The output array 0 will become Proton

f. Example (Simple Array): <html> <body> <script type="text/javascript"> var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + "<br />"); } </script> </body> </html>

g. Example (For...In Array) <html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (x in mycars) { document.write(mycars[x] + "<br />"); } </script> </body> </html> h. Join two arrays concat()

<html> <body> <script type="text/javascript"> var arr = new Array(3); arr[0] = "Jani"; arr[1] = "Tove"; arr[2] = "Hege"; var arr2 = new Array(3); arr2[0] = "John"; arr2[1] = "Andy"; arr2[2] = "Wendy"; document.write(arr.concat(arr2)); </script> </body> </html>

Javascript Boolean Object The Boolean object is used to convert a non-Boolean value (true or false)

The following code creates a Boolean object called myBoolean:

var myBoolean=new Boolean();


Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string "false")! All the following lines of code create Boolean objects with an initial value of

false:

var var var var var var

myBoolean=new myBoolean=new myBoolean=new myBoolean=new myBoolean=new myBoolean=new

Boolean(); Boolean(0); Boolean(null); Boolean(""); Boolean(false); Boolean(NaN);

And all the following lines of code create Boolean objects with an initial value of true:

var var var var

myBoolean=new myBoolean=new myBoolean=new myBoolean=new

Boolean(true); Boolean("true"); Boolean("false"); Boolean("Richard");

Javascript Math Object a. The math object allows us to perform mathematical task b. Example: random() is used to return a random number between 0 and 1 <html> <body> <script type="text/javascript"> document.write(Math.random()); </script> </body>

</html>

Syntax for using properties/methods of Math: var pi_value=Math.PI; var sqrt_value=Math.sqrt(16); Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it. Math Object Properties Property E LN2 LN10 LOG2E LOG10E PI SQRT1_2 SQRT2 Description Returns Euler's constant (approx. 2.718) Returns the natural logarithm of 2 (approx. 0.693) Returns the natural logarithm of 10 (approx. 2.302) Returns the base-2 logarithm of E (approx. 1.442) Returns the base-10 logarithm of E (approx. 0.434) Returns PI (approx. 3.14159) Returns the square root of 1/2 (approx. 0.707) Returns the square root of 2 (approx. 1.414)

Math Object Methods


Method abs(x) acos(x) asin(x) atan(x) atan2(y,x) ceil(x) cos(x) Description Returns the absolute value of a number Returns the arccosine of a number Returns the arcsine of a number Returns the arctangent of x as a numeric value between PI/2 and PI/2 radians Returns the angle theta of an (x,y) point as a numeric value between -PI and PI radians Returns the value of a number rounded upwards to the nearest integer Returns the cosine of a number

exp(x) floor(x) log(x) max(x,y) min(x,y) pow(x,y) random() round(x) sin(x) sqrt(x) tan(x) toSource() valueOf()

Returns the value of Ex Returns the value of a number rounded downwards to the nearest integer Returns the natural logarithm (base E) of a number Returns the number with the highest value of x and y Returns the number with the lowest value of x and y Returns the value of x to the power of y Returns a random number between 0 and 1 Rounds a number to the nearest integer Returns the sine of a number Returns the square root of a number Returns the tangent of an angle Represents the source code of an object Returns the primitive value of a Math object

Javascript Browser Detection a. The Javascript navigator object contains information about visitors browser b. The javascript Navigator object contain all information about the visitors browser. There are two properties of navigator object which is: o appName: holds the name of the browser o appVersion: holds, among other things, the version of the browser

c. Example (Detect the visitors browser and browser version):

d. Example (More detail about the visitors browser):

e. Example(Alert User,depending on browser)

Javascript Cookies a. A Cookies is a variable that is stored on the visitors computer b. Examples of cookies: o Name of Cookies: The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next

time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie o Password Cookies: The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie o Data Cookies: The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie c. Name cookies example:

Javascript Form Validation a. Used to validate input data in HTML forms before sending off the content to the server b. Form data that typically are checked by the javascript is:

o has the user left required fields empty?

o has the user entered a valid e-mail address? o has the user entered a valid date? o has the user entered text in a numeric field?
c. Syntax:

d. Email validation example:

Javascript Animation a. With javascript we can create animated images b. Example:

Javascript Images Map a. An image-map is an image with clickable regions b. Example(Simple HTML Image Map):

Javascript Images Map a. With javascript, it is possible to execute some code NOT immediately after a function is called, but after a specified time interval. This is called timing events.

b. It is very easy to time events in Javascript. The two key methods that are used are: 1. setTimeout() executes a some code time in the future Syntax: var t=setTimeout(javascript statement,milliseconds); 2. clearTimeout() cancels the setTimeout() Syntax: clearTimeout(setTimeout_variable) c. Example(Simple Timing):

Anda mungkin juga menyukai