SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
JAVASCRIPT
Lecturer, and Researcher at Thamar University
By Eng: Mohammed Hussein
ByEng:MohammedHussein
1
Republic of
Yemen
THAMAR UNIVERSITY
Faculty of Computer Science&
Information System
OUTLINE
 What is JavaScript?
 JavaScript Statements
 JavaScript Variables and Operators
 JavaScript Events
 JavaScript Try...Catch Statement
 JavaScript Browser (Navigator)
 JavaScript Cookies
 JavaScript Form Validation
ByEng:MohammedHussein
2
WHAT IS JAVASCRIPT?
 JavaScript is the scripting language of the Web.
 JavaScript is used in web pages to add functionality,
validate forms, communicate with the server, and much
more.
 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
ByEng:MohammedHussein
3
ARE JAVA AND JAVASCRIPT THE SAME?
 NO!
 Java and JavaScript are two completely different languages in
both concept and design!
 Java (developed by Sun Microsystems) is a powerful and much
more complex programming language - in the same category as C
and C++.
 JavaScript is an implementation of the ECMAScript language
standard. ECMA-262 is the official JavaScript standard.
 JavaScript was invented by Brendan Eich at Netscape (with
Navigator 2.0), and has appeared in all browsers since 1996.
 The official standardization was adopted by the ECMA
organization (an industry standardization association) in 1997.
 The ECMA standard (called ECMAScript-262) was approved as
an international ISO (ISO/IEC 16262) standard in 1998.
ByEng:MohammedHussein
4
WHAT CAN JAVASCRIPT DO?
 JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a scripting
language with a very simple syntax! Almost anyone can put small
"snippets" of code into their HTML pages
 JavaScript can react to events - A JavaScript can be set to execute
when something happens, like when a page has finished loading or
when a user clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can
read and change the content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used
to validate form data before it is submitted to a server. This saves the
server from extra processing
 JavaScript can be used to detect the visitor's browser - A
JavaScript can be used to detect the visitor's browser, and - depending
on the browser - load another page specifically designed for that
browser
 JavaScript can be used to create cookies - A JavaScript can be
used to store and retrieve information on the visitor's computer
ByEng:MohammedHussein
5
JS WRITING TO THE HTML DOCUMENT
 Unlike HTML,
JavaScript is case
sensitive.
 This example writes a
<p> element with
current date
information to the
HTML document.
 The lines between the
<script> and </script>
contain the JavaScript
and are executed by the
browser.
ByEng:MohammedHussein
6
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body>
</html>
JS CHANGING HTML ELEMENTS
 To manipulate HTML elements JavaScript uses
