Javascript

advertisement
Javascript Introduction
Norman White
Material is from w3schools.com
Go there to run examples interactively
Javascript overview
• JS is the primary scripting language for
browsers.
– Supported by virtually all browsers
– It is code that that is embedded in the html
and allows logic to be added that runs on the
client instead of the server.
– JS can dynamically change the content of the
web page after it is downloaded
– Official standard is ECMAScript-262
Javascript Advantages
• JS runs on then browser, not the server.
– Can dramatically reduce network traffic back to the server.
– Move processing from the server to the browser,
reduces/eliminates processing on the server.
– If running on a mobile device, Javascript allows access to native
mobile device capabilities through the Phone gap library.
– Javascript, CSS 3 and HTML 5 will allow us to develop web
pages that automatically display correctly on different devices,
including mobile.
• Many JS Libraries available, especially JQUERY
and JQUERY Mobile.
How do we use Javascript
• Insert JS code directly into the html document,
or include it from a file or the web.
• The browser will execute the JS code when it
sees it in the document.
• IMPORTANT
– JS is running on the browser NOT the server!
– JS may need to retrieve information from a server.
We will talk about that later.
Things JS can do
• React to events
–
–
–
–
–
Mouse over
Mouse click
Page load
Form submit
…
• Change the html code dynamically depending
on events
• Detect users browser
• Manage Cookies
How to insert dynamic content into html
<html>
<body>
<h1>My First Web Page</h1>
<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>
</body>
</html>
Hiding JS on browsers that don’t support it
Surround it in comments
<html>
<body>
<script type="text/javascript">
<!-document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>
Controlling when JS executes
• We may not want to execute it when/as
the page loads, but after some event.
– Like:
• User does something
• Page is completely loaded
•…
Better is to just change the <p> element
Avoids rewriting complete document
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo"></p>
<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>
JS Functions
•
•
•
•
•
•
<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>
JS can be in external files
<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>
JS Blocks
Code can be grouped into blocks with { }
<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>");
}
</script>
Comments
• Single line comments start with //
– // this is a single line comment
• Or
• Some code // comment at the end of the line
• Multiline comments start with /* and end with */
– This is a multi-line comment
/*
Some comments
Some more comments
*/
Variables
• Variables can take on different values at
different times
• Variable names are case sensitive
• Names have to start with a letter, a $ or an
underscore
• Variables that hold text have to have the
text in quotes,i.e.
Myvar=“Hello”
Local and Global variables
Local variables are declared in a function with the var
declaration, i.e.
var x;
These variables only exist inside the function. i.e. created
when the function is entered and deleted when it exits
Global variables are declared outside a function, or without
the “var” keyword in a function
Global variables can be used anywhere on the web page,
not just in the function they were created.
Arithmetic operators
(assume y = 5)
Operator
+
*
/
%
++
Description
Addition
Subtraction
Multiplication
Division
--
Decrement
Modulus
(division remainder)
Increment
Example
x=y+2
x=y-2
x=y*2
x=y/2
x=y%2
x=++y
x=y++
x=--y
x=y--
Result
x=7
x=3
x=10
x=2.5
x=1
x=6
x=5
x=4
x=5
y=5
y=5
y=5
y=5
y=5
y=6
y=6
y=4
y=4
Assignment operators
assume x=10 and y=5
Operator
=
+=
-=
*=
/=
%=
Example
x=y
x+=y
x-=y
x*=y
x/=y
x%=y
Same As
x=x+y
x=x-y
x=x*y
x=x/y
x=x%y
Result
x=5
x=15
x=5
x=50
x=2
x=0
Strings
+ = concatenation
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
txt3 will be “What a verynice day”
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
txt3 will be
“What a very nice day”
Strings and numbers
• Result of adding strings and numbers is a string….
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
Comparison Operators
x=5
Operator
==
===
!=
>
<
>=
<=
Description
is equal to
Example
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
Use:
If (age<18) document.write(“Too young”);
Logical Operators
x=6 and y=3
Operator
Description
Example
&&
||
!
and
or
not
(x < 10 && y > 1) is true
(x==5 || y==5) is false
!(x==y) is true
Conditional operator
Variablename= (condition)?value1:value2
<script type="text/javascript">
var visitor="PRES";
var greeting=(visitor=="PRES")?"Dear President ":"Dear ";
document.write(greeting);
</script>
Conditional Statements
if
if … else
If .. else if … else
switch
If Statement
if (condition)
{
Code to be executed
}
<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>
If …else
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
<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>
IF…else if…else
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2
is true
}
Switch statement
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Switch example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
var 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>
Popup boxes
alert("sometext");
(user has to click ok)
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>
Confirm box
user clicks OK or Cancel
confirm("sometext");
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>
Prompt box
User can enter new value and click ok, or cancel
prompt("sometext","defaultvalue");
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("<p>Hello " + name + "! How are you today?</p>");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
Functions
(usually defined in head section, so that they are defined before calling)
function functionname(var1,var2,...,varX)
{
some code
}
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
Return statement
Used to return values from functions
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write( product(4,3) );
</script>
</body>
</html>
For Loops
for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed
}
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
While loop
while (variable<=endvalue)
{
code to be executed
}
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
Do while
(execute at least once)
do
{
code to be executed
}
while (variable<=endvalue);
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>
Break statement
Breaks out of a loop
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Continue
break current loop and continue with next value
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
For … in
Loops through values of an object
for (variable in object)
{
code to be executed
}
var person={fname:"John",lname:"Doe",age:25};
var x;
for (x in person)
{
document.write(person[x] + " ");
}
Result:
John Doe 25
Events
Actions that can be detected by JS
<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>
Events
Many events, also functions that can cause
events
Some Examples:
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input field in an HTML form
Submitting an HTML form
A keystroke
onSubmit Event
Used to check form input
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
If checkForm returns “True” form will be submitted, otherwise it will be
cancelled.
This is how we would check form fields or compute the
value of a hidden field like”fchar”
Catching Errors, Try … catch
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
Throw Statement
Generate an error exception
throw exception
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 5 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<5)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(err)
{
if(err=="Err1")
{
document.write("Error! The value is too high.");
}
if(err=="Err2")
{
document.write("Error! The value is too low.");
}
if(err=="Err3")
{
document.write("Error! The value is not a number.");
}
}
</script>
</body>
</html>
Special Characters
Use the “\” to insert special characters
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
INSTEAD use \ to escape the “ so it is interpreted as a
regular character.
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
Other special characters
Code
\‘
\“
\\
\n
\r
\t
\b
\f
Outputs
single quote
double quote
backslash
new line
carriage return
tab
backspace
form feed
Misc
•
JavaScript is Case Sensitive
– A function named "myfunction" is not the same as "myFunction" and a variable
named "myVar" is not the same as "myvar".
– JavaScript is case sensitive - therefore watch your capitalization closely when
you create or call variables, objects and functions.
•
White Space
– JavaScript ignores extra spaces. You can add white space to your script to make
it more readable. The following lines are equivalent:
• var name="Hege";
var name = "Hege";
•
Break up a Code Line
– You can break up a code line within a text string with a backslash. The
example below will be displayed properly:
• document.write("Hello \
World!");
• However, you cannot break up a code line like this:
• document.write \
("Hello World!");
Takeaway
•
•
•
•
Javascript is a large language, many features
Very powerful
Need to be an expert to do “fancy” things
Allows us to move a lot of processing to the client,
reducing communications with server, very important for
mobile devices where we may have limited/no
bandwidth.
• Would be nice if there were some preprogrammed
functions to do useful things
• SOLUTION: The JQUERY library
JQUERY
•
•
•
•
Javascript library that works on most browsers.
Hides many details from developers.
In use at over 50% of large web sites
There is now a JQUERY MOBILE library,
customized for mobile devices
• One statement allows you to use jquery
– <script type=“text/javascript” src=“jquery.js”></script>
• Next time, intro to JQUERY
Download