+ All Categories
Home > Documents > 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language...

1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language...

Date post: 28-Mar-2015
Category:
Upload: mary-gonzales
View: 218 times
Download: 0 times
Share this document with a friend
Popular Tags:
40
1 JavaScript James Ohene-Djan Sandbox 2013
Transcript
Page 1: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

1

JavaScript

James Ohene-Djan

Sandbox 2013

Page 2: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

2

What is JavaScript? • JavaScript a scripting language developed to provide interactivity or

behaviour to otherwise static HTML pages• JavaScript, 1995, Netscape (c/w HTML, 1991)• Jscript, 1996, Microsoft• ECMAScript, standardized version of Jscript

• JavaScript consists of lines of executable computer code and is usually embedded directly in HTML pages;

• JavaScript is an interpreted language;

• JavaScript can be used freely, and is supported by all major browsers (e.g. Netscape 4.5 + and Internet Explorer 4 + are augmented with JavaScript/Jscript interpreter – both of which are based on ECMAScript);

• Client-side.

Page 3: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

3

What is JavaScript used for? • Lots of things, including:

– Dynamic page elements;– Link confirmation;– Client side calculations;– Animated buttons;– Browser detection;– Cookies;– Client side form validation;– Drop down menus.

• And more recently:

– XML;– Scripted HTTP / Ajax (XMLHttpRequest);– Third party APIs

• http://developer.yahoo.com/yuim• http://code.google.com/apis/gears/• http://dev.live.com/virtualearth/

Page 4: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

4

JavaScript basics JavaScript is usually embedded inside HTML documents

using the <script> tag.

For example:<html><head><title>JavaScript1</title></head><body>

<script type="text/javascript">alert("My very first JavaScript");</script>

</body></html>

Page 5: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

5

JavaScript can be placed in either the head or the body of an HTML document.

Scripts in the head section are executed only when they are called, or when a particular event occurs.

<html><head><title>JavaScript2</title><script type="text/javascript">function aFunction(){alert("Thanks for that");}</script></head><body><form name="aForm"><input type="button" value="Click Here" onclick="aFunction()"></form></body></html>

Page 6: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

6

Scripts in the body section will be executed when the page loads. Here the document.write() method is used to dynamically output HTML text into an HTML document while it is being loaded into the browser

<html><head><title>JavaScript3</title></head><body><script type="text/javascript">document.write("<h1>In the body section</h1>");</script></body></html>

Page 7: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

7

A web browser makes use of objects that can also be used in JavaScript programming. Each object has associated methods.

Types of ObjectObjects of predefined classes

Date, String, Math,….

Browser objectswindow, document,….

HTML objectslink, form, button,….

Page 8: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

8

Browser objects• the starting point for most JavaScript programs. Initiated

at browser startup• examples

window

document

location

history

navigator

Page 9: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

9

window object – the window in which an html page loads

methods– open(), close(), alert(), confirm(), prompt()

example<html><head><title>JavaScript4</title><head>

<body>

<h1>Window 1</h1>

<script type="text/javascript"> var newWindow;newWindow = window.open("http://www.bbc.co.uk");</script>

</body>

</html>

Page 10: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

10

document object – the current html page

methods– write(), open(), ….

example<html><head><title>JavaScript5</title><script type="text/javascript">function docOpen(){document.open()document.write("<h3>Hello World!</h3>")}</script></head>

<body><script type="text/javascript"> document.write("<h1>This heading was created on-the-fly</h1>");</script><form><input type="button" onclick="docOpen()" value="Open a new document"></form>

</body></html>

Page 11: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

11

location object - provides information about the origin of an html document, can be used to control the web page displayed by the browser.

Methods– reload(), replace()

attributes– host, href, pathname, port, protocol

example <html><head><title>JavaScript6</title></head><center><script type="text/javascript"> document.write("href= " + location.href + "<br>");document.write("pathname= " + location.pathname + "<br>");document.write("protocol= " + location.protocol);</script></centre></html>

Page 12: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

12

navigator object – provides information about the user’s browser

attributes– appCodeName, appName, appVersion, platform, userAgent

