+ All Categories
Home > Economy & Finance > JavaScript Workshop

JavaScript Workshop

Date post: 17-Aug-2014
Category:
Upload: pamela-fox
View: 10,883 times
Download: 1 times
Share this document with a friend
Description:
Put on by USC's Upsilon Pi Epsilon as part of Wonderful World of Web2.0 Workshop Series. http://pollux.usc.edu/~upe/
26
Sponsored by Upsilon Pi Epsilon The Computer Science Honors Society Javascript
Transcript
Page 1: JavaScript Workshop

Sponsored byUpsilon Pi Epsilon

The Computer Science Honors Society

Javascript

Page 2: JavaScript Workshop

JavaScript: a brief history

• Developed by Netscape Communications Corporation as Mocha, then LiveScript, and finally renamed to JavaScript. • JavaScript was first introduced in Netscape version 2.0B3 in 1995. • In Internet Explorer, “JavaScript” is implemented as JScript, which is not exactly the same.• The latest version of the language is JavaScript 1.7.• ECMAScript is a standardized version of JavaScript.

Page 3: JavaScript Workshop

JavaScript: the basics

<script><script>… … JavaScript code goes here… JavaScript code goes here… </script></script>

• Code Sits Between <script> tags• C/Java style syntax, for the most part• LOOSELY TYPED - more on this later• Can reside in external file also:<script <script src=”someJSFile.js”src=”someJSFile.js”></script>></script>

Page 4: JavaScript Workshop

JavaScript: the basics

<html> <html> <head><head><title>… the title of the document… </title> <title>… the title of the document… </title> <script type="text/Javascript"><script type="text/Javascript">… … JavaScript code… JavaScript code… </script> </script> </head> </head> <body><body>… … HTML Code/Tags/Content whatever… HTML Code/Tags/Content whatever… </body> </body> </html></html>

Page 5: JavaScript Workshop

JavaScript: the basics

•Event Handlers •(most basic html interaction tool)•“onclick”, “onmouseover”, “

onmouseout”, “onload”, “ondoubleclick”, etc.

•Written in the HTML as an attribute

Page 6: JavaScript Workshop

JavaScript: Hello World

<html> <html> <head><head><title>JavaScript-Hello-World</title> <title>JavaScript-Hello-World</title> <script type="text/Javascript"> <script type="text/Javascript">

function greetings(sender) {function greetings(sender) {alert (“Hello World!”); alert (“Hello World!”); } }

</script> </script> </head></head><body <body onLoad="greetings();“onLoad="greetings();“> > <h1>Javascript Hello World!</h1> <h1>Javascript Hello World!</h1> </body> </body> </html></html>

Page 7: JavaScript Workshop

JavaScript: Challenge!• Create a web page with a header that says “Hello

World...”.• When the user roles over the header, change the

text to read “Hello JavaScript!”.• Use an external JavaScript file.• Hint: Use Google to look up “onmouseover”• Hint: Event handlers can pass objects -- think of

the header as an object itself (a DOM object)• Hint: DOM Objects have an “innerHTML” property• Bonus: Change the font and background color

when you role over the text• Be Creative! Add whatever you want, we’ll help.

Page 8: JavaScript Workshop

JavaScript: Types• Number

• String

• Boolean

• Object

• Function

• Array

• Date

• RegExp

• Null

• Undefined

• Variables can hold any type!

Page 9: JavaScript Workshop

JavaScript: Numbers•All numbers are 64 bit floating point

(IEEE)•Familiar parseInt(“123”) syntax to get a

number from a string•Math object contains advanced math

functions•NaN is returned in any operation that

does not result in a valid number•Special Infinity and -Infinity values

Page 10: JavaScript Workshop

JavaScript: Strings•Really just Objects (like almost

everything)•Sequences of Unicode characters•Built-in length, charAt(),

toUpperCase() and other properties•“string literals” are also present

Page 11: JavaScript Workshop

JavaScript: Other Types

•Bools -- just what you think•RegExp -- Regular Expression

Objects•Null -- deliberate “no” value for an

arbitrary variable •Undefined -- variable that has not

even been initialized

Page 12: JavaScript Workshop

JavaScript: Operators•Same as C/C++/Java: ++, +=, +, -, /, *,

“string”, bitwise and/or/not, &&, ||, !, etc...•Boolean expressions •== performs type coercion•0 == False .... “dog” == True•=== is literal comparsion•False === False .... “dog” !== True

•If, Else, For, While, DoWhile, Switch -- same

Page 13: JavaScript Workshop

JavaScript: Objects•In JavaScript, all objects are

collections of name value pairs.•C++ Hash Table, PHP Associative

Array, Cocoa/Python Dictionary •“Name” is a JavaScript string•“Value” is any JavaScript type,

including other Objects

Page 14: JavaScript Workshop

JavaScript: Objectsvar obj= new Object();var obj= new Object();

var Obj { };var Obj { };

Create

obj.name= “John”;obj.name= “John”;

obj[“name”]= “John”;obj[“name”]= “John”;

Add Properties

Object Literal Syntax

var email {var email {message: “Hi Pamela!”,message: “Hi Pamela!”,details: {details: {to: “Pamela”,to: “Pamela”,from: “Ross”from: “Ross”}}}}

Page 15: JavaScript Workshop

