javascript, part 1 · origins-created in 1995 by brendan eich for netscape-named “javascript”...

123
Javascript, part 1 CS147L Lecture 4 Mike Krieger Thursday, October 15, 2009

Upload: others

Post on 16-Jan-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Javascript, part 1

CS147L Lecture 4Mike Krieger

Thursday, October 15, 2009

Page 2: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Intro

Thursday, October 15, 2009

Page 3: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Welcome back!

Thursday, October 15, 2009

Page 4: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

By the end of today...

- Understand Javascript's syntax

- Get to know jQuery

- How to get DOM element using Javascript

- How to create HTML elements and add them to the DOM

- How to attach events to objects

Thursday, October 15, 2009

Page 5: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Our first JS script<html><head>� <script>� � alert("Hello, world.");� </script></head><body></body>

Thursday, October 15, 2009

Page 6: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

A brief history of JS

Thursday, October 15, 2009

Page 7: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Origins

- Created in 1995 by Brendan Eich for Netscape

- Named “JavaScript” to capture Java's momentum at the time

- Microsoft implements JScript soon after

Thursday, October 15, 2009

Page 8: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Since then...

- Incredibly popular

- Has gotten a bit of a bad rap

- Most problems are with browser implementations, rather than language itself

Thursday, October 15, 2009

Page 9: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Javascript in 2009

- Toolkits: jQuery, Dojo, Prototype, Yahoo! User Interface library

- Plugins for these toolkits, like jQuery Touch

Thursday, October 15, 2009

Page 10: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

JS Basics

Thursday, October 15, 2009

Page 11: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Variable assignment//assigning a variablevar a = "Hello";var b = 5;

// comment one line with two slashes/* comment � blocks� with slashes and� stars/*

Thursday, October 15, 2009

Page 12: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