the DOM method getElementById(). This
method accesses the element with the specified id.
The browser will replace the content of the HTML
element with id=“name", with the current date
ByEng:MohammedHussein
7
<html>
<body>
<h1>My First Web Page</h1>
<p id=“name"></p>
<script type="text/javascript">
document.getElementById(“name").innerHTML=Date();
</script>
</body>
</html>
JAVASCRIPT STATEMENTS
 A JavaScript statement is a command to a
browser. The purpose of the command is to tell the
browser what to do.
 This JavaScript statement tells the browser to
write "Hello Mohammed" to the web page
 The semicolon at the end is optional. Using
semicolons makes it possible to write multiple
statements on one line.
 JavaScript statements can be grouped together in
blocks { } brackets .
ByEng:MohammedHussein
8
document.write("Hello Mohammed");
JAVASCRIPT COMMENTS
 The comment is used to prevent the execution
of a single code line (can be suitable for
debugging)
 Single line comments start with //.
 Multi line comments start with
ď‚— /* and end with */.
ByEng:MohammedHussein
9
<script type="text/javascript">
//document.write("<h1>This is a heading</h1>"); //
/* document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>"); */
document.write("<p> comments </p>");
</script>
SOME BROWSERS DO NOT SUPPORT JAVASCRIPT
 Browsers that do not support JavaScript, will display
JavaScript as page content.
 To prevent them from doing this, and as a part of the
JavaScript standard, the HTML comment tag should
be used to "hide" the JavaScript.
 Just add an HTML comment tag <!-- before the first
JavaScript statement, and a --> (end of comment) after
the last JavaScript statement.
 The two forward slashes at the end of comment line (//)
is the JavaScript comment symbol. This prevents
JavaScript from executing the --> tag.
ByEng:MohammedHussein
10
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
JAVASCRIPT PLACE IN HTML
 JavaScripts can be put in the <body> and in the
<head> sections of an HTML page.
 In <body>, the JavaScript is placed at the bottom
of the page to make sure it is not executed before
the <p> element is created as the pervious
example.
 In <head>, as we want to execute a JavaScript
when an event occurs, such as when a user clicks
a button. When this is the case we can put the
script inside a function.
 Events are normally used in combination with
functions (like calling a function when an event
occurs).
ByEng:MohammedHussein
11
JAVASCRIPT IN <BODY> OR <HEAD>
 You can place an
unlimited number of
scripts in your document,
and you can have scripts
in both the body and the
head section at the same
time.
 It is a common practice to
put all functions in the
head section, or at the
bottom of the page. This
way they are all in one
place and do not interfere
with page content.
ByEng:MohammedHussein
12
<html><head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo")
.innerHTML=Date();
}
</script>
</head>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<button type="button"
onclick="displayDate()">Display
Date</button>
</body>
</html>
USING AN EXTERNAL JAVASCRIPT
 JavaScript can also be placed in external files.
 External JavaScript files often contain code to
be used on several different web pages.
 External JavaScript files have the file
extension .js.
ByEng:MohammedHussein
13
<html>
<head>
<script type="text/javascript" src=“example.js"></script>
</head>
<body>
</body>
</html>
JAVASCRIPT VARIABLES
 A variable declared within a JavaScript function
becomes LOCAL and can only be accessed within
that function. (the variable has local scope).
 Variables declared outside a function
become GLOBAL, and all scripts and functions on
the web page can access it.
ď‚— Global variables are destroyed when you close the page.
 Rules for JavaScript variable names:
ď‚— Variable names are case sensitive (y and Y are two
different variables)
ď‚— Variable names must begin with a letter or the
underscore character.
ByEng:MohammedHussein
14var x=5;
var Facultyname=“CSIT";
JAVASCRIPT 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
(division
remainder)
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
ByEng:MohammedHussein
15
JAVASCRIPT ASSIGNMENT OPERATORS
Operator Example Same As Result
= x=y y=5 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
ByEng:MohammedHussein
16
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
Adding Strings and Numbers
The + Operator Used on Strings
JAVASCRIPT 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 true
x==="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
ByEng:MohammedHussein
17
LOGICAL OPERATORS
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
ByEng:MohammedHussein
18
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.
Syntax variablename=(condition)?value1:value2
Example greeting=(visitor==“Mohammed")?"Dear Dr.":"Dear ";
If the variable visitor has the value of “Mohammed", then the
variable greeting will be assigned the value "Dear Dr." else it
will be assigned "Dear".
JS - IF...ELSE AND SWITCH STATEMENTS
 These are similar to PHP Statements
ď‚— if statement - use this statement to execute some
code only if a specified condition is true
ď‚— if...else statement - use this statement to execute
some code if the condition is true and another code if
the condition is false
ď‚— if...else if....else statement - use this statement to
select one of many blocks of code to be executed
ď‚— switch statement - use this statement to select one
of many blocks of code to be executed
ByEng:MohammedHussein
19
JAVASCRIPT EVENTS
 Events are actions that can be detected by JavaScript.
 By using JavaScript, we have the ability to create
dynamic web pages. Events are actions that can be
detected by JavaScript.
ByEng:MohammedHussein
20
<html> <head><script type="text/javascript">
function displayDate()
{
document.getElementById("name").innerHTML=Date();
}
</script></head>
<body>
<h1>My First Web Page</h1>
<p id="name"></p>
<button type="button" onclick="displayDate()">Display
Date</button>
</body> </html>
ONLOAD AND ONUNLOAD EVENTS
 The onLoad and onUnload events are triggered
when the user enters or leaves the page.
 Both the onLoad and onUnload events are also
often used to deal with cookies that should be
set when a user enters or leaves a page.
ď‚— For example, you could have a popup asking for the
user's name upon his first arrival to your page. The
name is then stored in a cookie. Next time the
visitor arrives at your page, you could have another
popup saying something like: "Welcome Ahmed!".
ByEng:MohammedHussein
21
ONSUBMIT EVENT
 The onSubmit event is used to validate ALL
form fields before submitting it.
 Below is an example of how to use the
onSubmit event.
ď‚— The checkForm() function will be called when the
user clicks the submit button in the form. If the field
values are not accepted, the submit should be
cancelled. The function checkForm() returns either
true or false. If it returns true the form will be
submitted, otherwise the submit will be cancelled.
ByEng:MohammedHussein
22
<form method="post" action=“ex.htm" onsubmit="return checkForm()">
ONFOCUS, ONBLUR AND ONCHANGE EVENTS
 The onFocus, onBlur and onChange events are
often used in combination with validation of
form fields.
 Below is an example of how to use the
onChange event. The checkEmail() function
will be called whenever the user changes the
content of the field.
ByEng:MohammedHussein
23
<input type="text" size="30" id="email" onchange="checkEmail()">
JAVASCRIPT TRY...CATCH STATEMENT
 The try...catch statement allows you to test a block of
code for errors.
 The try block contains the code to be run, and the
catch block contains the code to be executed if an error
occurs.
ď‚— Note that try...catch is written in lowercase letters. Using
uppercase letters will generate a JavaScript error!
 The try .. catch example uses a confirm box to display
a custom message telling users they can click OK to
continue viewing the page or click Cancel to go to the
homepage. If the confirm method returns false, the
user clicked Cancel, and the code redirects the user. If
the confirm method returns true, the code does nothing
ByEng:MohammedHussein
24
TRY...CATCH 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.nn";
txt+="Click OK to continue viewing this page,n";
txt+="or Cancel to return to the home page.nn";
if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/";
}
}
}
</script> </head>
<body>
<input type="button" value="View message"
onclick="message()" />
</body> </html>
ByEng:MohammedHussein
25
OR
THE THROW STATEMENT
 The throw statement can be used together with
