Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 60

JAVASCRIPT

1
Writing Into H T M L Output
<html>
<body>
<p>
JavaScript can write directly into the HTML output stream:
</p>
<script type=“text/javascript”>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
</script>
<p>
You can only use <strong>document.write</strong> in the
HTML output.
If you use it after the document has loaded (e.g. in a function),
the whole document will be overwritten.
</p>
</body>
</html>
2
Manipulating HTML
Elements
⚫ To access an HTML element from JavaScript, you
can use the document.getElementById(id) method.
⚫ Use the "id" attribute to identify the HTML
element:
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script type=“text/javascript”>
document.getElementById("demo").innerHTML="My
First JavaScript";
</script>

</body>
</html>
3
Using
function
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script type=“text/javascript”>
function myFunction()
{
document.write("Oops! The
document disappeared!");
}
</script>
</body>
</html> 4
JavaScript Statements
⚫ JavaScript statements are "commands" to the browser.
⚫ The purpose of the statements is to tell the browser what to do.
<html>

<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph.</p>

<div id="myDIV">A DIV.</div>

<script type=“text/javascript” >

document.getElementById("demo").innerHTML="Hello Dolly";

document.getElementById("myDIV").innerHTML="How are you?";

</script>

</body>

</html>

5
JavaScript is Case
Sensitive
⚫ A function getElementById is not the same
as getElementbyID.
⚫ A variable named myVariable is not the
same as MyVariable.
White Space
⚫ JavaScript ignores extra spaces.You can
add white space to your script to make
it more readable.The following lines
are equivalent:
⚫ var person="Hege";
var person =
6
JavaScript Comments.
⚫ Comments will not be executed by JavaScript.
⚫ Comments can be added to explain the JavaScript,
or to make the code more readable.
⚫ Single line comments start with //.
⚫ Multi line comments start with /* and end with */.
⚫ Example
// Write to a heading:
document.getElementById("myH1").innerHTML="Welc
ome to my Homepage";
/* The code below will write
to a heading and to a paragraph,
and will represent the start
of my homepage:
*/
document.getElementById("myH1").innerHTML="Welc
ome to my Homepage";
7
How to Change HTML
Elements
⚫ HTML elements are changed using JavaScript,
the HTML D O M and events.
⚫ Eg. C hange the Background Color
<html>
<body>
<script type="text/javaScript">
document.body.bgColor="yellow
";
</script>
<p>The background color was changed by
the script.</p>
</body>
</html>
8
Changing the Text HTML
Element
⚫ The easiest way to get or modify the content of
an element is by using the innerHTML property
<html>
<body>
<p id="p1">Hello World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="Ne
w
text!";
</script>
<p>The paragraph above was changed by
the script.</p>
</body>
</html>
9
Using
<html>
function
<head>
<script type="text/javascript">
function ChangeText(){
document.getElementById("p
1").innerHTML="New text!";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeText()" value="Click
me to change text above">
</body>
</html>

10
Using the Style
its O bjectstyle.
 The Style object represents of each HTML element represents
individual
<html>
<head>
<script
type="text/javascript">
function ChangeText() {
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="ChangeText()" value="Click me to
change text above">
</body> 11
<p id="parat">
<img src="images/face.png" height=150 width=150 align="right" name="parai"
onclick="replace()" onmouseover="changeme()" onmouseOut="changemeback(
)"/><font face="arial" color="red" size="12">Javasript</font></p>
<javaScript type=“text/javaScript>
function changeme()
{
document.parai.src="person1.jpg";
}
function changemeback()
{
document.parai.src="images/face.png";
}
function replace()
{
document.getElementById("parat").innerHTML="<h2>replaced with ME
!!!!!!!!!!!!!</h2>“;
}
</script>
12
JavaScript
Variables
⚫You declare JavaScript variables with the var
keyword: var carname;
⚫ JavaScript variables are "containers" for storing
information:
<html>
<body>
<script type=“text/javascript”>
var x=5;
var y=6; var
z=x+y;
docume
nt.wr
ite(x
+
"<br>
");
docume
nt.wr 13
Cont--
⚫ Variable can have short names (like x and y) or
- more descriptive names (age, sum, totalvolume).
⚫ Variable names must begin with a letter
⚫ Variable names can also begin with $ and _ (but we
will not use it)
⚫ Variable names are case sensitive (y and Y are
different variables)
Legal variable names in JavaScript
_ May only consist of letters, digits, and underscores
_ Can not have blank spaces
_ May not begin with a number
_ May not be a JavaScript reserved word
(keyword)
14
JavaScript D ata
Types
There are just three simple data
types:
– string,
– numeric, and
– Boolean.

15
String D ata
Type
● A string literal is a sequence of
characters delimited by single or double
quotes: "This is a string“ 'But this is
also a string'
var string_value = "This is the first line\n This
is the second line";
● to include a quote within the quoted string,
– Use a single and double quotes can be
used interchangeably
var string_value = "This is a 'string' with a
quote." or:
var string_value = 'This is a "string" with a
quote.' 16
Number Data
Type
● Numbers in JavaScript are floating-point numbers,
●All of the following are valid floating-point
numbers: 0.3555 , 144.006 , -2.3 , 19.5e-2 (which
is equivalent to
19.5-2)
● octal and hexadecimal notation can be used
– A hexadecimal number begins with a zero, followed
by an x:
0xCCFF
– Octal values begin with zeros, and there is no leading
x:
0526

17
Null and
Undefined
● Not declared
– alert(sValue); // results in JavaScript error because
sValue is not declared first
● A null variable is one that has been defined, but
hasn't
been assigned a value.
– var sValue;
– alert(sValue); // no error, and a window with
the word 'undefined' is opened
● If the variable has been declared but not initialized, it
is considered undefined
Constants
● const CURRENT_MONTH = 3.5;
18
Exampl
<html>
e
<body>
<script type=“text/javaScript”>
var person;
var car="Volvo";
document.write(person +
"<br>"); document.write(car +
"<br>");
var car=null
document.write(car +
"<br>");
</script>
</body>
19
JavaScript Popup
Boxes
 three kinds of popup boxes: Alert box, Confirm
box, and Prompt box.
– Alert Box
● Used if you want to make sure information
comes through to the user.
alert("sometext");
– Confirm Box
● used if you want the user to verify or
accept something.
confirm("sometext");
– Prompt Box
●used if you want the user to input a value
before entering a page.
prompt("sometext","defaultvalue");

20
Example Alert
box
<html>
<head>
<script type="text/javascript">
function disp_alert() {
alert("I am an alert box!!");
}
</script>
</head>
<body>
<input type="button"
onclick="disp_alert()"value="Display alert box" />
</body>
</html>

21
Example Confirm
html>
Box
<head>
<script type="text/javascript">
function disp_confirm() {
var r=confirm("Press a
button"); if (r==true) {
document.write("You pressed
OK!");
}
else {
document.write("You pressed
Cancel!");
}
}
</script>
</head>
<body>
<input type="button"
onclick="disp_confirm()"value="Di 22
Example prompt
box
<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your name", "Harry
Potter"); if (name!=null && name!="") {
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
</body>
<input type="button"
onclick="disp_prompt()" value="Display a
prompt box" />
</body>
</html>
23
Operators and
● Assignment
Statements
 NValue = 35.00;
 nValue = nValue + 35.00;
nValue = someFunction( );//function call
var firstName = lastName = middleName = "";
//more than one assignment is possible
– Arithmetic Statements
Concatenation ( “+” used with string)
var newString = "This is an old " + oldString;
Multiplication ( “*” used with numbers)
var newValue = 3.5 * 2.0; // result is 7
var newValue = 3.5 * "2.0"; // result is still
7 var newValue = "3.5" * "2.0"; // still 7
24
Cont--
-Since + is used as a concatenation with
string.
var newValue = 3.5 + " 2.0"; // result is 3.52.0
● Better way to use is by explicitly converting
the value
var aVar = 3.5 + parseFloat("2.3 the sum is
"); document.write(aVar); // result is 5.8
⚫ The Unary Operators
++ Increments a value
-- Decrements a value
- Represents a negative value
25
Conditional Statements
and Program Flow
– if
– if...else
– Switch
● Ternary Operator
condition ? value if true; value if
false;
● Logical Operators
– A N D (&&) , OR (||) , N OT(!)

26
If
 Use the if statement to execute some
Statement
code only if a specified condition is
true.
Syntax
if (condition)
{
code to be executed if condition is true
}
 Note that if is written in lowercase
letters. Using uppercase letters (IF) will
generate a JavaScript error!
27
exampl
<html>
<body>e
<p>Click the button to get a "Good day" greeting if the time is less than
20:00.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script
type=“text/javaScript”>
function myFunction()
{
var x=5;
var y=4;
var
z=x*y if
(z<20)
{
z="Goo
d day";
}
documen
t.getEle 28
If...else
Statement
⚫ Use the if....else statement to execute
some code if a condition is true and
another code if the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
cod
e to
be
exe 29
Exampl
e
<html>
<body>
<p>Click the button to get a time-based
greeting.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script
type=“text/javaScript”>
function myFunction()
{
var x=4; var y=7; var
z=x*y; if (z<20)
{ z="Good
day“; } else
{ z="Good evening“; }
document.getElementById("demo").innerHTML=z;
}
</script>
30
</body>
If...else if...else
Statement
⚫ Use the if....else if...else statement to select one
of several blocks of code to be executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither
condition1 nor condition2 is true
}
31
JavaScript Switch
Statements
⚫ Use the switch statement to select one of
many blocks of code to be executed.
Syntax
switch(n
)
{
case
1:
exec
ute
code
block
1
break
; case
2:
exec 32
Exampl
<html>
<body> e
<p>Click the button to display what day it is
today.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script
type=“text/javaScript”>
function myFunction()
{ var x;
var d=new
D ate().getDay(); switch (d)
{
case 0:
x="Today it's
Sunday"; break;
case 1:
33
Cont-
case 2:
- it's
x="Today
Tuesday"; break;
case 3:
x="Today it's
Wednesday";
break
; case
4:
x="
Toda
y it's
Thurs
day";
brea
k;
case
5:
x="Today it's
Friday"; break;
case 6:
34
The
Loops
 While
 do...while
 For ( two types )
– First type
For (initial value; condition; update)
{… }
– second type of the for loop is a for...in loop
● which accesses each element of the array as a
separate item.The syntax for this handy statement
is:
for (variable in object) {
...
}

35
The For
⚫ The for loop is often the tool you will use when
Loop
you want to create a loop.
⚫The for loop has the following syntax:
for (statement 1; statement 2;
statement 3)
{
the code block to be executed
}

⚫ Statement 1 is executed before the loop (the


code block) starts.
⚫ Statement 2 defines the condition for running
the loop (the code block).
⚫ Statement 3 is executed each time after the
loop (the code block) has been executed.

36
Exampl
e
<html>
<body>

<p>Click the button to loop through a block of code five


times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{
var x="";
for (var i=0;i<5;i++)
{
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body> 37
The For/In
Loop
⚫The JavaScript for/in statement loops through the properties of an
object: Example
<html><body>
<p>Click the button to loop through the properties of an object named
"person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script
type=“text/javaScript”>
function myFunction()
{var x;
var txt="";
var
person={fname:"John",lname:"D
oe",age:25};
for (x in person)
{txt=txt + person[x];}
document.getElementById("demo").innerHTML=tx 38
Example 2 for in
loop
<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(myc
ars[x] + "<br />");
}
</script>
</body> 39
The While
Loop
⚫ The while loop loops through a block
of code as long as a specified
condition is true.
⚫ Syntax
while (condition)
{
code block to be executed
}

40
Exampl
<html>
e
<body>
<p>Click the button to loop through a block of as long as <em>i</em> is less
than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{
var
x="",i=0;
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}
document.getElementById("demo").in
nerHTML=x;
}
</script>
</body> 41
The Do/While
Loop
⚫ The do/while loop is a variant of the
while loop.This loop will execute the
code block once, before checking if
the condition is true, then it will repeat
the loop as long as the condition is
true.
⚫Syntax
do
{
code
bloc
k to 42
Exampl
<html>
<body>e
<p>Click the button to loop through a block of as long as <em>i</em> is less
than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script
type=“text/javaScript”>
function myFunction()
{
var
x="",i=0;
do
{
x=x + "The number is " + i +
"<br>"; i++;
}
while (i<5) ;
document.getElementById("demo").innerHTML=x;
}
</script> 43
JavaScript
A⚫ rrays
An array defined as number of memory
locations, each of which can store the same
data type and which can be references
through the same variable name.
⚫ An array is a collective name given to a group
of similar quantities.
⚫The following code creates an Array called
cars: var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new
Array("Saab","Volvo","BMW"); or (literal
array): 44
Exampl
e
<html>
<body>
<script type=“text/javaScript”>
var i;
var cars = new
Array(); cars[0] =
"Saab";
cars[1] = "Volvo";
cars[2] = "BMW";
for
(i=0;i<cars.length;i++)
{
document.write(cars[i]
+ "<br>");
}
</script>
45
</body>
An
<html>
array to write a
weekday
<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> 46
JavaScript Objects
⚫ An object is delimited by curly braces. Inside
the braces the object's properties are defined
as name and value pairs (name : value).The
properties are separated by commas:
var person={firstname:"John",
lastname:"Doe", id:5566};
The object (person) in the example above
has 3 properties: firstname, lastname, and
id.
Spaces and line breaks are not
important.Your declaration can span
multiple lines:
var
person={ firstna
me : "John",
lastname 47
Exampl
<html>
e
<body>
<script
type=“text/javaScript”> var
person={
firstname :
"John", lastname
: "Doe", id :
5566
};
document.write(person.lastname + "<br>");
document.write(person["lastname"] +
"<br>");
</script> 48
JavaScript Form
⚫Validation
JavaScript can be used to validate
data in HTML forms before sending
off the content to a server.
Form data that typically are checked
by a JavaScript could be:
◦ 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?

49
exampl
e
<html>
<head>
<script type="text/javascript">
// Form validation code will come here.
function validate()
{
if( document.Form1.username.value ==
"" )
{
alert( "Please provide your username!"
);
document.Form1.username.focus() ;
return false;
}
if( document.Form1.password.value == "" )
{
alert( "Please provide your
password!" );
document.Form1.password.focus() ;
return false;
}
}
</script>
</head> 50
cont…
<body >

<form action="formvalidate.php" method='post'


name="Form1" onsubmit="return(validate())"; >
<fieldset>
<legend> <b>Login
form</b></legend> User Name:
<input type="text" name="username"
maxlength="50"
size="25"><BR><br>
Password:
<input type="password"
name="password" maxlength="50"
size="25"><br/>
<input type='submit' value="login"
/><input type='reset' value='Reset' />
</fieldset>
</form>
</body>
51
Email
<html>
<head>
<script
validation
type="text/javaScript">
function validateForm()
{
var
x=document.myForm.email.value;
var
y=document.myForm.pass.value;
var atpos=x.indexOf("@ ");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 ||
dotpos+2>=x.length)
{
alert("Not a valid e-mail
address");
document.myForm.email.focus();
return false;
}
if(y=="")
{
alert("please provided your
52
passwerd");
Cont.
.
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm();"
method="post">
<fieldset>
<legend>signin</legend>
&nbsp;&nbsp;Email:&nbsp; &nbsp;<input
type="text" name="email"><br/>
password: <input
type="password"
name="pass"><br/>
<input type="submit"
value="Submit">
</form>
</body>
53
HTML Audio - Using
<embed>
⚫ The <embed> tag defines a container for
external (non-HTML) content.
Example
<html>
<body>
<embed height="50" width="100“
src="mami.mp3">
<p>If you cannot hear the sound, your computer
or browser doesn't support the sound
format.</p>
<p>Or, you have your speakers turned off :)</p>

</body>
</html>
54
HTML Audio - Using
⚫ The <object> tag can also define a
<object>
container for external (non-HTML)
content.
Example
<html>
<body>
<object height="50"
width="100"
data="mami.mp3"></object>
<p>If you cannot hear the sound, your
computer or browser doesn't support the
sound format.</p>
<p>Or, you have your speakers turned
off :)</p>
</body> 55
Example
2
<html>
<body>
<audio controls>
<source src="mami.mp3"
type="audio/mpeg">
<source src="mami.ogg" type="audio/ogg">
Your browser does not support this audio
format.
</audio>
</body>
</html> 56
HTML Video - Using
<embed>
⚫ The <embed> tag defines a container
for external (non-HTML) content.
Example
<html>
<body>
<h2>Playing the Object</h2>
<embed src=“cc.swf" width="200"
height="200"><p>If you cannot see this,
your computer doesn't support the
format</p>
</body>
</html>
57
HTML Video - Using
<object>
⚫ The <object> tag tag can also
define a container for external
(non-HTML) content.
Example
<html>
<body>
<object height="200"
width="200"
data=“cc.swf"></object>
</body>
</html>
58
Example
<html>
2
<body>
<video width="320" height="240" controls
autoplay>
<source src="movie.ogg" type="video/ogg">
<source src="movie.mp4" type="video/mp4">
<object data="movie.mp4"
width="320" height="240">
<embed width="320"
height="240" src="movie.swf">
</object>
</video>
</body>
</html> 59
THANK
YOU THE
END
‫تمت‬
60

You might also like