Upload
dulcie-oneal
View
226
Download
0
Embed Size (px)
DESCRIPTION
3 Of 48 What Can JavaScript do? JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies زبانهای برنامه سازی وب
Citation preview
JavaScript
محمد احمدی نیا[email protected]
2 Of 48
What is JavaScript?
JavaScript was designed to add interactivity to HTML pages A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts
execute without preliminary compilation) Everyone can use JavaScript without purchasing a license
زبانهای برنامه سازی وب
3 Of 48
What Can JavaScript do?
JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies
زبانهای برنامه سازی وب
4 Of 48
JavaScript How To
The HTML <script> tag is used to insert a JavaScript into an HTML page.
زبانهای برنامه سازی وب
5 Of 48
JavaScript Where To
JavaScript in <body><html><body>
<script type="text/javascript">document.write("<p>" + Date() + "</p>");
</script> </body> </html>
زبانهای برنامه سازی وب
6 Of 48
JavaScript Where To
JavaScript in <head><html><head><script type="text/javascript">function displayDate() {document.getElementById("demo").innerHTML=Date();}</script></head><body><p id="demo"></p><input type="button" onclick="displayDate()“ value=“DisplayDate”></body></html>
زبانهای برنامه سازی وب
7 Of 48
JavaScript Where To
Using an External JavaScript External JavaScript files often contain code to be used
on several different web pages. External JavaScript files have the file extension .js.
<html><head><script type="text/javascript" src=“menu.js"></script></head><body></body></html>
زبانهای برنامه سازی وب
8 Of 48
JavaScript Statements
JavaScript is Case Sensitive A JavaScript statement is a command to a browser
This JavaScript statement tells the browser to write "Hello Dolly" to the web page:document.write("Hello Dolly");
The semicolon at the end of each executable statement is optional
زبانهای برنامه سازی وب
9 Of 48
JavaScript Comments
Single line comments start with //. Multi line comments start with /* and end with */.
<script type="text/javascript"> // Write a heading document.write("<h1>This is a heading</h1>");
/* The code below will write one heading and two paragraphs */ document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>");</script>
زبانهای برنامه سازی وب
10 Of 48
JavaScript Variables
Variables are "containers" for storing information. Variable names are case sensitive (y and Y are two different
variables) Variable names must begin with a letter, the $ character, or the
underscore character Declaring (Creating) JavaScript Variables
You declare JavaScript variables with the var keyword:var x;var carname=“volvo”;
When you assign a text value to a variable, use quotes around the value.
زبانهای برنامه سازی وب
11 Of 48
Arithmetic Operators
Operator Description Example Result
+ Addition x=y+2 x=7 y=5
- Subtraction x=y-2 x=3 y=5
* Multiplication x=y*2 x=10 y=5
/ Division x=y/2 x=2.5 y=5
% Modulus x=y%2 x=1 y=5
++ Increment x=++y x=6 y=6
x=y++ x=5 y=6
-- Decrement x=--y x=4 y=4
x=y-- x=5 y=4
زبانهای برنامه سازی وب
12 Of 48
Assignment Operators
Operator Example Same As Result= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
زبانهای برنامه سازی وب
13 Of 48
Comparison Operators
Operator Description Example== is equal to x==8 is false
x==5 is true
=== is exactly equal to (value and type)
x===5 is truex==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true
زبانهای برنامه سازی وب
Given that x=5, the table below explains the comparison operators:
14 Of 48
Logical Operators
Operator Description Example&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
زبانهای برنامه سازی وب
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
15 Of 48
Conditional Statements
If...else Statementif (condition) { code to be executed if condition is true }else { code to be executed if condition is not true }
زبانهای برنامه سازی وب
16 Of 48
Conditional Statements
The JavaScript Switch Statement switch(n){case 1: execute code block 1 break;case 2: execute code block 2 break;default: code to be executed if n is different from case 1 and 2}
زبانهای برنامه سازی وب
17 Of 48
Popup Boxes Alert Box
alert("sometext");<html><head><script type="text/javascript">function show_alert(){alert(" Starting the virus installation ");}</script></head><body><input type="button" onclick="show_alert()" value="Show alert" /></body></html>
زبانهای برنامه سازی وب
18 Of 48
Popup Boxes
Confirm Box A confirm box is often used if you want the user to
verify or accept something. returns true or false confirm("sometext");
زبانهای برنامه سازی وب
19 Of 48
Popup Boxes(Confirm Box)
<html><head><script type="text/javascript">function show_confirm(){var r=confirm(“Are you ready …");if (r==true) { alert("You pressed OK!"); }else { alert("You pressed Cancel!"); }}</script></head>
زبانهای برنامه سازی وب
20 Of 48
Popup Boxes
Prompt Box A prompt box is often used if you want the user to
input a value before entering a page. prompt("sometext","defaultvalue"); the user will have to click either "OK" or "Cancel“
returns value entered or null if no value was entered
زبانهای برنامه سازی وب
21 Of 48
Popup Boxes
<html><head><script type="text/javascript">function show_prompt(){var num=prompt(“Enter the number of viruses to inestall",“10");if (num!=null && num!="") { document.write("<p> the number of viruses you selected is " + num+ “</p>"); }}</script></head>
زبانهای برنامه سازی وب
22 Of 48
JavaScript Functions
A function will be executed by an event or by a call to the function.
How to Define a Functionfunction functionname(var1,var2,...,varX){some code}
زبانهای برنامه سازی وب
23 Of 48
JavaScript Functions The return Statement
<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>
زبانهای برنامه سازی وب
24 Of 48
JavaScript Loops The for Loop
The for loop is used when you know in advance how many times the script should run.for (variable=startvalue;variable<=endvalue;variable=variable+increment){code to be executed}
var i=0;for (i=0;i<=5;i++){document.write("The number is " + i);document.write("<br />");}
زبانهای برنامه سازی وب
25 Of 48
JavaScript Loops The while loop
The while loop loops through a block of code while a specified condition is true.
while (variable<=endvalue) { code to be executed }
var i=0;while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; }
زبانهای برنامه سازی وب
26 Of 48
JavaScript Loops
The do...while Loopdo { code to be executed }while (variable<=endvalue);
زبانهای برنامه سازی وب
27 Of 48
JavaScript Events
Events are actions that can be detected by JavaScript. Examples of events:
A mouse click A web page or an image loading Mousing over a hot spot on the web page Submitting an HTML form A keystroke …
Events are normally used in combination with functions, and the function will not be executed before the event occurs!
زبانهای برنامه سازی وب
28 Of 48
JavaScript Events
onLoad and onUnload The onLoad and onUnload events are triggered when the user
enters or leaves the page. onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields.
<input type="text" size="30" id="email" onchange="checkEmail()" /> onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
زبانهای برنامه سازی وب
29 Of 48
JavaScript EventsAttribute Descriptiononblur The event occurs when an element loses focus
onchange The event occurs when the content of an element, the selection, or the checked state have changed
onclick The event occurs when the user clicks on an elementondblclick The event occurs when the user double-clicks on an elementonfocus The event occurs when an element gets focusonkeydown The event occurs when the user is pressing a key or holding down a keyonkeypress The event occurs when the user is pressing a key or holding down a keyonkeyup The event occurs when a keyboard key is releasedonload The event occurs when an object has been loadedonmousedown The event occurs when a user presses a mouse button over an elementonmousemove The event occurs when a user moves the mouse pointer over an elementonmouseover The event occurs when a user mouse over an elementonmouseout The event occurs when a user moves the mouse pointer out of an elementonmouseup The event occurs when a user releases a mouse button over an elementonselect The event occurs after some text has been selected in an elementonsubmit
زبانهای برنامه سازی وب
30 Of 48
Special Characters
In JavaScript you can add special characters to a text string by using the backslash sign.document.write("We are the so-called \"Vikings\" from the north.“);
زبانهای برنامه سازی وب
Code Outputs\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
31 Of 48
Objects Based Programming
JavaScript is an Object Based Programming language. Properties
Are the values associated with an object.document.write(txt.length);
Methods Are the actions that can be performed on objects.document.write(str.toUpperCase());
زبانهای برنامه سازی وب
32 Of 48
String object
The String object is used to manipulate a stored piece of text.
var txt="Hello world!";document.write(txt.length); 12document.write(txt.toUpperCase()); HELLO WORLD!
زبانهای برنامه سازی وب
33 Of 48
Date Object
The Date object is used to work with dates and times. ways of instantiating a date
new Date() // current date and timenew Date(milliseconds) //milliseconds since 1970/01/01new Date(dateString)new Date(year, month, day, hours, minutes, seconds, milliseconds)
var today = new Date()var d1 = new Date("October 13, 1975 11:13:00")var d2 = new Date(79,5,24)var d3 = new Date(79,5,24,11,33,0)
زبانهای برنامه سازی وب
34 Of 48
Date ObjectMethod DescriptiongetDate() Returns the day of the month (from 1-31)getDay() Returns the day of the week (from 0-6)getFullYear() Returns the year (four digits)getHours() Returns the hour (from 0-23)getMilliseconds() Returns the milliseconds (from 0-999)getMinutes() Returns the minutes (from 0-59)getMonth() Returns the month (from 0-11)getSeconds() Returns the seconds (from 0-59)setDate() Sets the day of the month (from 1-31)setFullYear() Sets the year (four digits)setHours() Sets the hour (from 0-23)setMilliseconds() Sets the milliseconds (from 0-999)setMinutes() Set the minutes (from 0-59)setMonth() Sets the month (from 0-11)setSeconds() Sets the seconds (from 0-59)
زبانهای برنامه سازی وب
35 Of 48
Array Object The Array object is used to store multiple values in a single
variable. Create an Array
1. var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab"; // argument to control array's size)myCars[1]="Volvo";
2. var myCars=new Array("Saab","Volvo","BMW"); // condensed array
3. var myCars=["Saab","Volvo","BMW"]; // literal array Access an Array
document.write(myCars[0]); // The index number starts at 0
زبانهای برنامه سازی وب
36 Of 48
Timing Events
With JavaScript, it is possible to execute some code after a specified time-interval. setTimeout() - executes a code some time in the future
var t=setTimeout("javascript statement",milliseconds);<script type="text/javascript">
function timeMsg() {var t=setTimeout("alertMsg()",3000);}function alertMsg() {alert("Hello");}</script>
زبانهای برنامه سازی وب
37 Of 48
Timing Events
clearTimeout() - cancels the setTimeout()
زبانهای برنامه سازی وب
38 Of 48
DOM(Document Object Model)
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
The DOM presents an HTML document as a tree-structure.
The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.
زبانهای برنامه سازی وب
39 Of 48
DOM Nodes
In the DOM, everything in an HTML document is a node. The entire document is a document node Every HTML element is an element node The text in the HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes
زبانهای برنامه سازی وب
40 Of 48
DOM Node Tree
The HTML DOM views an HTML document as a node-tree.
زبانهای برنامه سازی وب
41 Of 48 زبانهای برنامه سازی وب
window
plugins
document
document
document
frames
history
navigator
location
event
screen
all
collections
anchorsappletsbody
embeds
imagesformsfilters
linksplugins
styleSheetsscripts
objects
42 Of 48
DOM Properties and Methods
Properties and methods define the programming interface of the HTML DOM. x.innerHTML – a property of x x.getElementById(id) – a method of x
زبانهای برنامه سازی وب
43 Of 48
Accessing Nodes You can access a node in two ways:
By using the getElementById() method returns the element with the specified ID
node.getElementById("id");
By using the getElementsByTagName() method returns all elements with a specified tag name
node.getElementsByTagName("tagname");
x=document.getElementsByTagName("p"); selects all <p> nodes in a node-list.The nodes can be accessed by index. y=x[1];
زبانهای برنامه سازی وب
44 Of 48
DOM - Change HTML Elements change the inner content and attributes of HTML
elements
<script type="text/javascript"> document.body.bgColor=“red";</script>
زبانهای برنامه سازی وب
45 Of 48
DOM - Change HTML Elements
modify the content of an element with innerHTML property <head><script type="text/javascript"> function ChangeText(){ document.getElementById("p1").innerHTML="New text!"; }</script></head><body> <p id="p1">Hello world!</p> <input type="button" onclick="ChangeText()" value="Change text" /></body>
زبانهای برنامه سازی وب
46 Of 48
DOM - Change HTML Elements
Using the Style Object <head>
<script type="text/javascript"> function ChangeBackground(){ document.body.style.backgroundColor=“blue"; }</script></head><body> <input type="button" onclick="ChangeBackground()" value="Change color" /></body>
زبانهای برنامه سازی وب
47 Of 48
DOM - Change HTML Elements Change the font and color of an Element
<head><script type="text/javascript">function ChangeStyle(){document.getElementById("p1").style.color="blue";document.getElementById("p1").style.fontFamily="Arial";}</script></head><body><p id="p1">Hello world!</p><input type="button" onclick="ChangeStyle()" value="Change style" /></body>
زبانهای برنامه سازی وب
48 Of 48
Form Validation
JavaScript can be used to validate data in HTML forms before sending has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?
زبانهای برنامه سازی وب