the try...catch statement, to create an exception
for the error.
 The throw statement allows you to create an
exception. If you use this statement together with
the try...catch statement, you can control program
flow and generate accurate error messages.
ď‚— The exception can be a string, integer, Boolean or an
object.
ď‚— Note that throw is written in lowercase letters. Using
uppercase letters will generate a JavaScript error!
ByEng:MohammedHussein
26
THROW 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"; }
else if(isNaN(x))
{ throw "Err3"; }
}
catch(er)
{
if(er=="Err1")
{ alert("Error! The value is too high"); }
if(er=="Err2")
{ alert("Error! The value is too low"); }
if(er=="Err3")
{ alert("Error! The value is not a number"); }
}
</script></body></html>
ByEng:MohammedHussein
27
JAVASCRIPT BROWSER (NAVIGATOR)
 The Navigator object contains information about
the visitor's browser: name, version, and more.
 Browser Detection
ď‚— Browser should enabled JavaScript. However, there are
some things that just don't work on certain browsers -
especially on older browsers.
ď‚— Sometimes it can be useful to detect the visitor's browser,
and then serve the appropriate information.
ď‚— Note: There is no public standard that applies to the
navigator object, but all major browsers support it.
ByEng:MohammedHussein
28
THE NAVIGATOR OBJECT
ByEng:MohammedHussein
29
<div id="example">Browser</div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
JAVASCRIPT COOKIES
 A cookie is often used to identify a user.
 What is a Cookie?
ď‚— A cookie is a variable that is stored on the visitor's computer. Each time
the same computer requests a page with a browser, it will send the cookie
too. With JavaScript, you can both create and retrieve cookie values.
 Examples of cookies:
ď‚— Name cookie - 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 Ana!" The name is retrieved from the stored cookie.
ď‚— Password cookie - 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
ď‚— Date cookie - 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,
2008!" The date is retrieved from the stored cookie
ByEng:MohammedHussein
30
CREATE AND STORE A COOKIE:
STORE FUNCTION
 In this example we will create a cookie that stores the name of a
visitor.
 First, we create a function that stores the name of the visitor in a
cookie variable:
 The parameters of the function hold the name of the cookie, the
value of the cookie, and the number of days until the cookie
expires.
 we first convert the number of days to a valid date, then we add
the number of days until the cookie should expire. After that we
store the cookie name, cookie value and the expiration date in the
document.cookie object.
ByEng:MohammedHussein
31
function setCookie(c_name , value, exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : ";
expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
CREATE AND STORE A COOKIE:
RETURN FUNCTION
 This function makes an array to retrieve cookie
names and values, then it checks if the specified
cookie exists, and returns the cookie value.
ByEng:MohammedHussein
32
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^s+|s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
CREATE AND STORE A COOKIE:
DISPLAY FUNCTION
 The function that displays a welcome message if the cookie
is set, and if the cookie is not set it will display a prompt
box, asking for the name of the user, and stores the
username cookie for 365 days, by calling the setCookie
function.
ByEng:MohammedHussein
33
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{ alert("Welcome again " + username); }
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{ setCookie("username",username,365); }
}
}
COOKIE FULL EXAMPLE
<html><head><script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^s+|s+$/g,"");
if (x==c_name)
{ return unescape(y); }
} }
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{ alert("Welcome again " + username); }
else
{ username=prompt("Please enter your name:","");
if (username!=null && username!="")
{ setCookie("username",username,365); } }
}
</script> </head> <body onload="checkCookie()"> </body> </html>
ByEng:MohammedHussein
34
F5
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?
ByEng:MohammedHussein
35
REQUIRED FIELDS
 The function below checks if a field has been left
empty. If the field is blank, an alert box alerts a
message, the function returns false, and the form
will not be submitted.
ByEng:MohammedHussein
36
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{ alert("First name must be filled out");
return false; }
}
<form name="myForm" action=“Reg_form.asp"
onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
E-MAIL VALIDATION
 The function below checks if the content has the general syntax of
an email. This means that the input data must contain an @ sign
and at least one dot (.). Also, the @ must not be the first character
of the email address, and the last dot must be present after the @
sign, and minimum 2 characters before the end.
ByEng:MohammedHussein
37
function validateForm()
{
var x=document.forms["myForm"]["email"].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");
return false; } }
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
REFERENCES
 http://www.w3schools.com/w3c/w3c_html.asp
 http://httpd.apache.org/
 http://www.joomla.org/download.html
 http://www.yourhtmlsource.com/javascript/coo
kies.html

Weitere ähnliche Inhalte

Was ist angesagt?

JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulationborkweb
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source codeLaurence Svekis âś”
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2borkweb
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academyactanimation
 
Java Script
Java ScriptJava Script
Java Scriptsiddaram
 
Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Vlad Mysla
 
KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7phuphax
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4SURBHI SAROHA
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Haim Michael
 
Javascript 2009
Javascript 2009Javascript 2009
Javascript 2009borkweb
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM eventsJussi Pohjolainen
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjaliGeetanjali Bhosale
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_queryFajar Baskoro
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & eventBorey Lim
 
Web Components
Web ComponentsWeb Components
Web ComponentsNikolaus Graf
 

Was ist angesagt? (20)

JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source code
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
Java Script
Java ScriptJava Script
Java Script
 
Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)
 
KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 
Javascript 2009
Javascript 2009Javascript 2009
Javascript 2009
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Java script
Java scriptJava script
Java script
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
jQuery
jQueryjQuery
jQuery
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
 
Web Components
Web ComponentsWeb Components
Web Components
 

Andere mochten auch

Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Mohammed Hussein
 
Whizle For Learners
Whizle For LearnersWhizle For Learners
Whizle For Learnershumanist3
 
Lec3 Algott
Lec3 AlgottLec3 Algott
Lec3 Algotthumanist3
 
