SlideShare a Scribd company logo
1 of 50
Download to read offline
HTML Scripts
Visit our website : techaltum.com
Online Tutorial : tutorial.techaltum.com Made By:
Avinash Malhotra1http://www.tutorial.techaltum.com
Scripts
O In computer programming, a script is a program or
sequence of instructions that is interpreted or carried
out by another program rather than by the computer
processor (as a compiled program is).
O Some languages have been conceived expressly as
script languages. Among the most popular are Perl,
Rexx (on IBM mainframes), JavaScript, and Tcl/Tk.
O In the context of the World Wide Web, Perl, VBScript,
and similar script languages are often written to
handle forms input or other services for a Web site
and are processed on the Web server.
O A JavaScript script in a Web page runs "client-side" on
the Web browser.
2http://www.tutorial.techaltum.com
HTML Scripts (cont)
O With HTML scripts you can create dynamic
web pages, make image rollovers for really
cool menu effects, or even validate your
HTML form's data before you let the user
submit. However, javascript and vbscript are
very complicated compared to HTML. It may
be simpler just to download someone elses
scripting code and use it on your web page.
3http://www.tutorial.techaltum.com
HTML Javascript Code
O If you want to insert javascript code into your
HTML you are going to use the script tag.
O Below is the correct code to insert
embedded javascript code onto your site.
<script type="text/javascript">
<!--script ***Some javascript code should
go here*** -->
</script>
4http://www.tutorial.techaltum.com
The Name "JavaScript"
O The name JavaScript is owned by Netscape.
O Microsoft calls its version of the language
JScript.
O The generic name of the language is
EcmaScript.
5http://www.tutorial.techaltum.com
The HTML DOM
O The HTML Document Object Model (DOM) is
the browser's view of an HTML page as an
object hierarchy, starting with the browser
window itself and moving deeper into the
page, including all of the elements on the
page and their attributes.
6http://www.tutorial.techaltum.com
Simplified Version of HTML
DOM
7http://www.tutorial.techaltum.com
Introduction to JavaScript
O JavaScript is used in millions of Web pages
to improve the design, validate forms, detect
browsers, create cookies, and much more.
O JavaScript is the most popular scripting
language on the internet, and works in all
major browsers, such as Internet Explorer,
Mozilla, Firefox, Netscape, and Opera.
O Before you continue you should have a basic
understanding of HTML
8http://www.tutorial.techaltum.com
What is JavaScript?
O JavaScript was designed to add interactivity to HTML
pages
O JavaScript is a scripting language
O A scripting language is a lightweight programming
language
O A JavaScript consists of lines of executable computer
code
O A JavaScript is usually embedded directly into HTML
pages
O JavaScript is an interpreted language (means that
scripts execute without preliminary compilation)
O Everyone can use JavaScript without purchasing a
license
9http://www.tutorial.techaltum.com
Are Java and JavaScript the
Same?
O NO!
O Java and JavaScript are two completely
different languages in both concept and
design!
O Java (developed by Sun Microsystems) is a
powerful and much more complex
programming language - in the same
category as C and C++.
10http://www.tutorial.techaltum.com
What can a JavaScript Do?
O 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
O JavaScript can put dynamic text into an HTML page
- A JavaScript statement like this: document.write("<h1>" +
name + "</h1>") can write a variable text into an HTML page
O 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
O JavaScript can read and write HTML elements - A
JavaScript can read and change the content of an HTML
element
11http://www.tutorial.techaltum.com
What can a JavaScript Do?
(cont)
O 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
O 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
O JavaScript can be used to create cookies
- A JavaScript can be used to store and retrieve
information on the visitor's computer
12http://www.tutorial.techaltum.com
JavaScript Basic Rules
O JavaScript statements end with semi-
colons.
O JavaScript is case sensitive.
O JavaScript has two forms of comments:
O Single-line comments begin with a double
slash (//).
O Multi-line comments begin with "/*" and
end with "*/".
13http://www.tutorial.techaltum.com
Comment Syntax
O Syntax
// This is a single-line comment
/* This is
a multi-line
comment. */
14http://www.tutorial.techaltum.com
O Enter any two value from user show its addition
multiplication subtraction and division
O Enter 5 subject marks from the user show its total
Enter km and show in meter.
O marks and its percentage (%)
O Enter meter and show in km
O Enter the tem.. In dc and show in Fahrenheit.
Questions ...
15http://www.tutorial.techaltum.com
Dot Notation
O In JavaScript, objects can be referenced
using dot notation, starting with the highest-
level object (i.e, window). Objects can be
referred to by name or id or by their position
on the page. For example, if there is a form
on the page named "loginform", using dot
notation you could refer to the form as
follows:
O Syntax
window.document.loginform
O Another example is:
document.write // write is a method
for document
16http://www.tutorial.techaltum.com
Document Object Methods
Method Description
close() Closes an output stream opened with the
document.open() method, and displays the
collected data
getElementById() Returns a reference to the first object with the specified
id
getElementsByName() Returns a collection of objects with the specified name
getElementsByTagName() Returns a collection of objects with the specified
tagname
open() Opens a stream to collect the output from any
document.write() or document.writeln() methods
write() Writes HTML expressions or JavaScript code to a
document
writeln() Identical to the write() method, with the addition of
writing a new line character after each expression
17http://www.tutorial.techaltum.com
write method
O <html>
O <body>
O <script type="text/javascript">
O document.write("Hello World!");
O </script>
O </body>
O </html>
Output
Hello World!
18http://www.tutorial.techaltum.com
Example Explained
O To insert a JavaScript into an HTML
page, we use the <script> tag. Inside the
<script> tag we use the "type=" attribute
to define the scripting language.
O So, the <script type="text/javascript">
and </script> tells where the JavaScript
starts and ends.
O The word document.write is a
standard JavaScript command for writing
output to a page.
19http://www.tutorial.techaltum.com
write method (cont)
O <html>
O <body>
O <script type="text/javascript">
O document.write("<h1>This is a
header</h1>");
O </script>
O </body>
O </html>
Output
This is a header20http://www.tutorial.techaltum.com
write method (cont)
<html>
<body>
<script type="text/javascript">
document.write("<h1>This is a header</h1>");
document.write("<p>This is a paragraph</p>");
document.write("<p>This is another
paragraph</p>");
</script>
</body>
</html>
21http://www.tutorial.techaltum.com
JavaScript Variables
O Variables are "containers" for storing
information.
O Variables can be used to hold values
O Example:
x=5;  length=66.10;
22http://www.tutorial.techaltum.com
JavaScript Variables (cont)
O A variable can have a short name, like x,
or a more describing name like length.  
O A JavaScript variable can also hold a text
value like in carname="Volvo".
O Rules for JavaScript variable names:
O Variable names are case sensitive (y and
Y are two different variables)
O Variable names must begin with a
letter or the underscore character
O NOTE:  Because JavaScript is case-
sensitive, variable names are case-
sensitive.
23http://www.tutorial.techaltum.com
JavaScript Variables (cont)
<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Hege";
document.write(firstname);
document.write("<br />");
firstname="Tove";
document.write(firstname);
</script>
<p>The script above declares a variable, assigns a value to it,
displays the value, change the value, and displays the value
again.</p>
</body>
</html>
24http://www.tutorial.techaltum.com
Assigning Values to
Undeclared JavaScript
VariablesO If you assign values to variables that has
not yet been declared, the variables will
automatically be declared.
O If you redeclare a JavaScript variable, it
will not lose its original value.
O var x=5;
O var x;
O After the execution of the statements
above, the variable x will still have the
value of 5. The value of x is not reset (or
cleared) when you redeclare it.
25http://www.tutorial.techaltum.com
JavaScript Operators
O The assignment operator = is used to assign
values to JavaScript variables.
O Arithmetic operators are used to perform
arithmetic between variables and/or values.
26http://www.tutorial.techaltum.com
JavaScript Operators (cont)
O Given that y=5, the table below explains the
arithmetic operators:
Sign Description Example Result
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4 27http://www.tutorial.techaltum.com
JavaScript Assignment Operators
O Assignment operators are used to assign values to
JavaScript variables.
O Given that x=10 and y=5, the table below explains the
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
28http://www.tutorial.techaltum.com
The + Operator Used on
Strings
O The + operator can also be used to add string variables
or text values together.
O To add two or more string variables together, use the +
operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
O After the execution of the statements above, the
variable txt3 contains "What a verynice day".
29http://www.tutorial.techaltum.com
Adding Strings and
Numbers
O Look at these examples:
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
O The rule is:
O If you add a number and a string, the result
will be a string.
10
55
55
55
30http://www.tutorial.techaltum.com
JavaScript Comparison and
Logical Operators
O Comparison and Logical operators are used
to test for true or false.
O Comparison operators are used in logical
statements to determine equality or
difference between variables or values.
31http://www.tutorial.techaltum.com
JavaScript Comparison and Logical
Operators (cont)
O Given that x=5, the table below explains the
comparison operators:
Sign Description Example
== is equal to x==8 is false
=== 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 32http://www.tutorial.techaltum.com
How Can it be Used
O Comparison operators can be used in
conditional statements to compare values
and take action depending on the result:
if (age<18) document.write("Too young");
33http://www.tutorial.techaltum.com
Logical Operators
O Logical operators are used in determine
the logic between variables or values.
O Given that x=6 and y=3, the table below
explains the logical operators:
Sign Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
34http://www.tutorial.techaltum.com
Conditional Operator
O JavaScript also contains a conditional operator
that assigns a value to a variable based on some
condition.
O Syntax
variablename=(condition)?value1:value2 
O Example
greeting=(visitor=="PRES")?"Dear President
":"Dear ";
O If the variable visitor has the value of "PRES",
then the variable greeting will be assigned the
value "Dear President " else it will be assigned
"Dear". 35http://www.tutorial.techaltum.com
JavaScript If...Else
Statements
O Conditional statements in JavaScript are used to perform
different actions based on different conditions.
O In JavaScript we have the following conditional statements:
O if statement - use this statement if you want to execute
some code only if a specified condition is true
O if...else statement - use this statement if you want to
execute some code if the condition is true and another code if
the condition is false
O if...else if....else statement - use this statement if you
want to select one of many blocks of code to be executed
O switch statement - use this statement if you want to select
one of many blocks of code to be executed
36http://www.tutorial.techaltum.com
If Statement
O You should use the if statement if you want
to execute some code only if a specified
condition is true.
O Syntax
if (condition)
{
code to be executed if condition
is true }
O Note that if is written in lowercase letters.
Using uppercase letters (IF) will generate a
JavaScript error!
37http://www.tutorial.techaltum.com
If Statement Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good
morning</b>");
}
</script> 38http://www.tutorial.techaltum.com
If Statement Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=d.getHours();
if (time==11)
{
document.write("<b>Lunch-time!</b>");
}
</script>
39http://www.tutorial.techaltum.com
If...else Statement
O If you want to execute some code if a condition is true and
another code if the condition is not true, use the if....else
statement.
O Syntax
if (condition)
{
code to be executed if condition is true }
else
{
code to be executed if condition is not true
}
40http://www.tutorial.techaltum.com
If...else Statement
Example<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting. //Otherwise you
will get a "Good day“greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
} </script> 41http://www.tutorial.techaltum.com
JavaScript Switch
Statement
O You should use the switch statement if you want to
select one of many blocks of code to be executed.
O Syntax
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
}
42http://www.tutorial.techaltum.com
JavaScript Switch Statement
(cont)
O This is how it works: First we have a single
expression n (most often a variable), that is
evaluated once. The value of the expression
is then compared with the values for each
case in the structure. If there is a match, the
block of code associated with that case is
executed. Use break to prevent the code
from running into the next case
automatically.
43http://www.tutorial.techaltum.com
Switch Statement
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5: document.write("Finally Friday");
break;
case 6: document.write("Super Saturday");
break;
case 0: document.write("Sleepy Sunday");
break;
default: document.write("I'm looking forward to this weekend!");
} </script>
44http://www.tutorial.techaltum.com
JavaScript Functions
O A function is a reusable code-block that will be executed by an
event, or when the function is called.
O To keep the browser from executing a script when the page
loads, you can put your script into a function.
O A function contains code that will be executed by an event or
by a call to that function.
O You may call a function from anywhere within the page (or
even from other pages if the function is embedded in an
external .js file).
O Functions can be defined both in the <head> and in the
<body> section of a document. However, to assure that the
function is read/loaded by the browser before it is called, it
could be wise to put it in the <head> section.
45http://www.tutorial.techaltum.com
How to Define a
Function
O The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{
some code
}
O var1, var2, etc are variables or values
passed into the function. The { and the }
defines the start and end of the function.
46http://www.tutorial.techaltum.com
How to Define a
Function (cont)
O Note: A function with no parameters must include
the parentheses () after the function name:
function functionname()
{
some code
}
O Note: Do not forget about the importance of
capitals in JavaScript! The word function must be
written in lowercase letters, otherwise a JavaScript
error occurs! Also note that you must call a function
with the exact same capitals as in the function
name. 47http://www.tutorial.techaltum.com
The return Statement
O The return statement is used to specify the value that is
returned from the function.
O Example
O The function below should return the product of two numbers
(a and b):
function prod(a,b)
{
x=a*b;
return x;
}
O When you call the function above, you must pass along two
parameters:
O product=prod(2,3);
O The returned value from the prod() function is 6, and it will be
stored in the variable called product. 48http://www.tutorial.techaltum.com
The Lifetime of JavaScript
Variables
O When you declare a variable within a function, the
variable can only be accessed within that function.
When you exit the function, the variable is destroyed.
These variables are called local variables. You can
have local variables with the same name in different
functions, because each is recognized only by the
function in which it is declared.
O If you declare a variable outside a function, all the
functions on your page can access it. The lifetime of
these variables starts when they are declared, and
ends when the page is closed.
49
http://www.tutorial.techaltum.com
Thanks
50
Visit our website : techaltum.com
Online Tutorial : tutorial.techaltum.com
http://www.tutorial.techaltum.com