example<html><head><title>JavaScript7</title></head><center><h1>Elements of the navigator object</h1>You are using the following browser:<p><script type="text/javascript"> document.write("<table border=1 width=50%>");document.write("<td>appCodeName</td>")document.write("<td>" + navigator.appCodeName);document.write("</td><tr>");document.write("<td>appName</td>")document.write("<td>" + navigator.appName);document.write("</td><tr>");document.write("<td>appVersion</td>")document.write("<td>" + navigator.appVersion);document.write("</td><tr>");document.write("<td>platform</td>")document.write("<td>" + navigator.platform);document.write("</td><tr>");document.write("<td>userAgent</td>")document.write("<td>" + navigator.userAgent);document.write("</td><tr>");document.write("</table>");</script></center></html>

Page 13: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

13

Prefined classes

• Belong to ECMAScript language standard• Examples

– Date, String, Math <html><head><title>JavaScript8</title></head><body><script type="text/javascript">var d = new Date()document.write(d.getDate())document.write(".")document.write(d.getMonth() + 1)document.write(".")document.write(d.getFullYear())</script></body></html>

Page 14: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

14

Pop up windows - alert

<html><head><title>JavaScript9</title><head><title>Alert Example</title></head>

<body>

<script type="text/javascript">alert("This Site Is Not Suitable for Anybody Over the Age of 30");</script>

</body>

</html>

Page 15: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

15

Pop up windows - confirm<html><head><title>JavaScript10</title></head><body>

<script type="text/javascript">var reply;reply=confirm("Do you agree?");if (reply){ alert("GOOD!");}else{ alert("NEVER MIND.");}</script>

</body></html>

Page 16: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

16

Pop up windows - prompt

<html><head><title>JavaScript11</title></head>

<body>