02 greedy, d&c, binary search
02 greedy, d&c, binary search02 greedy, d&c, binary search
02 greedy, d&c, binary searchPankaj Prateek
 
02 asymptotic-notation-and-recurrences
02 asymptotic-notation-and-recurrences02 asymptotic-notation-and-recurrences
02 asymptotic-notation-and-recurrencesNoushadur Shoukhin
 
02 Analysis of Algorithms: Divide and Conquer
02 Analysis of Algorithms: Divide and Conquer02 Analysis of Algorithms: Divide and Conquer
02 Analysis of Algorithms: Divide and ConquerAndres Mendez-Vazquez
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursionMohammed Hussein
 
Comnet Network Simulation
Comnet Network SimulationComnet Network Simulation
Comnet Network SimulationMohammed Hussein
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1Mohammed Hussein
 
Algorithm Analyzing
Algorithm AnalyzingAlgorithm Analyzing
Algorithm AnalyzingHaluan Irsad
 
Data Management (Data Mining Klasifikasi)
Data Management (Data Mining Klasifikasi)Data Management (Data Mining Klasifikasi)
Data Management (Data Mining Klasifikasi)Adam Mukharil Bachtiar
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sortMadhu Bala
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 

Andere mochten auch (20)

Multimedia lecture ActionScript3
Multimedia lecture ActionScript3Multimedia lecture ActionScript3
Multimedia lecture ActionScript3
 
Whizle For Learners
Whizle For LearnersWhizle For Learners
Whizle For Learners
 
Lec3 Algott
Lec3 AlgottLec3 Algott
Lec3 Algott
 
Multimedia lecture6
Multimedia lecture6Multimedia lecture6
Multimedia lecture6
 
Wireless lecture1
Wireless lecture1Wireless lecture1
Wireless lecture1
 
02 greedy, d&c, binary search
02 greedy, d&c, binary search02 greedy, d&c, binary search
02 greedy, d&c, binary search
 
02 asymptotic-notation-and-recurrences
02 asymptotic-notation-and-recurrences02 asymptotic-notation-and-recurrences
02 asymptotic-notation-and-recurrences
 
02 Analysis of Algorithms: Divide and Conquer
02 Analysis of Algorithms: Divide and Conquer02 Analysis of Algorithms: Divide and Conquer
02 Analysis of Algorithms: Divide and Conquer
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Iteration, induction, and recursion
Iteration, induction, and recursionIteration, induction, and recursion
Iteration, induction, and recursion
 
Comnet Network Simulation
Comnet Network SimulationComnet Network Simulation
Comnet Network Simulation
 
PHP
 PHP PHP
PHP
 
Internet programming lecture 1
Internet programming lecture 1Internet programming lecture 1
Internet programming lecture 1
 
Algorithm Analyzing
Algorithm AnalyzingAlgorithm Analyzing
Algorithm Analyzing
 
Multimedia Network
Multimedia NetworkMultimedia Network
Multimedia Network
 
Control system
Control systemControl system
Control system
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Data Management (Data Mining Klasifikasi)
Data Management (Data Mining Klasifikasi)Data Management (Data Mining Klasifikasi)
Data Management (Data Mining Klasifikasi)
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 

Ă„hnlich wie JAVA SCRIPT

Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java scriptnanjil1984
 
Java script Basic
Java script BasicJava script Basic
Java script BasicJaya Kumari
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
Javascript
JavascriptJavascript
JavascriptNagarajan
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)Shrijan Tiwari
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPTGo4Guru
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students shafiq sangi
 
Introduction of javascript
Introduction of javascriptIntroduction of javascript
Introduction of javascriptsyeda zoya mehdi
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
BEAAUTIFUL presentation of java
BEAAUTIFUL  presentation of javaBEAAUTIFUL  presentation of java
BEAAUTIFUL presentation of javarana usman
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptxachutachut
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptxGangesh8
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationSoumen Santra
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Lookrumsan
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scriptingfantasticdigitaltools
 
JavaScript - Part-1
JavaScript - Part-1JavaScript - Part-1
JavaScript - Part-1Jainul Musani
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using JavascriptBansari Shah
 