More Related Content

What's hot

Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903DouglasPickett
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Even Faster Web Sites at The Ajax Experience
Even Faster Web Sites at The Ajax ExperienceEven Faster Web Sites at The Ajax Experience
Even Faster Web Sites at The Ajax ExperienceSteve Souders
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllersmussawir20
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 

What's hot (20)

Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903Sourcerer and Joomla! rev. 20130903
Sourcerer and Joomla! rev. 20130903
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Even Faster Web Sites at The Ajax Experience
Even Faster Web Sites at The Ajax ExperienceEven Faster Web Sites at The Ajax Experience
Even Faster Web Sites at The Ajax Experience
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
php part 2
php part 2php part 2
php part 2
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 
Smarty
SmartySmarty
Smarty
 
On Web Browsers
On Web BrowsersOn Web Browsers
On Web Browsers
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
jQuery
jQueryjQuery
jQuery
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
 

Viewers also liked

Learn Angular JS for Beginners - Lite
Learn Angular JS for Beginners - LiteLearn Angular JS for Beginners - Lite
Learn Angular JS for Beginners - Liteayman diab
 
jQuery tutorial
jQuery tutorialjQuery tutorial
jQuery tutorialToad Xu
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginnersMunir Hoque
 
Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3Matt Raible
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrapZunair Sagitarioux
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Cedric Spillebeen
 