JavaScript: Arraysvar a= new Array();var a= new Array();a[0]= “red”;a[0]= “red”;a[1]= “blue;a[1]= “blue;

var a= {“red”, “blue”};var a= {“red”, “blue”};

Create

• Full-fledged JavaScript Objects themselves• Built-in Length property = highest index + 1• Other Built-in methods:a.toString(), a.toLocaleString(), a.concat(item, ..), a.join(sep),a.pop(), a.push(item, ..), a.reverse(), a.shift(), a.slice(start, end),a.sort(cmpfn), a.splice(start, delcount, [item]..), a.unshift([item]..)

Page 16: JavaScript Workshop

JavaScript: Functions

•Very flexible system -- functions are all JavaScript Objects

•Can take any number of named parameters•Parameters not required to be passed in•More parameters can be passed than asked

for in your function•Return either an explicit value, or

undefined

Page 17: JavaScript Workshop

JavaScript: Functions

function add(x, y) {function add(x, y) { var total = x + y;var total = x + y; return total;return total;}}

> add()> add()NaNNaN> add(2, 3)> add(2, 3)55

Page 18: JavaScript Workshop

JavaScript: Functions

function avg() {function avg() { var sum = 0;var sum = 0; for (var i=0, j=arguments.length; i<j; i++) for (var i=0, j=arguments.length; i<j; i++) {{ sum += arguments[i];sum += arguments[i]; }} return sum/arguments.length;return sum/arguments.length;}}

> avg(2, 3, 4, 5)> avg(2, 3, 4, 5)3.53.5> avg.apply(null, [2, 3, 4, 5])> avg.apply(null, [2, 3, 4, 5])3.5 3.5

Page 19: JavaScript Workshop

JavaScript: Functions

•You can assign functions to variables, and do all kinds of crazy things with scope:

•Example, when you say in HTML:•<a onclick=”foo()” id=”bar”></a>

• It’s just like saying bar.onclick= foo in JS

Page 20: JavaScript Workshop

JavaScript: Classes• JavaScript “Classes” are just functions that

initialize new objects (think “constructors”)•“this” refers to the “current” object•“new” is similar to C++ -- call it on

“constructor” functions

function Person(first, last) {function Person(first, last) { this.first = first;this.first = first; this.last = last;this.last = last; this.fullName = function() {this.fullName = function() { return this.first + ' ' + this.last;return this.first + ' ' + this.last; }} this.fullNameReversed = function() {this.fullNameReversed = function() { return this.last + ', ' + this.first;return this.last + ', ' + this.first; }}}}var ross = new Person("Ross", "Boucher");var ross = new Person("Ross", "Boucher");

Page 21: JavaScript Workshop

JavaScript: Classes•Previous method duplicates member

functions for every instance•Alternate approach to creating a class:

function personFullName() {function personFullName() { return this.first + ' ' + this.last;return this.first + ' ' + this.last;}}function personFullNameReversed() {function personFullNameReversed() { return this.last + ', ' + this.first;return this.last + ', ' + this.first;}}function Person(first, last) {function Person(first, last) { this.first = first;this.first = first; this.last = last;this.last = last; this.fullName = personFullName;this.fullName = personFullName; this.fullNameReversed = personFullNameReversed;this.fullNameReversed = personFullNameReversed;}}

Page 22: JavaScript Workshop

JavaScript: Classes•Still another approach, using

Prototype:

function Person(first, last) {function Person(first, last) { this.first = first;this.first = first; this.last = last;this.last = last;}}Person.prototype.fullName = function() {Person.prototype.fullName = function() { return this.first + ' ' + this.last;return this.first + ' ' + this.last;}}Person.prototype.fullNameReversed = function() {Person.prototype.fullNameReversed = function() { return this.last + ', ' + this.first;return this.last + ', ' + this.first;}}var ross= new Person(“Ross”, “Boucher”);var ross= new Person(“Ross”, “Boucher”);

Page 23: JavaScript Workshop

JavaScript: Prototype

•Prototypes are a set of properties shared across all objects of the same type

•In this case, all “Person” objects will have the two methods assigned to Person.prototype

•Forms part of a “lookup chain”•Can add to the prototype of built-in objects•Not to be confused with the library of the

same name

Page 24: JavaScript Workshop

JavaScript: DOM•document is a built in object for

interacting with the DOM•document.getElementById(“string”)

allows you to get a reference to a specific node in your document

•document.createElement(“tag”) allows you to create new elements

•document.createNode(“text”) allows you to create new text nodes

Page 25: JavaScript Workshop

JavaScript: DOM•Documents are made up entirely of nodes•Element Nodes: every tag in your HTML is

an element•Have children nodes, attributes

•Text Nodes: these contain text, and are children of elements like <p> nodes•Have no children or attributes

•Nodes have common methods•nodeType, nodeName, nodeValue

Page 26: JavaScript Workshop

JavaScript: Challenge 2!• Wow, that was a lot of material. Let’s try applying

it!• Create a container DIV, and a few floating divs

inside (hint: assign these inner divs to a class)• Make this look like a few boxes inside a larger box.• Add a link or form button to dynamically add new

divs inside the container (also floated)• Hint: give your container a unique ID so you can

access it with document.getElementById(“myId”);• Hint: use an event handler on the button• Hint: google appendChild()• Bonus: Apply a different style to added divs• Bonus++: Apply a different style every time!


Recommended