Ă„hnlich wie JAVA SCRIPT (20)

Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Javascript
JavascriptJavascript
Javascript
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
 
Introduction of javascript
Introduction of javascriptIntroduction of javascript
Introduction of javascript
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
BEAAUTIFUL presentation of java
BEAAUTIFUL  presentation of javaBEAAUTIFUL  presentation of java
BEAAUTIFUL presentation of java
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptx
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptx
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 
Java scipt
Java sciptJava scipt
Java scipt
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scripting
 
JavaScript - Part-1
JavaScript - Part-1JavaScript - Part-1
JavaScript - Part-1
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
 

KĂĽrzlich hochgeladen

PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

KĂĽrzlich hochgeladen (20)

PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1CĂłdigo Creativo y Arte de Software | Unidad 1
CĂłdigo Creativo y Arte de Software | Unidad 1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

JAVA SCRIPT

  • 1. JAVASCRIPT Lecturer, and Researcher at Thamar University By Eng: Mohammed Hussein ByEng:MohammedHussein 1 Republic of Yemen THAMAR UNIVERSITY Faculty of Computer Science& Information System
  • 2. OUTLINE  What is JavaScript?  JavaScript Statements  JavaScript Variables and Operators  JavaScript Events  JavaScript Try...Catch Statement  JavaScript Browser (Navigator)  JavaScript Cookies  JavaScript Form Validation ByEng:MohammedHussein 2
  • 3. WHAT IS JAVASCRIPT?  JavaScript is the scripting language of the Web.  JavaScript is used in web pages to add functionality, validate forms, communicate with the server, and much more.  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 ByEng:MohammedHussein 3
  • 4. ARE JAVA AND JAVASCRIPT THE SAME?  NO!  Java and JavaScript are two completely different languages in both concept and design!  Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.  JavaScript is an implementation of the ECMAScript language standard. ECMA-262 is the official JavaScript standard.  JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all browsers since 1996.  The official standardization was adopted by the ECMA organization (an industry standardization association) in 1997.  The ECMA standard (called ECMAScript-262) was approved as an international ISO (ISO/IEC 16262) standard in 1998. ByEng:MohammedHussein 4
  • 5. WHAT CAN JAVASCRIPT DO?  JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages  JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element  JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element  JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing  JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser  JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer ByEng:MohammedHussein 5
  • 6. JS WRITING TO THE HTML DOCUMENT  Unlike HTML, JavaScript is case sensitive.  This example writes a <p> element with current date information to the HTML document.  The lines between the <script> and </script> contain the JavaScript and are executed by the browser. ByEng:MohammedHussein 6 <html> <body> <h1>My First Web Page</h1> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); </script> </body> </html>
  • 7. JS CHANGING HTML ELEMENTS  To manipulate HTML elements JavaScript uses the DOM method getElementById(). This method accesses the element with the specified id. The browser will replace the content of the HTML element with id=“name", with the current date ByEng:MohammedHussein 7 <html> <body> <h1>My First Web Page</h1> <p id=“name"></p> <script type="text/javascript"> document.getElementById(“name").innerHTML=Date(); </script> </body> </html>
  • 8. JAVASCRIPT STATEMENTS  A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do.  This JavaScript statement tells the browser to write "Hello Mohammed" to the web page  The semicolon at the end is optional. Using semicolons makes it possible to write multiple statements on one line.  JavaScript statements can be grouped together in blocks { } brackets . ByEng:MohammedHussein 8 document.write("Hello Mohammed");
  • 9. JAVASCRIPT COMMENTS  The comment is used to prevent the execution of a single code line (can be suitable for debugging)  Single line comments start with //.  Multi line comments start with ď‚— /* and end with */. ByEng:MohammedHussein 9 <script type="text/javascript"> //document.write("<h1>This is a heading</h1>"); // /* document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); */ document.write("<p> comments </p>"); </script>
  • 10. SOME BROWSERS DO NOT SUPPORT JAVASCRIPT  Browsers that do not support JavaScript, will display JavaScript as page content.  To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript.  Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement.  The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag. ByEng:MohammedHussein 10 <script type="text/javascript"> <!-- document.getElementById("demo").innerHTML=Date(); //--> </script>
  • 11. JAVASCRIPT PLACE IN HTML  JavaScripts can be put in the <body> and in the <head> sections of an HTML page.  In <body>, the JavaScript is placed at the bottom of the page to make sure it is not executed before the <p> element is created as the pervious example.  In <head>, as we want to execute a JavaScript when an event occurs, such as when a user clicks a button. When this is the case we can put the script inside a function.  Events are normally used in combination with functions (like calling a function when an event occurs). ByEng:MohammedHussein 11
  • 12. JAVASCRIPT IN <BODY> OR <HEAD>  You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.  It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content. ByEng:MohammedHussein 12 <html><head> <script type="text/javascript"> function displayDate() { document.getElementById("demo") .innerHTML=Date(); } </script> </head> <body> <h1>My First Web Page</h1> <p id="demo"></p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html>
  • 13. USING AN EXTERNAL JAVASCRIPT  JavaScript can also be placed in external files.  External JavaScript files often contain code to be used on several different web pages.  External JavaScript files have the file extension .js. ByEng:MohammedHussein 13 <html> <head> <script type="text/javascript" src=“example.js"></script> </head> <body> </body> </html>
  • 14. JAVASCRIPT VARIABLES  A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope).  Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it. ď‚— Global variables are destroyed when you close the page.  Rules for JavaScript variable names: ď‚— Variable names are case sensitive (y and Y are two different variables) ď‚— Variable names must begin with a letter or the underscore character. ByEng:MohammedHussein 14var x=5; var Facultyname=“CSIT";
  • 15. JAVASCRIPT 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 (division remainder) 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 ByEng:MohammedHussein 15
  • 16. JAVASCRIPT ASSIGNMENT OPERATORS Operator Example Same As Result = x=y y=5 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 ByEng:MohammedHussein 16 txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; x=5+5; document.write(x); x="5"+"5"; document.write(x); x=5+"5"; document.write(x); x="5"+5; document.write(x); Adding Strings and Numbers The + Operator Used on Strings
  • 17. JAVASCRIPT 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 true x==="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 ByEng:MohammedHussein 17
  • 18. LOGICAL OPERATORS Operator Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true ByEng:MohammedHussein 18 Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2 Example greeting=(visitor==“Mohammed")?"Dear Dr.":"Dear "; If the variable visitor has the value of “Mohammed", then the variable greeting will be assigned the value "Dear Dr." else it will be assigned "Dear".
  • 19. JS - IF...ELSE AND SWITCH STATEMENTS  These are similar to PHP Statements ď‚— if statement - use this statement to execute some code only if a specified condition is true ď‚— if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false ď‚— if...else if....else statement - use this statement to select one of many blocks of code to be executed ď‚— switch statement - use this statement to select one of many blocks of code to be executed ByEng:MohammedHussein 19
  • 20. JAVASCRIPT EVENTS  Events are actions that can be detected by JavaScript.  By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. ByEng:MohammedHussein 20 <html> <head><script type="text/javascript"> function displayDate() { document.getElementById("name").innerHTML=Date(); } </script></head> <body> <h1>My First Web Page</h1> <p id="name"></p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html>
  • 21. ONLOAD AND ONUNLOAD EVENTS  The onLoad and onUnload events are triggered when the user enters or leaves the page.  Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. ď‚— For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome Ahmed!". ByEng:MohammedHussein 21
  • 22. ONSUBMIT EVENT  The onSubmit event is used to validate ALL form fields before submitting it.  Below is an example of how to use the onSubmit event. ď‚— The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled. ByEng:MohammedHussein 22 <form method="post" action=“ex.htm" onsubmit="return checkForm()">
  • 23. ONFOCUS, ONBLUR AND ONCHANGE EVENTS  The onFocus, onBlur and onChange events are often used in combination with validation of form fields.  Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field. ByEng:MohammedHussein 23 <input type="text" size="30" id="email" onchange="checkEmail()">
  • 24. JAVASCRIPT TRY...CATCH STATEMENT  The try...catch statement allows you to test a block of code for errors.  The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. ď‚— Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!  The try .. catch example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing ByEng:MohammedHussein 24
  • 25. TRY...CATCH 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.nn"; txt+="Click OK to continue viewing this page,n"; txt+="or Cancel to return to the home page.nn"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> ByEng:MohammedHussein 25 OR
  • 26. THE THROW STATEMENT  The throw statement can be used together with the try...catch statement, to create an exception for the error.  The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages. ď‚— The exception can be a string, integer, Boolean or an object. ď‚— Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error! ByEng:MohammedHussein 26
  • 27. THROW 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"; } else if(isNaN(x)) { throw "Err3"; } } catch(er) { if(er=="Err1") { alert("Error! The value is too high"); } if(er=="Err2") { alert("Error! The value is too low"); } if(er=="Err3") { alert("Error! The value is not a number"); } } </script></body></html> ByEng:MohammedHussein 27
  • 28. JAVASCRIPT BROWSER (NAVIGATOR)  The Navigator object contains information about the visitor's browser: name, version, and more.  Browser Detection ď‚— Browser should enabled JavaScript. However, there are some things that just don't work on certain browsers - especially on older browsers. ď‚— Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information. ď‚— Note: There is no public standard that applies to the navigator object, but all major browsers support it. ByEng:MohammedHussein 28
  • 29. THE NAVIGATOR OBJECT ByEng:MohammedHussein 29 <div id="example">Browser</div> <script type="text/javascript"> txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; txt+= "<p>Browser Name: " + navigator.appName + "</p>"; txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; txt+= "<p>Platform: " + navigator.platform + "</p>"; txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; document.getElementById("example").innerHTML=txt; </script>
  • 30. JAVASCRIPT COOKIES  A cookie is often used to identify a user.  What is a Cookie? ď‚— A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.  Examples of cookies: ď‚— Name cookie - 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 Ana!" The name is retrieved from the stored cookie. ď‚— Password cookie - 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 ď‚— Date cookie - 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, 2008!" The date is retrieved from the stored cookie ByEng:MohammedHussein 30
  • 31. CREATE AND STORE A COOKIE: STORE FUNCTION  In this example we will create a cookie that stores the name of a visitor.  First, we create a function that stores the name of the visitor in a cookie variable:  The parameters of the function hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.  we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object. ByEng:MohammedHussein 31 function setCookie(c_name , value, exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; }
  • 32. CREATE AND STORE A COOKIE: RETURN FUNCTION  This function makes an array to retrieve cookie names and values, then it checks if the specified cookie exists, and returns the cookie value. ByEng:MohammedHussein 32 function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^s+|s+$/g,""); if (x==c_name) { return unescape(y); } } }
  • 33. CREATE AND STORE A COOKIE: DISPLAY FUNCTION  The function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user, and stores the username cookie for 365 days, by calling the setCookie function. ByEng:MohammedHussein 33 function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,365); } } }
  • 34. COOKIE FULL EXAMPLE <html><head><script type="text/javascript"> function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^s+|s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,365); } } } </script> </head> <body onload="checkCookie()"> </body> </html> ByEng:MohammedHussein 34 F5
  • 35. 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? ByEng:MohammedHussein 35
  • 36. REQUIRED FIELDS  The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted. ByEng:MohammedHussein 36 function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } <form name="myForm" action=“Reg_form.asp" onsubmit="return validateForm()" method="post"> First name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form>
  • 37. E-MAIL VALIDATION  The function below checks if the content has the general syntax of an email. This means that the input data must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be present after the @ sign, and minimum 2 characters before the end. ByEng:MohammedHussein 37 function validateForm() { var x=document.forms["myForm"]["email"].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"); return false; } } <form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post"> Email: <input type="text" name="email"> <input type="submit" value="Submit"> </form>
  • 38. REFERENCES  http://www.w3schools.com/w3c/w3c_html.asp  http://httpd.apache.org/  http://www.joomla.org/download.html  http://www.yourhtmlsource.com/javascript/coo kies.html