Comportamientos y reglas sociales
Comportamientos y reglas socialesComportamientos y reglas sociales
Comportamientos y reglas socialesKefas Jhs
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to BootstrapRon Reiter
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 

Viewers also liked (10)

Learn Angular JS for Beginners - Lite
Learn Angular JS for Beginners - LiteLearn Angular JS for Beginners - Lite
Learn Angular JS for Beginners - Lite
 
jQuery tutorial
jQuery tutorialjQuery tutorial
jQuery tutorial
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginners
 
Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3Refreshing Your UI with HTML5, Bootstrap and CSS3
Refreshing Your UI with HTML5, Bootstrap and CSS3
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
 
Comportamientos y reglas sociales
Comportamientos y reglas socialesComportamientos y reglas sociales
Comportamientos y reglas sociales
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to Bootstrap
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Similar to Javascript tutorial

Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programminghchen1
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)Shrijan Tiwari
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentationJohnLagman3
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPTGo4Guru
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application developmentzonathen
 
JavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJonnJorellPunto
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Lookrumsan
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptxachutachut
 
Javascript survival for CSBN Sophomores
Javascript survival for CSBN SophomoresJavascript survival for CSBN Sophomores
Javascript survival for CSBN SophomoresAndy de Vera
 

Similar to Javascript tutorial (20)