<script type="text/javascript">username=prompt("Please enter your name","Enter your name here"); document.write("<h2>Hello "+username+" Welcome to My

Homepage</h2><br>")</script>

</body></html>

Page 17: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

17

Variables and Operators • Variables should be declared/defined using the var command. Variables should start

with a letter and not contain any embedded spaces

• Assigning a value to an undeclared variable implicitly declares the variable (globally)

• Attempting to read the value of an undeclared variable causes a runtime error

• Values are most commonly assigned to variables using the = operator.

<html><head><title>JavaScript12</title></head><body>

<script type="text/javascript">var username;var age;username="bjones";age=32;document.write(username);document.write(age);</script>

</body></html>

Page 18: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

18

Arithmetic operators

Operator Description Example Result (y)

+ Addition x=5y=x+3

8

- Subtraction x=5y=12-x

7

* Multiplication x=3y=x*4

12

/ Division y=16/5 3.2

% Modulus (division remainder)y=11%4

3

++ Increment y=9y++

10

-- Decrement y=23y--

22

Page 19: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

19

Assignment operators

Example Is The Same As

x=y x=y

x+=y x=x+y

x-=y x=x-y

x*=y x=x*y

x/=y x=x/y

x%=y x=x%y

Page 20: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

20

Comparison operators

Operator Explanation

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

Page 21: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

21

Concatenate two strings using the + operator

<html><head><title>JavaScript13</title></head><body>

<script type="text/javascript">text1="Welcome to"text2="my homepage."document.write(text1+text2);document.write("<br>")document.write(text1+" "+text2);</script>

</body></html>

Page 22: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

22

Selection - if (condition) {action1} else {action2} <html><head><title>JavaScript14</title></head><body>

<script type="text/javascript">var d = new Date()var time = d.getHours()if (time < 12) { document.write("<b>Good morning</b>")}else{ document.write("<b>Good afternoon</b>")}</script>

</body></html>

Page 23: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

23

Logical operators: AND, OR and NOT <html><head><title>JavaScript16</title></head><body>

<script type="text/javascript">

cw1_grade=parseInt(prompt("Please enter your mark for cw1","1"));cw2_grade=parseInt(prompt("Please enter your mark for cw2","1"));

if (cw1_grade && cw2_grade){

document.write("Well done you passed")}else if ((cw1_grade && !cw2_grade) || (!cw1_grade && cw2_grade))

document.write("Sorry, but you have failed - but only just");else

document.write("Sorry, you have failed big time");

</script>

</body></html>

Page 24: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

24

Functions

• A function contains code that will be executed by an event or a call to that function. Functions are usually defined at the beginning of a .html file (in the head section) or as an external function in a separate file altogether (.js file).

• A function is defined with a name, values ("arguments") and statements. Functions can return a value to the calling expression.

Page 25: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

25

Function example1<html><head><title>JavaScript17</title><script type="text/javascript">function AddTwoNumbers(n1,n2){ answer=n1+n2 return(answer)}</script></head>

<body><script type="text/javascript">x=parseInt(prompt("Input first number","Number1 goes here")); y=parseInt(prompt("Input second number","Number2 goes here")); sum=AddTwoNumbers(x,y);document.write("The sum of the two numbers is "+sum+"<br>");</script></body></html>

Page 26: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

26

Function example1<html><head><title>JavaScript18</title><script SRC="javascript18.js"></script></head>

<body><script type="text/javascript">x=parseInt(prompt("Input first number","Number1 goes here")); y=parseInt(prompt("Input second number","Number2 goes here")); sum=AddTwoNumbers(x,y);document.write("The sum of the two numbers is "+sum+"<br>");</script></body></html>

function AddTwoNumbers(n1,n2){ answer=n1+n2 return(answer)}

.html file

javascript18.js

Page 27: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

27

JavaScript Loops

<html><head><title>JavaScript19</title></head><body><table border=3><tr><td>INCHES</td><td>CMs</td></tr><script type="text/javascript"> for (inches=1; inches<=30; inches=inches+1){ document.write("<tr><td>"+inches+"</td><td>"+(inches*2.54)+"</td></tr>");}</script></table></body></html>

Page 28: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

28

<html><head><title>JavaScript20</title></head><body><table border=3><tr><td>mile</td><td>km</td></tr><script type="text/javascript"> mile=5while (mile <= 100){ document.write("<tr><td>"+mile+"</td><td>"+(mile*1.6093)+"</td></tr>"); mile=mile+5}</script></table></body></html>

Page 29: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

29

JavaScript Arrays<html><head><title>JavaScript21</title></head><body>

<script type="text/javascript">var cities = new Array()cities[0] = " london"cities[1] = " paris"cities[2] = " rome"

for (i=0;i<cities.length;i++){document.write(cities[i] + "<br />")}</script>

</body></html>

Page 30: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

30

Array - sort<html><head><title>JavaScript22</title></head><body>

<script type="text/javascript">

var arr = new Array(6)arr[0] = "evans"arr[1] = "smith"arr[2] = "davies"arr[3] = "collins"arr[4] = "bowen"arr[5] = "thomas"

document.write(arr + "<br />")document.write(arr.sort())</script>

</body></html>

Page 31: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

31

Last Updated Script

<html><head><title>JavaScript23</title></head><body><script type="text/javascript"> <!-- document.write('<center>Last updated : ');document.write(document.lastModified);document.write('</center>');// --></script></body></html>

Notice the use of HTML comment (<!--and -->) and JavaScript comment (//). These are used to prevent browsers that do not support JavaScript from writing the JavaScript code to the screen as text.

Page 32: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

32

Browser Detection <html><head><title>JavaScript24</title><script type="text/javascript">alert(navigator.appName);if (navigator.appName.indexOf("Microsoft")!=-1) window.location.href = "http://www.microsoft.com";else if (navigator.appName.indexOf("Netscape")!=-1) window.location.href = "http://www.netscape.com";else document.write("Browser "+navigator.appName+" not supported");</script></head><body></body></html>

Makes use of the navigator object and the indexOf method. The navigator object holds name, version, etc. details of the browser. The indexOf() method returns the index value for where the parameter you give it first appears in the string it is invoked on, or the value -1 if the parameter (string) does not appear.

Page 33: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

33

Animated Buttons

<html><head><title>JavaScript25</title></head><body>

<a href="http://www.gold.ac.uk" onmouseOver="document.button1.src = 'computing-select.jpg'" onmouseOut="document.button1.src = 'computing-norm.jpg'"> <Img Src="computing-norm.jpg" name="button1" border=0 ></a>

</body></html>

Page 34: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

34

Onclick event

<html><head><title>JavaScript27</title></head><body><center>SELECT A BACKGROUND COLOUR.<p>

<form> <input type=button value="Blue" onclick='document.bgColor="Blue";'> <input type=button value="Green“ onclick='document.bgColor="Green";'> <input type=button value="Red " onclick='document.bgColor="Red";'>

</form></body></html>

Page 35: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

35

<html><head><title>JavaScript28</title><script type="text/javascript">function validate_email(){found_at=document.form1.email_address.value.indexOf("@")if (found_at == -1)

{alert("Not a valid e-mail")return false}

}</script></head><body><form name="form1"action=”form_ok.html"onsubmit="return validate_email()">Enter your E-mail address:<input type="text" name="email_address"> <input type="submit" value="Send input"> </form></body></html>

Form Validation – simple check for valid email

Page 36: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

form_ok.html

36

<html>

<head>

<title>Form Validation Example 1</title>

</head>

<body>

<h1>Form has been sent</h1>

</body>

</html>

Page 37: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

37

<html><head><title>JavaScript29</title><script type="text/javascript">

function validate_email(e_address){ var emailFilter=/^.+@.+\..{2,3}$/; var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/

if (!(emailFilter.test(e_address))) {

alert("Not a valid e-mail");return false;

} if (e_address.match(illegalChars)) { alert("Not a valid e-mail"); return false; }}</script></head>

<body><form name="form1"

action="http://www.comp.glam.ac.uk/pages/staff/jmware/form_ok.html"onsubmit="return validate_email(email_address.value)">Enter your E-mail address:<input type="text" name="email_address"> <input type="submit" value="Send input">

</form></body></html>

Form Validation – less simple check for valid email

Page 38: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

38

<html><head><title>JavaScrip30</title><script type="text/javascript">function validate(){ day=document.myForm.day.value; if ( (parseInt(day) < 1) || (parseInt(day) > 31) ) { alert("day field invalid"); document.myForm.day.focus(); return false; } month=document.myForm.month.value.toLowerCase(); if ( (month!="jan") && (month!="feb") && (month!="mar") && (month!="apr") && (month!="may") && (month!="jun") && (month!="jul") && (month!="aug") && (month!="sep") && (month!="oct") && (month!="nov") && (month!="dec") ) { alert("invalid month"); document.myForm.month.focus(); return false; } year=document.myForm.year.value; current = new Date(); if (year != current. getFullYear()()) { alert("invalid year - only taking bookings for current year"); document.myForm.year.focus(); return false; } return true}</script></head><body><form name="myForm" action="valid_page.html" onsubmit="return validate()"> Please supply required departure date<br><br>Day <input type="text" name="day" size=1 maxlength=2 value="01"><br>Month <input type="text" size=1 maxlength=3 value ="jan" name="month"><br>Year <input type="text" size=2 maxlength=4 value ="2003" name="year"><br><br> <input type="submit" value="validate date"></form></body></html>

Simple date validation

Page 39: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

39

javascript31.html – will work in its own right (but slowly the first time you load it)

<html><head><title>javascript31</title></head><body><img src="http://heritage.stsci.edu/2003/06/dumbbell/0306a.jpg" width=300 height=300><img src="http://heritage.stsci.edu/2001/24/mars/0124a.jpg" width=300 height=300><img src="http://heritage.stsci.edu/2001/15/saturn/0115a.jpg" width=300 height=300></body></html>

Pre-loading media

Page 40: 1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

40

javascript32.html – preloads images, user might (or might not) visit display page

<html><head><title>javascript32</title><script type="text/javascript"> if (document.images) { img1 = new Image(); img1.src = "http://heritage.stsci.edu/2003/06/dumbbell/0306a.jpg"; img2 = new Image(); img2.src = "http://heritage.stsci.edu/2001/24/mars/0124a.jpg"; img3 = new Image(); img3.src = "http://heritage.stsci.edu/2001/15/saturn/0115a.jpg";}</SCRIPT></head><body><a href="javascript31.html">Show Image</a></body></html>

Test out above – effect will only be properly demonstrated if you delete temporary internet files before executing preloadimage.html (in browser select Tools->Internet Options->Delete Files


Recommended