For loops/* for loop */for (var i = 0; i < 10; i++) {� // do something}

/* for each loop, useful for arrays*/for (var i in obj) {� alert(obj[i]);� // i is the name of the property,� // *not* the object represented� // by that property}

Thursday, October 15, 2009

Page 13: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Defining functionsfunction doStuff(argument1, argument2...) {� alert(argument1);}

or in line:function doStuff(argument1) {� var f = function() {� � // function inside a function� }� f(); // calling a function}

Thursday, October 15, 2009

Page 14: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Javascript is Loosely Typed

- Everything is assigned to vars

- Be careful: ("5" + 10) = 510 (the 10 is coerced to a string)

Thursday, October 15, 2009

Page 15: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Coercing typesvar a = 5;var b = "10"; // came from somewhere elsea + b;... 510a + parseInt(b);... 15b = "10.5";parseInt(b) -> 10parseFloat(b) -> 10.5a.toString() -> "5"

Thursday, October 15, 2009

Page 16: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Booleanstrue and false

var a = 5;var b = 5;a == b;>>> true

var a = 1;var b = true;a == b;>>> true

a === b;>>> false

== is a “loose” comparison=== is strict

Thursday, October 15, 2009

Page 17: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Objects

- Objects are the building blocks for everything else in Javascript

- Reference properties inside objects with a period (obj.propertyname) or brackets: obj['propertyname']

Thursday, October 15, 2009

Page 18: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Objectsvar a = {� property1: "value",� property2: "othervalue"}alert(a.property1); -> "value"a.property2 = "what?";alert(a.property2); -> "what?"alert(a['property2']); -> "what?"

Thursday, October 15, 2009

Page 19: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Arrays

- Ordered lists

- Grows dynamically as things are added to it

- Can have any number of different things in it (numbers, strings, objects...)

Thursday, October 15, 2009

Page 20: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Arrays Syntaxvar a = []; //creates an empty Arraya.push("hi");console.log(a); -> ["hi"];var b = a.pop();console.log(b); -> "hi";console.log(a); -> [];a.push("okay");console.log(a[0]); -> "okay"var c = {� propname: "value";}a.push(c);console.log(a); -> ["okay", {propname:"value"}];

Thursday, October 15, 2009

Page 21: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Going through elementsvar arr = [1,2,5,7,10];for(var i = 0; i < arr.length; i++) {� // do something with arr[i]}

// common pattern!

Thursday, October 15, 2009

Page 22: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Variable scope

- In browser, global scope is the window

- functions define new scope

- var declares variable in that scope

- Scope means: what variables can I access at this point in the app?

Thursday, October 15, 2009

Page 23: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

The scope chain// define a new variable a, in the current scope// which, since we're not in a function, is windowvar a = 5;

// get a variable a, in the current scope or a parent //scopeconsole.log(a);>>> 5

console.log(window.a);>>> 5

function newFunction(){� alert(a); // refers to global a� var b = 3; // creates b in newFunctions' scope}console.log(b); // undefined, because b is out of scope

Thursday, October 15, 2009

Page 24: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Scope exercisesvar a = 5;var b = 10;var x = function() {� var a = 10;� b = 5;}x();

what does a equal after x runs?

Thursday, October 15, 2009

Page 25: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Scope exercisesvar a = 5;var b = 10;var x = function() {� var a = 10;� b = 5;}x();

what does a equal after x runs?Answer: 5

Thursday, October 15, 2009

Page 26: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Scope exercisesvar a = 5;var b = 10;var x = function() {� var a = 10;� b = 5;}x();

what does b equal after x runs?

Thursday, October 15, 2009

Page 27: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Scope exercisesvar a = 5;var b = 10;var x = function() {� var a = 10;� b = 5;}x();

what does b equal after x runs?Answer: 5

Thursday, October 15, 2009

Page 28: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

What the browser does

- Checks the currently running function for a declaration of the requested variable

- If not found, go up one in the scope chain, until we hit the window

Thursday, October 15, 2009

Page 29: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Object-oriented?

- Javascript is Object-oriented, but not class-oriented

- Instead, uses prototypical inheritance

Thursday, October 15, 2009

Page 30: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Creating instancesfunction Building(location) {� this.location = location;� this.getLocation = function(){� � return this.location;� }}// calling a function with new treats// the called function as a prototype// and makes a new instancevar Gates = new Building("353 Serra");

Thursday, October 15, 2009

Page 31: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Changing prototype on the fly

var Gates = new Building("353 Serra");Building.prototype.getStreet = function() {� return this.location.split(" ")[1];}

Gates.getStreet();>> "Serra"// prototypes can be changed on the fly,// and anyone based on that prototype will// pick up the changes

Thursday, October 15, 2009

Page 32: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

What is 'this'?

- Defines the context that a function is being executed in

Thursday, October 15, 2009

Page 33: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Examplesthis;>> DOMWindowBuilding.prototype.getThis = function(){� return this;}

Gates.getThis();>> Gates

Thursday, October 15, 2009

Page 34: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Functions are just objects

window.getThis = Gates.getThis;// now there's a "getThis" function defined // on the windowgetThis();

Thursday, October 15, 2009

Page 35: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Functions are just objects

window.getThis = Gates.getThis;// now there's a "getThis" function defined // on the windowgetThis();>> DOMWindow

Thursday, October 15, 2009

Page 36: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

This means...

- Be very aware when using "this" inside your functions

Thursday, October 15, 2009

Page 37: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

More on 'this'

- We'll see more of this later today when we do events

Thursday, October 15, 2009

Page 38: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Timing events// execute one function, delayed:window.setTimeout( function, delayInMilliseconds);

// execute a function at regular intervals:var timer = window.setInterval(function, delayBetweenInMillis);

// stop the timerwindow.clearInterval(timer);

Thursday, October 15, 2009

Page 39: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Examplefunction onLoad() {� window.setTimeout(function(){� � var dv = document.createElement("div");� � dv.innerHTML = "created by setTimeout";� � document.body.appendChild(dv);� }, 5000); //add something after 5 seconds

� window.setInterval(function(){� � var dv = document.createElement("div");� � dv.innerHTML = "created by setInterval";� � document.body.appendChild(dv);� }, 500) // add something every half a second�}

window.onload = onLoad;

Thursday, October 15, 2009

Page 40: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Demotimers.html

Thursday, October 15, 2009

Page 41: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Javascript in the Browser

Thursday, October 15, 2009

Page 42: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

the <script> tag<head>� <script>� // your in-file JS� </script>� <script src="jsfile.js"></script></head>

Thursday, October 15, 2009

Page 43: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

When is JS executed?

- As it occurs in the DOM

- So, in the <head> you don't have access to any of the elements in your body at first

- Solution? hooking up to onload

Thursday, October 15, 2009

Page 44: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Hook up to onload using JS

<head><script>� function onloadActions() {� � // hook up events, etc;� }� window.onload = onloadActions;</script></head><body>...

Thursday, October 15, 2009

Page 45: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

jQuery

Thursday, October 15, 2009

Page 46: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Javascript Frameworks

- Abstract away common functions that are slightly different across browsers

- Simplify common tasks like showing & hiding elements

- Help build features like a tab menu, a “CoverFlow” type menu, drag and drop

Thursday, October 15, 2009

Page 47: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Why jQuery?

- Good fit for our class—syntax is very CSS-selector based

- We'll use jQueryTouch plugin next week

Thursday, October 15, 2009

Page 48: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

If you're interested...

- We can cover Javascript “guts” in the last week of class

Thursday, October 15, 2009

Page 49: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

jQuery crash course

- Global jQuery() function that selects elements to act on

- Shortcut $( ) function that we'll use instead

Thursday, October 15, 2009

Page 50: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Interacting with the DOM

Thursday, October 15, 2009

Page 51: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

CSS Flashback

- #name (selects by id)

- .name (selects by class)

- tagname (selects by tag)

Thursday, October 15, 2009

Page 52: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

CSS Flashback

- #name -> $("#name");

- .name -> $(".name");

- tagname (selects by tag) -> $("tagname");

Thursday, October 15, 2009

Page 53: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Onload function$(document); // selects the whole document$(document).ready( func ); // sets func to be executed onload

Thursday, October 15, 2009

Page 54: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Selecting By Id

<head>� <script src="../jquery.js" type="text/javascript" charset="utf-8"></script>� <script>� function onloadActions(){� � var a = $("#selectme");� � console.log(a);� }� $(document).ready(onloadActions);� </script></head><body>� <div id="selectme"></div></body>

< jQuery object

Thursday, October 15, 2009

Page 55: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

By Class<head>� <script src="../jquery.js" type="text/javascript" charset="utf-8"></script>� <script>� function onloadActions(){� � var a = $(".main");� � console.log(a);� }� $(document).ready(onloadActions);� </script></head><body>� <div class="main" id="selectme"></div>� <div class="main" id="selectmetoo"></div></body>

Thursday, October 15, 2009

Page 56: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

By Tag<head>� <script src="../jquery.js" type="text/javascript" charset="utf-8"></script>� <script>� function onloadActions(){� � var a = $("div");� � console.log(a);� }� $(document).ready(onloadActions)� </script></head><body>� <div id="selectme"></div></body>

Thursday, October 15, 2009

Page 57: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Acting on selector resultsfunction actOnElement(index, element) {� console.log(index, element);}

$(".main").each( actOnElement );

Thursday, October 15, 2009

Page 58: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

One gotcha

- Sometimes jQuery returns a "jQuery wrapped" object that responds to jQuery commands like .each, .click, etc

- Other times it's just the raw DOM element

- Use $( ) to convert back to jQ wrapped

Thursday, October 15, 2009

Page 59: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Examplesvar a = $("#selectme"); // a is jQ object array>>> Object� 0: HTMLDivElement� context: HTMLDocument� length: 1� selector: "#selectme"

a[0];>>> <div class= "main" id= "selectme"> This is the first div. </div>

$(a[0]);>>> Object� 0: HTMLDivElement� context: HTMLDivElement� length: 1

Thursday, October 15, 2009

Page 60: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Specifying context<div id="firstcontainer">� <div class="main" id="selectme">This is the first div.</div>� <div class="main" id="selectmetoo">This is the second div.</div></div><div id="secondcontainer">� <div class="main" id="selectmethree">This is the third div.</div>� <div class="main" id="selectmefour">This is the fourth div.</div></div>

// if we want to select just the .main divs in second container:$(".main", "#secondcontainer");>>> Object� 0: HTMLDivElement� 1: HTMLDivElement� context: HTMLDocument� length: 2� prevObject: Object� selector: "#secondcontainer .main"

Thursday, October 15, 2009

Page 61: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Traversing the DOM

- Use parent(), children(), next(), prevObject

Thursday, October 15, 2009

Page 62: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Traversing the DOM<script>function onloadActions(){� var a = $("#container");� console.log(a.children());� console.log(a.children()[0]);� console.log($(a.children()[0]).parent());}window.onload = onloadActions;</script></head><body>� <div id="container">� � <div id="selectme"></div>� � <div id="selectmetoo"></div>� </div>

Thursday, October 15, 2009

Page 63: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Chaining/* $() usually returns the object acted on, � which lets you do things like:*/$("#mydiv").css("background-color", "red").click(function(){ alert('hi')}).show()

Thursday, October 15, 2009

Page 64: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Creating & Adding Elements

Thursday, October 15, 2009

Page 65: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Task

- Trying to insert objects into the DOM dynamically

- For example, a "Loading..." indicator

Thursday, October 15, 2009

Page 66: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

$("htmlstring")var el = $("<div></div>");

Accepts: a string representing the HTML to create

Returns: the created Element (which hasn't been added to the DOM)

Thursday, October 15, 2009

Page 67: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

$.appendvar a = $("<div>Loading</div>");var container = $("#container");

container.append(a);

append is called on an element, accepts an element, returns the original element

you can also do:a.appendTo("#container"); // or,a.appendTo($("#container"));

appendTo returns the element being appended

Thursday, October 15, 2009

Page 68: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Setting the content/* use .html() */

var el = $("<div></div>");el.html("Loading...");

$(document).append(el);

Thursday, October 15, 2009

Page 69: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Changing styles

Thursday, October 15, 2009

Page 70: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Styling from JS

- All jQuery elements have a .css() function

- Either call it with .css("property", "value"), or pass in an object like so:

.css({

'prop1': 'value',

'prop2': 'value'

})

Thursday, October 15, 2009

Page 71: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

ExamplesBlack background: $("#selectme").css("background-color", "black")

12px font -> $("#selectme").css("font-size", "12px");

5px rounded corners -> $("#selectme").css("-webkit-border-radius", "5px")

//All together:$("#selectme").css({� "background-color": "black",� "font-size": "12px",� "-webkit-border-radius": "5px"});

Thursday, October 15, 2009

Page 72: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Showing / hidingvar el = $("#loading");

el.hide();el.show();

el.hide(true); //with animationel.show(true); //with animation

Thursday, October 15, 2009

Page 73: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Example<script src="../jquery.js" type="text/javascript" charset="utf-8"></script><script>function onloadActions(){� var a = $(".main");� a.each(function(i, el) {� � $(el).css({� � � 'width': '200px',� � � '-webkit-border-radius': '10px',� � � 'border': "1px solid #333"� � })� });� $(".main").click(function(){� � $(this).hide(true);� })}function showAll() {� $(".main").show(true);}$(document).ready(onloadActions);</script><div id="firstcontainer">� <div class="main" id="selectme">This is the first div.</div>� <div class="main" id="selectmetoo">This is the second div.</div></div><input type="button" onclick='showAll()' value="show all"/>

Thursday, October 15, 2009

Page 74: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Demoshowhide.html

Thursday, October 15, 2009

Page 75: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Changing classes$("#id").addClass("classname");$("#id").removeClass("classname");$("#id").toggleClass("classname");

Thursday, October 15, 2009

Page 76: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Example<script src="../jquery.js" type="text/javascript" charset="utf-8"></script><style type="text/css" media="screen">� .highlight { background-color: yellow;}</style><script type="text/javascript" charset="utf-8">� $(document).ready(function(){� � $("#clickme").click(function(){� � � $(this).addClass("highlight");� � })� })</script><script type="text/javascript" charset="utf-8">� <div id="clickme">Click to highlight</div></script>

Thursday, October 15, 2009

Page 77: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Democlassnames.html

Thursday, October 15, 2009

Page 78: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Firebug is your friend

Thursday, October 15, 2009

Page 79: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Interactive console

- Use it whenever you want to test something out

Thursday, October 15, 2009

Page 80: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Thursday, October 15, 2009

Page 81: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Thursday, October 15, 2009

Page 82: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Create element, and appendTo the top bar

Thursday, October 15, 2009

Page 83: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Clicking on DOM element inspects it

Thursday, October 15, 2009

Page 84: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Event-driven architecture

Thursday, October 15, 2009

Page 85: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Event-driven vs polling

- Two different approaches to UI programming: polling & event-driven

Thursday, October 15, 2009

Page 86: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Polling

- Scripts that are interested in changes have to go: "did anything change? did anything change? did anything change?" every n seconds

Thursday, October 15, 2009

Page 87: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Event-driven

- Interested listeners register themselves

- When an event occurs, source notifies its listeners

Thursday, October 15, 2009

Page 88: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

In Javascript

- addEventListener('eventName', function, ...);

- in jQuery, we do .bind('eventname', callbackFn) or the actual event, so .click(callbackFn), .hover, etc

Thursday, October 15, 2009

Page 89: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Example: hooking up to listen to a click

<script src="../jquery.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8">� function doSomething(event) {� � alert("hi!");� }

� function init() {� � var el = $('#clickme');� � el.click(doSomething);� }� $(document).ready(init);</script><body>� <div id="clickme">Click me!</div></body>

Thursday, October 15, 2009

Page 90: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Does...

Thursday, October 15, 2009

Page 91: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Hover

- element.hover(onMouseOverCallback, onMouseOutCallback);

(first function called on entering the element, other called on leaving)

Thursday, October 15, 2009

Page 92: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Hover<script src="../jquery.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8">� function doOnMouseOver(event) {� � $(event.target).css("background-color", "blue");� }� function doOnMouseOut(event) {� � $(event.target).css("background-color", "white")� }

� function init() {� � var el = $('#hoverme');� � console.log(el);� � el.hover(doOnMouseOver, doOnMouseOut);� � el.css("-webkit-transition", "background-color 1s ease");� }� $(document).ready(init);</script><body>

Thursday, October 15, 2009

Page 93: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Demo

hover.html

Thursday, October 15, 2009

Page 94: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Events worth watching forclickhoverloadmousemove (useful for drag & drop)

Thursday, October 15, 2009

Page 95: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Inline Functions

Thursday, October 15, 2009

Page 96: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Overview

- Functions can be defined anonymously in line

- This is most helpful for event handlers

Thursday, October 15, 2009

Page 97: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Examplefunction init() {� $("#clickme").click(function(event){� � // do something on click� })}

// we've defined an anonymous function// that will execute on click

Thursday, October 15, 2009

Page 98: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Closures

- Functions defined anonymously inside other functions will have that their parent function's context

Thursday, October 15, 2009

Page 99: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Examplefunction init() {� var saying = "Hello";� $("#clickme").click(function(){� � alert(saying);� })}

// Even though that function executes way// after init() is done running, it can // access init's variables

Thursday, October 15, 2009

Page 100: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Closures gone wrong

function init() {� for(var i = 0; i < 3; i++){� � $("<div>" + i + "</div>").appendTo("#container");� }}

Thursday, October 15, 2009

Page 101: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Closures gone wrong

for(var i = 0; i < 3; i++){� var newDiv = $("<div>Box #" + i + "</div>");� newDiv.appendTo("#container");� newDiv.click(function(){� � alert(i);� })}

What happens when I click on Box #0?

Thursday, October 15, 2009

Page 102: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Thursday, October 15, 2009

Page 103: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Uh oh...function init() {� for(var i = 0; i < 3; i++){� � var newDiv = $("<div>Box #" + i + "</div>");� � newDiv.appendTo("#container");� � newDiv.click(function(){� � � alert(i);� � })� }}

Our click closure points back to init(), but in init(), the i variable equals 3 because the for loop kept going after the event handler was attached to box #0

Thursday, October 15, 2009

Page 104: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Workarounds

- There are ways to do this, but they're complicated

- We can cover in last week if interested

- For now, don't rely on values you expect to change in original function, use event or this instead (example next)

Thursday, October 15, 2009

Page 105: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Thursday, October 15, 2009

Page 106: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

The code<script src="../jquery.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8">�</script><body>You are Goldilocks. What would you like to do next?<div class="actionlink" id="firstbed">Try the first bed.</div><div class="actionlink" id="secondbed">Try the middle bed.</div><div class="actionlink" id="thirdbed">Try the last bed.</div>

Thursday, October 15, 2009

Page 107: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Attaching listeners$(document).ready(function(){� var message = "this bed is ";� $(".actionlink").click(function(event){� � var whichBed = event.target.id;� � var result;� � if(whichBed == 'firstbed') {� � � result = "too small!";� � } else if (whichBed == 'secondbed') {� � � result = "too big!";� � } else {� � � result = "just right!";� � }� � alert(message + result);� });

})

Thursday, October 15, 2009

Page 108: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Demo

Thursday, October 15, 2009

Page 109: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

What context is that callback being executed in?$(".actionlink").click(function(event){� alert(this);});

Thursday, October 15, 2009

Page 110: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Thursday, October 15, 2009

Page 111: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

What's going on?

- Event function is attached to the div

- When div fires event, function fires with the div as context

- It's a closure, so still has access to scope it was created in (but this has changed)

Thursday, October 15, 2009

Page 112: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

So if we wanted to use 'this'$(".actionlink").click(function(event){� // this callback is attached to each div,� // and 'this' is the clicked div� var whichBed = this.id;� var result;� if(whichBed == 'firstbed') {� � result = "too small!";� } else if (whichBed == 'secondBed') {� � result = "too big!";� } else {� � result = "just right!";� }� alert(result);});

Thursday, October 15, 2009

Page 113: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Thursday, October 15, 2009

Page 114: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Portfolio 4

Thursday, October 15, 2009

Page 115: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Refresher

Thursday, October 15, 2009

Page 116: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Goal

- Hook up the subpages, too

Thursday, October 15, 2009

Page 117: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Strategy

- Minimize page loads on the iPhone

- All links lead to current page but with an anchor in the hash ("page.html#id")

- Use setInterval to watch for changes in the hash and update page

Thursday, October 15, 2009

Page 118: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Step 1: adding content<div id="how-might-we" class='content subpage'>� This is some great work I did for the How Might We? Assignment.</div><div id="inspiration" class='content subpage'>� Wow, that was super inspirational.</div><div id="discovery" class='content subpage'>� Can you discover?</div>

Thursday, October 15, 2009

Page 119: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Step 2: Hooking up links<li><a href="#how-might-we">How Might We?</a></li><li><a href="#inspiration">Inspiration</a></li><li><a href="#discovery">Discovery</a></li>

Thursday, October 15, 2009

Page 120: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Step 3: watching for hash changes

var loop = setInterval(function(){� var curid = currentPage.attr('id');� if (location.hash == '') {� � location.hash = '#' + curid;� } else if (location.hash != '#' + curid) {� � goPage(location.hash)� }}, 100);

// jQTouch will take care of this next week

Thursday, October 15, 2009

Page 121: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Step 4: Changing Pagesfunction goPage () {� var pageToLoad = window.location.hash;� var prevFound = false;� for(var i = 0; i < pageHistory.length; i++) {� � if (pageHistory[i] == pageToLoad) {� � � $(pageToLoad).removeClass("parentpage");� � � $(currentPage).addClass("subpage");� � � prevFound = true;� � � pageHistory.pop();� � }� } � if(!prevFound) {� � $(currentPage).addClass("parentpage");� � $(pageToLoad).removeClass("subpage");� � pageHistory.push("#"+currentPage.attr("id"));� }� currentPage = $(pageToLoad);� return false;}

Thursday, October 15, 2009

Page 122: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Step 5: CSS Classes.subpage {� left: 360px !important;}.parentpage {� left: -360px !important;}

Thursday, October 15, 2009

Page 123: Javascript, part 1 · Origins-Created in 1995 by Brendan Eich for Netscape-Named “JavaScript” to capture Java's momentum at the time-Microsoft implements JScript soon afterThursday,

Demoweek04.html in portfolio folder

bug when on iPhone, will fix and update

Thursday, October 15, 2009