Javascript
JavascriptJavascript
Javascript
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
An Introduction to Ajax Programming
An Introduction to Ajax ProgrammingAn Introduction to Ajax Programming
An Introduction to Ajax Programming
 
Session vii(java scriptbasics)
Session vii(java scriptbasics)Session vii(java scriptbasics)
Session vii(java scriptbasics)
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
Web programming
Web programmingWeb programming
Web programming
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application development
 
JavaScript - Getting Started.pptx
JavaScript - Getting Started.pptxJavaScript - Getting Started.pptx
JavaScript - Getting Started.pptx
 
Java Script
Java ScriptJava Script
Java Script
 
Javascript
JavascriptJavascript
Javascript
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scripting
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptx
 
Lect35 javascript
Lect35 javascriptLect35 javascript
Lect35 javascript
 
Javascript survival for CSBN Sophomores
Javascript survival for CSBN SophomoresJavascript survival for CSBN Sophomores
Javascript survival for CSBN Sophomores
 
Web Designing
Web DesigningWeb Designing
Web Designing
 

Recently uploaded

Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptxAneriPatwari
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...Introduction to Research ,Need for research, Need for design of Experiments, ...
Introduction to Research ,Need for research, Need for design of Experiments, ...
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 
ARTERIAL BLOOD GAS ANALYSIS........pptx
ARTERIAL BLOOD  GAS ANALYSIS........pptxARTERIAL BLOOD  GAS ANALYSIS........pptx
ARTERIAL BLOOD GAS ANALYSIS........pptx
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 

