Академический Документы
Профессиональный Документы
Культура Документы
Atul Kahate
akahate@gmail.com
What is JavaScript?
Designed to add interactivity to HTML pages Scripting language (Lightweight programming language) Embedded directly in HTML pages Interpreted language Open software (Free) Supported by all major browsers, like Netscape and Internet Explorer
JavaScript 2
NO!
Java and JavaScript are two completely different languages! Java (developed by Sun Microsystems) is a powerful and very complex programming language - in the same category as C and C++
JavaScript 3
JavaScript Capabilities
Programming tool - Scripting language with a very simple syntax Dynamic text into an HTML page - Example: document.write("<h1>" + name + "</h1>") Reacting to events - Execute when something happens, like when a page has finished loading or when a user clicks on an HTML element Read and write HTML elements - A JavaScript can read and change the content of an HTML element Validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing
JavaScript 4
Simple Example
<html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html>
JavaScript 5
Scripts in a page will be executed immediately while the page loads into the browser This is not always what we want Sometimes we want to execute a script when a page loads, other times when a user triggers an event
JavaScript 7
Scripts to be executed when they are called, or when an event is triggered, go in the head section When we place a script in the head section, we will ensure that the script is loaded before anyone uses it
JavaScript
Scripts to be executed when the page loads go in the body section When we place a script in the body section it generates the content of the page
JavaScript
We can place an unlimited number of scripts in our document, so we can have scripts in both the body and the head section.
JavaScript
10
External JavaScript
<html> <head> </head> <body> <script src="xxx.js"></script> </body> </html>
JavaScript 11
</body> </html>
JavaScript
12
<script type="text/javascript"> document.write("This message is written when the page loads") </script>
</body> </html>
JavaScript
13
JavaScript Variables
Syntaxes
Variable names are case sensitive They must begin with a letter or the underscore character var strname = some value strname = some value
var strname = Ram" strname = Ram"
JavaScript 14
Examples
Variables Scope
Local variables
When you declare a variable within a function, the variable can only be accessed within that function When you exit the function, the variable is destroyed If you declare a variable outside a function, all the functions on your page can access it The lifetime of these variables starts when they are declared, and ends when the page is closed
JavaScript 15
Global variables
JavaScript Operators
Arithmetic
Assignment
Comparison
Logical
String joining
JavaScript 16
JavaScript Functions
A function contains some code that will be executed by an event or a call to that function A function is a set of statements You can reuse functions within the same script, or in other documents You define functions at the beginning of a file (in the head section), and call them later in the document Example
alert("This is a message")
JavaScript
17
Function Syntaxes
sum=total(2,3)
JavaScript 19
if statement - use this statement if you want to execute a set of code when a condition is true if...else statement - use this statement if you want to select one of two sets of lines to execute switch statement - use this statement if you want to select one of many sets of lines to execute
JavaScript 20
if Example
<script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script>
JavaScript 21
if-else Example
<script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date() var time = d.getHours()
JavaScript
22
Statements, II
switch (expression) { case label : statement; break; case label : statement; break; ... default : statement; }
switch Example
<script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: Case 0: document.write("Super Weekend") break default: document.write("I'm looking forward to this weekend!") } </script> JavaScript 25
Conditional Operator
Syntax
variablename=(condition)?value1:value2
Example
JavaScript
26
JavaScript Loops
while - loops through a block of code while a condition is true do...while - loops through a block of code once, and then repeats the loop while a condition is true for - run statements a specified number of times
JavaScript 27
for Example
html> <body> <script type="text/javascript"> for (i = 0; i <= 5; i++) { document.write("The number is " + i) document.write("<br>") } </script> <p>Explanation:</p> <p>The for loop sets <b>i</b> equal to 0.</p> <p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html>
JavaScript
28
while Example
<html> <body> <script type="text/javascript"> i=0 while (i <= 5) { document.write("The number is " + i) document.write("<br>") i++ } </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html>
JavaScript
29
do-while Example
<html> <body> <script type="text/javascript"> i=0 do { document.write("The number is " + i) document.write("<br>") i++ } while (i <= 5) </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>The loop will run</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> </body> </html>
JavaScript
30
JavaScript Objects
JavaScript
31
Arrays
Syntax
OR
JavaScript
33
Boolean Object
The Boolean object is an object wrapper for a Boolean value and it is used to convert a non-Boolean value to a Boolean value Example: Initialize to null
JavaScript
34
Date Object 1
<html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(".") document.write(d.getFullYear()) </script> </body> </html>
JavaScript 35
Date Object 2
<html> <body> <script type="text/javascript"> var d = new Date() d.setFullYear("1990") document.write(d) </script> </body> </html>
JavaScript 36
Date Object 3
<html> <body> <script type="text/javascript"> var d=new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday"," Friday","Saturday") document.write("Today is " + weekday[d.getDay()]) </script> </body> </html>
JavaScript 37
Date Object 4
<html> <body> <script type="text/javascript"> var d=new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturda y") var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") document.write(weekday[d.getDay()] + " ") document.write(monthname[d.getMonth()] + " ") document.write(d.getFullYear()) </script> </body> </html>
JavaScript 38
The built-in Math object includes mathematical constants and functions We do not need to create the Math object before using it Example
r_number=Math.round(8.6) r_number=Math.random()
JavaScript 40
Math Example 1
<html> <body> <script type="text/javascript"> document.write(Math.round(7.25)) </script> </body> </html>
JavaScript 41
Math Example 2
<html> <body> <script type="text/javascript"> document.write(Math.max(2,4)) </script> </body> </html>
JavaScript 42
log(x)
max(x,y) min(x,y) pow(x,y) random()
round(x)
sin(x) sqrt(x) tan(x)
JavaScript
44
JavaScript Guidelines
Case sensitive Needs matching closing tags Ignores extra spaces Special characters need to be prefixed with a backslash (\)
Comments: // and /* */
JavaScript 45
HTML DOM
The HTML DOM is a programming interface for HTML documents The HTML DOM defines how you can access and change the content of HTML documents DOM stands for the Document Object Model The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML objects
JavaScript 47
Because we need an easy and standard way to access the content of HTML documents, that can be used by all types of browsers, and all types of programming languages
e.g. JavaScript can use DOM APIs to access contents of HTML documents
The HTML DOM defines how to access HTML elements, and how to change, add, or delete their content, attributes and styles
JavaScript 48
DOM Parts
DOM Core
Allows parsing of HTML documents
XML DOM
Allows parsing of XML documents
(X)HTML DOM
Allows parsing of XHTML documents
DOM Example
<html> <head> <script type="text/javascript"> function ChangeColor() { document.body.bgColor="yellow" } </script> </head> <body onclick="ChangeColor()"> Click on this document! </body> </html> Result: After the document is displayed in the browser window; if the user clicks in the browser, the background color would change to yellow. JavaScript 50
Document Objects
Document object is the parent of all the other objects in an HTML document Document.body object represents the <body> element of the HTML document Meaning: Document object is the parent of the body object, and the body object is a child of the document object.
JavaScript 51
Object Properties/Attributes
HTML document objects can have properties (also called attributes) e.g. document.body.bgColor property defines the background color of the body object. The statement document.body.bgColor="yellow sets the background color of the HTML document to yellow
JavaScript 52
Object Events
HTML document objects can respond to events The onclick="ChangeColor()" defines an action to take place when the user clicks on the document
JavaScript
53
JavaScript
54
Button Object
The button object represents a push button on an HTML form For each instance of an HTML <input type="button"> tag on an HTML form, a Button object is created The Button objects are stored in the elements array of the corresponding form We can access a Button object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute
JavaScript 55
Button Example
<html> <head> <script type="text/javascript"> function show_alert() { alert("Hello World!") document.all("myButton").focus() } </script> </head> <body> <form> <input type="button" value="Click me!" name="myButton" onClick="show_alert()" /> </form> </body> </html>
JavaScript
56
Checkbox Object
The Checkbox object represents a checkbox on an HTML form For each instance of an HTML <input type="checkbox"> tag on an HTML form, a Checkbox object is created All Checkbox objects are stored in the elements array of the corresponding form We can access a Checkbox object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute
JavaScript 57
Checkbox Example
<html> <head> <script type="text/javascript"> function check() { coffee=document.forms[0].coffee answer=document.forms[0].answer txt="" for (i=0;i<coffee.length;++ i) { if (coffee[i].checked) txt=txt + coffee[i].value + " " } answer.value="You ordered a coffee with " + txt } </script> </head> <body> <form> How would you like your coffee?<br /><br /> <input type="checkbox" name="coffee" value="cream">With cream<br /> <input type="checkbox" name="coffee" value="sugar">With sugar<br /> <br /> <input type="button" name="test" onclick="check()" value="Send order"> <br /><br /> <input type="text" name="answer" size="50"> </form> </body> </html>
JavaScript
58
Document Object
The Document object is used to access all elements in a page Contains many collections, properties, methods, and events
JavaScript
59
Event Object
Represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons Is available only during an event - that is, you can use it in event handlers but not in other code In VBScript, you must access the event object through the window object
JavaScript 60
Event Example 1
<html> <head> <script type="text/javascript"> function whichButton() { if (event.button==1) alert("You clicked the left mouse button!") else alert("You clicked the right mouse button!") } </script> </head> <body onmousedown="whichButton()"> <p>Click in the document. An alert box will alert which mouse button you clicked.</p> </body> </html>
JavaScript 61
Event Example 2
<html> <head> <script type="text/javascript"> function isKeyPressed() { if (event.shiftKey==1) alert("The shift key was pressed!") else alert("The shift key was NOT pressed!") } </script> </head> <body onmousedown="isKeyPressed()"> <p>Click somewhere in the document. An alert box will tell you if you pressed the shift key or not.</p> </body> </html> JavaScript 62
Form Object
Forms are used to prompt users for input We may use form elements such as text fields, radio buttons, checkboxes and selection lists The input data is normally posted to a server for processing
JavaScript 63
Form Example
<html> <head> <script type="text/javascript"> function formSubmit() { document.forms.myForm.submit() } </script> </head> <body> <form name="myForm" action="js_form_action.asp" method="get"> Firstname: <input type="text" name="firstname" size="20"><br /> Lastname: <input type="text" name="lastname" size="20"><br /><br /> <input type="button" onclick="formSubmit()" value="Submit"> </form> </body> </html> JavaScript 64
Form Example 2
<html> <head> <script type="text/javascript"> function check(browser) { document.forms[0].answer.value=browser } </script> </head> <body> <form> Select which browser is your favorite:<br /><br /> <input type="radio" name="browser" onclick="check(this.value)" value="Internet Explorer">Internet Explorer<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Netscape">Netscape<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Opera">Opera<br /> <br /> <input type="text" name="answer" size="20"> </form> </body> </html>
JavaScript
69
Option Object 1
For each instance of an HTML <option> tag in a selection list on a form, an Option object is created An option in a selection list can be created either with the HTML <option> tag
<option>Wolksvagen</option>
OR
Using the option constructor and assign it to an index of the relevant Select object
document.myForm.cartypes[3]=new Option("Wolksvagen")
JavaScript 70
Option Object 2
To specify a value to be returned to the server when an option is selected and the form submitted
document.myForm.cartypes[3]=new Option("Wolksvagen")
document.myForm.cartypes[3]=new Option("Wolksvagen")
JavaScript 71
Option Example - 1
<html> <head> <script type="text/javascript"> function makeDisable() { var x=document.getElementById("mySelect") x.disabled=true } function makeEnable() { var x=document.getElementById("mySelect") x.disabled=false } </script> </head>
<body> <form> <select id="mySelect"> <option>Apple</option> <option>Grape</option> <option>Orange</option> <script type="text/javascript"> document.forms[0].mySelect[3]=new Option("Mango") </script>
</select> <input type="button" onclick="makeDisable()" value="Disable list"> <input type="button" onclick="makeEnable()" value="Enable list"> </form> </body>
</html>
JavaScript
72
Option Example - 2
<html> <head> <script type="text/javascript"> function getText() { var x=document.getElementById("mySelect") alert(x.options[x.selectedIndex].text) } </script> </head>
<body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="getText()" value="Show text of selected fruit"> </form> </body> </html> JavaScript 73
Option Example - 3
html> <head> <script type="text/javascript"> function getIndex() { var x=document.getElementById("mySelect") alert(x.options[x.selectedIndex].index) } </script> </head>
<body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="getIndex()" value="Show index of selected fruit"> </form> </body> JavaScript 74
Option Example - 4
<html> <head> <script type="text/javascript"> function changeText() { var x=document.getElementById("mySelect") x.options[x.selectedIndex].text="Melon" } </script> </head>
<body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="changeText()" value="Change text of selected fruit"> </form> </body> </html> JavaScript 75
Option Example - 5
<html> <head> <script type="text/javascript"> function changeText() { var x=document.getElementById("mySelect") x.options[x.selectedIndex].text="Melon" } </script> </head>
<body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="changeText()" value="Change text of selected fruit"> </form> </body> </html> JavaScript 76
Pop up boxes
Three types
Alert Box
Syntax: alert (Your message) A pop-up screen appears User needs to select OK to proceed Syntax: confirm (Your message) User needs to select OK or Cancel
Confirm Box
Prompt Box
JavaScript
79
Exercises
JavaScript
80
Problem 1
Requirement: Allow the user to enter some text in a textbox and validate to ensure that it is not empty.
JavaScript
81
Solution 1
<html> <head> <SCRIPT> function validateForm(form) { //This is the name of the function if (form.FIELD1.value == "") { //This checks to make sure the field is not empty alert("This field is empty."); //Informs user of empty field form.FIELD1.focus( ); //This focuses the cursor on the empty field return false; //This prevents the form from being submitted } // you may copy the above 5 lines for each form field you wish to validate // Replace the text "FIELD1" with the name you wish to call the field } </SCRIPT> </head> <body> <FORM METHOD="POST" ACTION="" onSubmit="return validateForm(this)"> <INPUT TYPE="TEXT" NAME="FIELD1" SIZE=10 MAXLENGTH=60 VALUE=""> <INPUT TYPE="SUBMIT" NAME="ACTION" value="SUBMIT"> </FORM>
JavaScript
82
Problem
Allow the user to enter two numbers on the screen and show the result of multiplying them
JavaScript
83
Solution
<html> <head> <title>A Simple Calculator</title> <script type="text/javascript"> function multiplyTheFields () { var number_one = document.the_form.field_one.value; var number_two = document.the_form.field_two.value; var product = number_one * number_two;
</script> </head> <body> <form name = "the_form"> Number 1: <input type = "text" name = "field_one"> <br> Number 2: <input type = "text" name = "field_two"> <br> <a href = "#" onClick = "multiplyTheFields (); return false;">Multiply them! </a> </form> </body> </html>
JavaScript
84
Problem
Modify the above example so that the result of multiplication is not displayed in a separate alert box. Instead, have it displayed in a third text box on the same screen.
JavaScript
85
Solution
<html> <head> <title>A Simple Calculator</title> <script type="text/javascript"> function multiplyTheFields () { var number_one = document.the_form.field_one.value; var number_two = document.the_form.field_two.value; var product = number_one * number_two; document.the_form.the_answer.value = product; } </script> </head> <body> <form name = "the_form"> Number 1: <input type = "text" name = "field_one"> <br> Number 2: <input type = "text" name = "field_two"> <br> The Product: <input type = "text" name = "the_answer"> <br> <a href = "#" onClick = "multiplyTheFields (); return false;">Multiply them! </a> </form> </body> </html>
JavaScript
86
Problem
Create an HTML form and mandate that the user has entered data in all the fields before the form can be submitted.
JavaScript
87
Problem 2
Display a heading and a URL on the screen. When the user moves the mouse over the URL, display a pop up box.
JavaScript
88
Solution 2
<HTML> <TITLE> Example Event Handler </TITLE> <BODY> <H1>Example Event Handler</H1> <P><A HREF = "http://www.test.com" onMouseOver = "alert ('Link to the home page.')">Move the mouse over this link and a popup window appears.</A></P> </BODY> </HTML>
JavaScript 89
Problem 3
In the same example, count and display the number of times the user has moved the mouse over the URL.
JavaScript
90
Solution 3
<HTML> <HEAD> <TITLE> Event Handler with Multiple Statements</TITLE> <SCRIPT LANGUAGE = "JavaScript"> count = 0 </SCRIPT> </HEAD> <BODY> <H1>Event Handler with Multiple Statements</H1> <P><A HREF = "http://www.test.com" onMouseOver = '++count; alert ("Count = "+count+"")'>Displays the count.</A></P> </BODY> </HTML>
JavaScript 91
Problem 4
Display a welcome message when the user views a Web page and also when the user closes the browser window.
JavaScript
92
Solution 4
<HTML> <HEAD> <TITLE> Handling Load Events</TITLE> </HEAD> <BODY onLoad = "alert ('Hello!')" onUnload = "alert ('Bye bye!')"> <H1>Handling load events in a content document</H1> <P>This is a simple document</P> </BODY> </HTML>
JavaScript 93
Problem 5
Accept distance from the user in miles and convert it into kilometers and display the result on the screen.
JavaScript
94
Solution 5
<html> <head> <title>JavaScript Example: Distance Converter</title> </head> <body> <h3>Distance Converter:</h3> <form action="javascript:void();"> <p>Distance in miles: <input name="miles" type="text" size="5"></p> <p> <input type="button" value="Convert to kilometres" onclick= "kilometres = Math.round( form.miles.value * 1.6667 * 100 ) / 100; window.alert( 'Distance in kilometres is ' + kilometres );"> </p> </form> </body> </html>
JavaScript
95
Problem 6
Accept a number from the user and display the result as to whether it is even or odd.
JavaScript
96
Solution 6
<html> <head> <title>Find out if a number is even or odd</title> <script> function EvenOrOdd (num) { if (num.value %2 == 0) return 'Even'; else return 'Odd'; } </script> </head> <body> <h3>Even or odd?</h3> <form action="javascript:void();"> <p>Please enter a number: <input name="num" type="text" size="5"></p> <p> <input type="button" value="Is this even or odd?" onclick= "window.alert ('Number is: ' + EvenOrOdd (num));"> </p> </form> </body> </html>
JavaScript
97
Problem 7
JavaScript
98
Solution 7
<html> <head> <title>Find out the factorial of a number</title> <script language="JavaScript"> function compute(n) { if (validate(n)) { return factorial(n); } else { return "-invalid-"; } } function validate(n) { if (n < 0 || n > 25) { alert("Input must be between 1 and 25."); return false; } else { return true; } } function factorial(n) { var result = 1; for (var i = 2; i <= n; i++) { result *= i } return result; } </script> </head> <body> <H2> Factorial Example </H2> <form name="myForm" method="post" action=""> <p>Enter a number: <input type="text" name="myInput"> <input type="button" name="computeButton" value="Compute!" onclick="with (document.myForm) { result.value=compute(myInput.value) }"> </p>
JavaScript
99
Problem
Have the user enter two numbers on the screen. Swap them if the first is greater than the second.
JavaScript
100
Solution
<html> <head> <script> function swap() { var form=document.switchtext; var t1=form.text1; var v1=parseFloat(t1.value); var t2=form.text2; var v2=parseFloat(t2.value); if (v1 > v2) { var temp = t1.value; t1.value = t2.value; t2.value=temp; } } </script> </head> <body> Please insert only numeric values.<BR /> <form name="switchtext"> <input type="text" name="text1"> <BR /> <input type="text" name="text2"> <BR /> <input type="button" name="switch" value="Switch Text" onclick=swap()> </form> </body> </html>
JavaScript
101
Problem
Ask the user to enter user name and password. The password should be accepted once more for verification. Ensure that the verification is successful.
JavaScript
102
Solution
<html> <head> <!-- Password check --> <script type = "text/javascript"> function validForm(passForm) { if (passForm.passwd1.value == "") { alert("you must enter a password"); passForm.passwd1.focus(); return false; } if (passForm.passwd1.value != passForm.passwd2.value) { alert("Entered passwords did not match"); passForm.passwd1.focus(); passForm.passwd1.select(); return false; } return true; } </script> </head> <body> <form name="form" action="http://www.js-examples.com/" onsubmit="return validForm(this)"> Your name: <input type="text" name="textfield"> <BR> Choose a password: <input type="password" name="passwd1" value="abc123"> <BR> Verify password: <input type="password" name="passwd2" value="abc123"> <BR> <input type="submit" value="Submit"> <input type="reset"> </form> </body> </html>
JavaScript
103
Problem
Create an HTML form to accept first and last names, mailing address, day time phone number, evening time phone number, and email ID of the user. Perform appropriate validations.
JavaScript
104
Solution
<html> <head> <!-- Form validations --> <script language="javascript"> function verify(form) { for (i=0; i<form.elements.length; i++ ) { form.elements[i].focus(); if ((form.elements[i].type=="text" || form.elements[i].type=="textarea") && form.elements[i].value == "") { // having this alert not commented out causes the focus to not work correctly... //alert("Please fill out all fields."); return; } } // if all else is validated - then validiate the email... everify(form); } function everify(form) { if (form.email.value == "" || form.email.value.indexOf('@') == -1 || form.email.value.indexOf('.') == -1 || form.email.value.length<6) { // same for this alert and the focus issue. //alert("Not a valid e-mail address!"); form.email.focus(); return; } // uncomment this to submit the form when all validated. // form.submit(); } </script> </head> <body>
JavaScript
105
JavaScript
106
JavaScript
107
JavaScript
108
JavaScript
109
Thank you!
Questions and Comments Welcome!