Javascript tutorial

  • 1. HTML Scripts Visit our website : techaltum.com Online Tutorial : tutorial.techaltum.com Made By: Avinash Malhotra1http://www.tutorial.techaltum.com
  • 2. Scripts O In computer programming, a script is a program or sequence of instructions that is interpreted or carried out by another program rather than by the computer processor (as a compiled program is). O Some languages have been conceived expressly as script languages. Among the most popular are Perl, Rexx (on IBM mainframes), JavaScript, and Tcl/Tk. O In the context of the World Wide Web, Perl, VBScript, and similar script languages are often written to handle forms input or other services for a Web site and are processed on the Web server. O A JavaScript script in a Web page runs "client-side" on the Web browser. 2http://www.tutorial.techaltum.com
  • 3. HTML Scripts (cont) O With HTML scripts you can create dynamic web pages, make image rollovers for really cool menu effects, or even validate your HTML form's data before you let the user submit. However, javascript and vbscript are very complicated compared to HTML. It may be simpler just to download someone elses scripting code and use it on your web page. 3http://www.tutorial.techaltum.com
  • 4. HTML Javascript Code O If you want to insert javascript code into your HTML you are going to use the script tag. O Below is the correct code to insert embedded javascript code onto your site. <script type="text/javascript"> <!--script ***Some javascript code should go here*** --> </script> 4http://www.tutorial.techaltum.com
  • 5. The Name "JavaScript" O The name JavaScript is owned by Netscape. O Microsoft calls its version of the language JScript. O The generic name of the language is EcmaScript. 5http://www.tutorial.techaltum.com
  • 6. The HTML DOM O The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object hierarchy, starting with the browser window itself and moving deeper into the page, including all of the elements on the page and their attributes. 6http://www.tutorial.techaltum.com
  • 7. Simplified Version of HTML DOM 7http://www.tutorial.techaltum.com
  • 8. Introduction to JavaScript O JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. O JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, and Opera. O Before you continue you should have a basic understanding of HTML 8http://www.tutorial.techaltum.com
  • 9. What is JavaScript? O JavaScript was designed to add interactivity to HTML pages O JavaScript is a scripting language O A scripting language is a lightweight programming language O A JavaScript consists of lines of executable computer code O A JavaScript is usually embedded directly into HTML pages O JavaScript is an interpreted language (means that scripts execute without preliminary compilation) O Everyone can use JavaScript without purchasing a license 9http://www.tutorial.techaltum.com
  • 10. Are Java and JavaScript the Same? O NO! O Java and JavaScript are two completely different languages in both concept and design! O Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++. 10http://www.tutorial.techaltum.com
  • 11. What can a JavaScript Do? O 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 O JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page O 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 O JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element 11http://www.tutorial.techaltum.com
  • 12. What can a JavaScript Do? (cont) O 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 O 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 O JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer 12http://www.tutorial.techaltum.com
  • 13. JavaScript Basic Rules O JavaScript statements end with semi- colons. O JavaScript is case sensitive. O JavaScript has two forms of comments: O Single-line comments begin with a double slash (//). O Multi-line comments begin with "/*" and end with "*/". 13http://www.tutorial.techaltum.com
  • 14. Comment Syntax O Syntax // This is a single-line comment /* This is a multi-line comment. */ 14http://www.tutorial.techaltum.com
  • 15. O Enter any two value from user show its addition multiplication subtraction and division O Enter 5 subject marks from the user show its total Enter km and show in meter. O marks and its percentage (%) O Enter meter and show in km O Enter the tem.. In dc and show in Fahrenheit. Questions ... 15http://www.tutorial.techaltum.com
  • 16. Dot Notation O In JavaScript, objects can be referenced using dot notation, starting with the highest- level object (i.e, window). Objects can be referred to by name or id or by their position on the page. For example, if there is a form on the page named "loginform", using dot notation you could refer to the form as follows: O Syntax window.document.loginform O Another example is: document.write // write is a method for document 16http://www.tutorial.techaltum.com
  • 17. Document Object Methods Method Description close() Closes an output stream opened with the document.open() method, and displays the collected data getElementById() Returns a reference to the first object with the specified id getElementsByName() Returns a collection of objects with the specified name getElementsByTagName() Returns a collection of objects with the specified tagname open() Opens a stream to collect the output from any document.write() or document.writeln() methods write() Writes HTML expressions or JavaScript code to a document writeln() Identical to the write() method, with the addition of writing a new line character after each expression 17http://www.tutorial.techaltum.com
  • 18. write method O <html> O <body> O <script type="text/javascript"> O document.write("Hello World!"); O </script> O </body> O </html> Output Hello World! 18http://www.tutorial.techaltum.com
  • 19. Example Explained O To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the "type=" attribute to define the scripting language. O So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends. O The word document.write is a standard JavaScript command for writing output to a page. 19http://www.tutorial.techaltum.com
  • 20. write method (cont) O <html> O <body> O <script type="text/javascript"> O document.write("<h1>This is a header</h1>"); O </script> O </body> O </html> Output This is a header20http://www.tutorial.techaltum.com
  • 21. write method (cont) <html> <body> <script type="text/javascript"> document.write("<h1>This is a header</h1>"); document.write("<p>This is a paragraph</p>"); document.write("<p>This is another paragraph</p>"); </script> </body> </html> 21http://www.tutorial.techaltum.com
  • 22. JavaScript Variables O Variables are "containers" for storing information. O Variables can be used to hold values O Example: x=5;  length=66.10; 22http://www.tutorial.techaltum.com
  • 23. JavaScript Variables (cont) O A variable can have a short name, like x, or a more describing name like length.   O A JavaScript variable can also hold a text value like in carname="Volvo". O Rules for JavaScript variable names: O Variable names are case sensitive (y and Y are two different variables) O Variable names must begin with a letter or the underscore character O NOTE:  Because JavaScript is case- sensitive, variable names are case- sensitive. 23http://www.tutorial.techaltum.com
  • 24. JavaScript Variables (cont) <html> <body> <script type="text/javascript"> var firstname; firstname="Hege"; document.write(firstname); document.write("<br />"); firstname="Tove"; document.write(firstname); </script> <p>The script above declares a variable, assigns a value to it, displays the value, change the value, and displays the value again.</p> </body> </html> 24http://www.tutorial.techaltum.com
  • 25. Assigning Values to Undeclared JavaScript VariablesO If you assign values to variables that has not yet been declared, the variables will automatically be declared. O If you redeclare a JavaScript variable, it will not lose its original value. O var x=5; O var x; O After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it. 25http://www.tutorial.techaltum.com
  • 26. JavaScript Operators O The assignment operator = is used to assign values to JavaScript variables. O Arithmetic operators are used to perform arithmetic between variables and/or values. 26http://www.tutorial.techaltum.com
  • 27. JavaScript Operators (cont) O Given that y=5, the table below explains the arithmetic operators: Sign Description Example Result + Addition x=y+2 x=7 - Subtraction x=y-2 x=3 * Multiplication x=y*2 x=10 / Division x=y/2 x=2.5 % Modulus (division remainder) x=y%2 x=1 ++ Increment x=++y x=6 -- Decrement x=--y x=4 27http://www.tutorial.techaltum.com
  • 28. JavaScript Assignment Operators O Assignment operators are used to assign values to JavaScript variables. O Given that x=10 and y=5, the table below explains the 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 28http://www.tutorial.techaltum.com
  • 29. The + Operator Used on Strings O The + operator can also be used to add string variables or text values together. O To add two or more string variables together, use the + operator. txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; O After the execution of the statements above, the variable txt3 contains "What a verynice day". 29http://www.tutorial.techaltum.com
  • 30. Adding Strings and Numbers O Look at these examples: x=5+5; document.write(x); x="5"+"5"; document.write(x); x=5+"5"; document.write(x); x="5"+5; document.write(x); O The rule is: O If you add a number and a string, the result will be a string. 10 55 55 55 30http://www.tutorial.techaltum.com
  • 31. JavaScript Comparison and Logical Operators O Comparison and Logical operators are used to test for true or false. O Comparison operators are used in logical statements to determine equality or difference between variables or values. 31http://www.tutorial.techaltum.com
  • 32. JavaScript Comparison and Logical Operators (cont) O Given that x=5, the table below explains the comparison operators: Sign Description Example == is equal to x==8 is false === 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 32http://www.tutorial.techaltum.com
  • 33. How Can it be Used O Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document.write("Too young"); 33http://www.tutorial.techaltum.com
  • 34. Logical Operators O Logical operators are used in determine the logic between variables or values. O Given that x=6 and y=3, the table below explains the logical operators: Sign Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true 34http://www.tutorial.techaltum.com
  • 35. Conditional Operator O JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. O Syntax variablename=(condition)?value1:value2  O Example greeting=(visitor=="PRES")?"Dear President ":"Dear "; O If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear President " else it will be assigned "Dear". 35http://www.tutorial.techaltum.com
  • 36. JavaScript If...Else Statements O Conditional statements in JavaScript are used to perform different actions based on different conditions. O In JavaScript we have the following conditional statements: O if statement - use this statement if you want to execute some code only if a specified condition is true O if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false O if...else if....else statement - use this statement if you want to select one of many blocks of code to be executed O switch statement - use this statement if you want to select one of many blocks of code to be executed 36http://www.tutorial.techaltum.com
  • 37. If Statement O You should use the if statement if you want to execute some code only if a specified condition is true. O Syntax if (condition) { code to be executed if condition is true } O Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error! 37http://www.tutorial.techaltum.com
  • 38. If Statement Example 1 <script type="text/javascript"> //Write a "Good morning" greeting if //the time is less than 10 var d=new Date(); var time=d.getHours(); if (time<10) { document.write("<b>Good morning</b>"); } </script> 38http://www.tutorial.techaltum.com
  • 39. If Statement Example 2 <script type="text/javascript"> //Write "Lunch-time!" if the time is 11 var d=new Date(); var time=d.getHours(); if (time==11) { document.write("<b>Lunch-time!</b>"); } </script> 39http://www.tutorial.techaltum.com
  • 40. If...else Statement O If you want to execute some code if a condition is true and another code if the condition is not true, use the if....else statement. O Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } 40http://www.tutorial.techaltum.com
  • 41. If...else Statement Example<script type="text/javascript"> //If the time is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day“greeting. var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } </script> 41http://www.tutorial.techaltum.com
  • 42. JavaScript Switch Statement O You should use the switch statement if you want to select one of many blocks of code to be executed. O Syntax 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 } 42http://www.tutorial.techaltum.com
  • 43. JavaScript Switch Statement (cont) O This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. 43http://www.tutorial.techaltum.com
  • 44. Switch Statement Example <script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm looking forward to this weekend!"); } </script> 44http://www.tutorial.techaltum.com
  • 45. JavaScript Functions O A function is a reusable code-block that will be executed by an event, or when the function is called. O To keep the browser from executing a script when the page loads, you can put your script into a function. O A function contains code that will be executed by an event or by a call to that function. O You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file). O Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the <head> section. 45http://www.tutorial.techaltum.com
  • 46. How to Define a Function O The syntax for creating a function is: function functionname(var1,var2,...,varX) { some code } O var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function. 46http://www.tutorial.techaltum.com
  • 47. How to Define a Function (cont) O Note: A function with no parameters must include the parentheses () after the function name: function functionname() { some code } O Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. 47http://www.tutorial.techaltum.com
  • 48. The return Statement O The return statement is used to specify the value that is returned from the function. O Example O The function below should return the product of two numbers (a and b): function prod(a,b) { x=a*b; return x; } O When you call the function above, you must pass along two parameters: O product=prod(2,3); O The returned value from the prod() function is 6, and it will be stored in the variable called product. 48http://www.tutorial.techaltum.com
  • 49. The Lifetime of JavaScript Variables O When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. O If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed. 49 http://www.tutorial.techaltum.com
  • 50. Thanks 50 Visit our website : techaltum.com Online Tutorial : tutorial.techaltum.com http://www.tutorial.techaltum.com