[ Silence ]
>> All right, welcome to Computer Science S76,
Building Mobile Applications.
My name is David Malan.
I'll be your instructor for this summer.
So we have a lot of new toys up here today.
So I'm going to do my best not to embarrass myself by toggling
between multiple machines and hitting these screens.
So, please forgive if I look like a neophyte
when it comes to this stuff.
But we do know a little something, at least, hopefully,
about mobile applications and that's why we're here.
So, this course is primarily focused on the world of iOS.
There are certainly alternatives out there but the summer is only
so long so, we thought we'd pick one platform and focus
on two aspects of it,
namely mobile web application development
and native application development,
and let's start there.
What is meant by these two distinctions?
What are we about to get into this summer?
[ Pause ]
OK, so browser versus standalone.
So mobile web application is one that of course runs
within the confines of the browser
which likely means a mobile web application is written
in what language?
Yeah, so HTML, CSS and then if it's an actual application,
presumably there is some programming language underlying
it so not just a markup language,
so something like JavaScript.
So indeed, that will be the trio of languages that we use
for mobile web applications.
Now, native applications, they don't run inside
of a browser so where do they run?
I'm sorry, so on the OS itself.
So there is this language called Objective-C that Apples used
for some time, most recently in the context of iOS,
their mobile operating system
with which you can write native applications which are ones
that once you've written the source code you can compile
them, so to speak, into object code or machine code.
And that machine code runs natively on the CPU
and on the operating system that's running on an iPod,
on theiPad or on an iPhone these days.
So we're going to focus on both of these over the course
of the next several weeks though mostly on the native side
of things because indeed that's probably
where the greatest returns are in terms of new material
and challenges what we will spend today
and the first project in the course on the mobile web aspect.
So before we get there, let's take a look
at what we actually mean by this.
So let's start with mobile web.
Here is a screen shot of a typical iPhone and you can
of course pull up Safari on the bottom there.
And when you do, you might be inclined
to actually visit a website, like Harvard's here,
that's mobile friendly.
So the irony is if you go to harvard.edu,
you don't actually get the mobile friendly version,
you get the desktop friendly version.
But if you guess and type in manually m.harvard.edu,
M generally designating mobile, you do in fact get this site
which looks much more touch friendly.
So what does it take to actually make a mobile web application
like this that's clearly conducive
to actually interacting it with your fingers?
So things are big enough to touch.
Text is big enough to read.
What's involved in doing this?
Well, you all have probably come into this course
with some background in HTML and CSS,
maybe a little bit of JavaScript.
But to do something like this, all you need is pure HTML,
a little bit of CSS and a little bit of savvy as to what tags
and what properties actually underlie the little
configuration details that make things much more mobile
friendly, much more touchable,
much larger at the end of the day.
So, here's an example of Harvard's site.
It may look like these things are buttons, four buttons here,
three buttons down, but all of these are are pings or gifs
or jpegs in image tags, IMG tags
with which you're probably familiar.
They're laid out in some kind of grid fashion with the table
or with the sequence of divs and so, they've just been optimized
by the designers to be sort of conducive
to being touched buy one's finger
and the graphics have all been similarly designed in Photoshop
but they're like to fit in this interface.
So at the end of the day, if we look underneath the hood
at this website and look at its code, you're just going
to see some fairly familiar HTML, CSS and not all
that much magic but they're probably are a few tags
that underlie that make it a little more mobile friendly just
like that they do sites like these.
You just take it for granted that when you pull up a site
like Gmail or m.harvard.edu or dozens of others out there
that you might use, that they come
up in this web mobile conducive way.
But it does take a little bit of savvy.
So before we dive into anything approaching the native side
of things, let's take a look at HTML 5.
So, if you've been programming HTML in some form for some time,
you've probably started out with earlier iterations,
maybe even XHTML and various tags that have come
and gone over the years.
But HTML 5 is now what's with us
and browser support is increasing
for its several features.
We won't dwell too much on the basics
of HTML 'cause I will assume that you largely know those
but what we will do is try to solve at least one problem.
But first, some canonical HTML, there we go,
my first goof [phonetic].
All right, there's what lies ahead.
So, let's go to, let's say, the slide here.
All right, just as I intended.
So this is a mobile website that we've made for the course,
Computer Science S76 and it's got two links,
lectures and syllabus.
But odds are most of you can barely, if at all,
see lectures or syllabus.
And yet, this is just very simple HTML.
In fact, what tags have I probably used in this website?
I can show off that this thing does actually work on demand.
So we've used the anchor tag
to actually have a link that's clickable and blue there--
what other tags are probably there.
What's that?
So the list tag, so a UL tag for unordered list probably,
an LI tag and then the easy ones, HTML body, head,
title and all of the other boring ones
that probably underlie this page.
But I haven't really told the browser that I should anticipate
that this thing's going to be viewed on a mobile device.
It's barely legible, and why is that?
Well, most browsers assume by default,
even mobile browsers running on our phones these days,
that they're sized really for desktop computers.
And just in case, this is actually a real website
with lots of graphics and text, your phone is going to show it
at the default zoom level which is not going to lend itself
to actually seeing up close what the text is
that you've actually marked up there.
So how can we go about fixing this?
What's the easiest kludge via which we can fix this problem?
>> Enlarge the font size.
>> Enlarge the font size, right, we can deploy some CSS.
We can change the font size, the font family.
Any number of tweaks we can make aesthetically in hopes
that it actually works.
Unfortunately then, if you then view the same side
on a desktop browser, if that's also your goal,
then the thing is going to look
like the opposite problem has happened.
So we need somehow to tell--
we need some way of telling the browser dynamically
to size itself based on what the device actually is and it turns
out there's a way of doing this.
So with one of this meta tags,
which to date you might not ever have used
or if you've used them, you've used them for keywords
or for descriptions underneath the web page.
You can actually use them for other names,
namely one called viewport.
So name equals "viewport" and if we give it a content
or just a value of this, with equals device width,
you can probably infer from this what it's going to do.
It's essentially instructing the browser
that it should size the web page based
on the device width not some assumption of a typical web page
which might be 800 pixels, 1024 pixels
or even bigger these days.
And literally, just by putting that in the head of my web page
as HTML, I end up getting an example like this
with no other changes.
Much more readable, sizes to a reasonable extent
and this is one of the most useful things you can do
certainly for a text-driven website
and just making things work on your mobile browsers.
Now, if you go back here, there's--
it turns out there's a bunch of other things.
And this might now explain why you've gone
to some mobile unfriendly websites
and have been driven nuts by the fact that you can't do what
on some mobile websites on your phone.
So you can't zoom no matter how you try to pinch and zoom,
it just doesn't work frankly 'cause some idiot has disabled
it by way of one of this meta tags by specifying
that the minimum scale or the maximum scale of his
or her website is, for instance, 1.0.
That's the maximum and the minimum via
which you might want to scale.
Now the upside of doing something like this is
that the site is probably going
to look exactly the way the designer intended.
The downside of course is that if your eyes are not consistent
with the designer's vision, you're not going to even going--
you're not even going to be able to override that setting.
So some value but also a frustration,
so do bear in mind too that just because things work well for you
on your own phone, it doesn't necessarily mean your users are
going to be as enamored.
But by far, the most useful at first glance
for us would be something like this and just solving
that particular problem.
All right, so let's take a look then
at a more generalized web page.
Let me see if I can master this yet.
So here, I propose that this is the simplest possible web page
that we can make in HTML 5 that validates
and at least has some bare minimum of content.
So for those unfamiliar with HTML 5,
turns out it's probably simpler than the flavor of HTML
with which you've been familiar.
One, the doctype is no longer the atrocious unmemorable thing
that it was for some time with HTML 4, with X HTML.
It's quite simply open bracket bang doctype HTML.
And then below that,
you actually have the body of your web page.
So this is called the doctype declaration,
the document type declaration.
And all this really is, is a signal, a hint,
to the browser that's reading the contents
of this dot HTML file what version of HTML it is.
Because if you've been designing pages for the web for some time,
you've probably ran into various headaches with Chrome or Firefox
or IE or other browsers because they all behave
slightly differently.
You might have come across something called quirks mode.
And quirks mode essentially dictates how a browser
interprets certain patterns of HTML and long story short.
It's this doctype that hopefully these days will increasingly
kick browsers into a standards compliant mode
so that your pages work more consistently
across multiple browsers.
All right, but this here is a representative web page,
but we can do more than this.
Suppose that we actually want to infuse a bit of stylization,
we can add this line here in yellow.
Functionally, what happens now
when a web browser visits a web page containing these contents
as it parses the file, top to bottom, left to right?
Tell a story if you could, just in your own words,
somehow involving the networks,
somehow involving whatever this yellow tag is that explains
for those less familiar what this line
of yellow text is doing, functionally.
[ Inaudible Remark ]
OK, good. So it loads the file styles.css from the server
which turns out it's just a text file and in that text file is,
as you might have guessed, CSS or cascading style sheet rules.
It does load it synchronously top to bottom.
So there is in fact an order to the tags in HTML so that
if you load a file here and then another one here,
you can in fact assume that B is going to be loaded after A
which certainly has its advantages.
But we'll see some problems that can nonetheless arise
when it comes to this sort of worry about synchronization.
This relation here is just telling the browser
that the relation of this file to the rest of the HTML here is
that it's meant to be a style sheet
so it should somehow be applied.
And so inside of this styles.css file is your typical rules
for fonts and colors and borders and all of that,
and they are then applied to all of the elements,
all of the tags subsequently in this web page.
So that too is probably familiar but we'll use this
to our advantage as time passes, certainly to stylize things
and perhaps solve some additional problems
that might arise.
In fact, let's go ahead and propose this.
This website that we have here is pretty damn uninteresting.
All we have is a super simple text-based website
for the course, not all that compelling even though
if we click through these various links
on the course's website we would actually get to the PDFs
and the content that we want.
But let's see if we can stylize this a bit a more
so that we can make a web application look more
like it's a native application even though I have no idea
yet how to write a single line of Objective-C.
So let's try to make this look more like an actual application.
So to this, let me offer a brief aside on the ways
in which you can approach development
of web-based applications on your own Mac, presumably,
but the same holds true for PCs.
Whenever you start writing in JavaScript code, if unfamiliar,
it often-- you often trip over a security feature
of browsers whereby if you try
to run a JavaScript file locally that's living
on your own hard drive, it's not going to run
because the browser is trying to protect you against something
that could very well be malicious.
So you can work around this by changing Chrome settings
or changing Safari's or your various browser settings
or we can solve this problem
by just introducing an actual web server.
That would be a pain if we all had to go out
and buy a commercial web host and maybe a domain name
and actually put all of our files for the course
and for this first project on some remote server
but we can actually replicate that idea even
without having internet access ultimately
by just running a web server on our own computer.
So what I'm going to propose that you do
for this first project which we'll talk about later
but what I've done here
in advance is I've downloaded some free software called XAMPP,
X-A-M-P-P, and this is free software that actually exist
for Mac, OS, Linux, Windows and probably a couple
of other operating systems that once you figure out how
to navigate its somewhat cryptic pages of links,
you can get down to the download page and download, in this case,
the universal binary for Mac OS and as an aside
for any projects we would point you
in this direction explicitly.
You don't have to memorize all of these little details.
But long story short, once I download this program,
run it on my local computer,
it will install a free software called Apache.
Apache is a very popular web server software that's used all
throughout the world and you can run it on your little old laptop
in addition to PHP and MySQL which also comes with XAMPP.
But what's nice about this is that it gets you up
and running super fast even without having to tinker
with your Mac's own built-in settings.
So I did this in advance and I ran the installer and what
that gives me is a program called the XAMPP control panel.
So I'm going to go ahead and load this file here
and I'm going to get a very simple two screens.
One is just a reminder of how to get started with this thing
and the other is just this little control panel via
which I can start Apache and we're not going
to bother using FTP or MySQL,
all we need is a place to put our files.
I'm being prompted for my password there
and I should now see a green light which indicates
that a web server is running on my computer.
Unfortunately, my computer here is not on the public internet.
I don't even know what its IP address is
and it definitely doesn't have a domain name.
So how do I go about accessing with the browser?
Let's forget about phones for the moment,
the web server that's now running
on my particular laptop here, yeah.
Yeah, so it turns out that all computers
that are running web servers are configured with a default name
and that name is usually local host.
So if I pull up a browser, I happen to be using Chrome,
but I could use Safari or whatever else I have
on my own Mac here and I do http colon slash slash localhost,
one word, and then hit Enter,
what I'll see is this default page.
So this is coming from a web server.
Just so happens that that web server is running where?
OK, on my own laptop.
It has nothing to do with the internet.
I could unplug my cable now, I could turn off the WiFi
and I could still actually interface
with this development environment.
So that's what we're going to use it for.
You don't strictly have to do this for the first project
but this is a nice and quick and dirty way of getting yourself up
and running with the web server.
So now, we can get back to focusing on the web stuff
and the development thereof.
So what I'm actually going to do next is I'm going
to grab the distribution code for tonight's lecture.
So if I go to cs76.net, if you have trouble getting
on WiFi during the break, we can log in as ourselves if need be
or you can use your Harvard University ID and PIN,
but we'll take a break in a little while.
You can field those kinds of questions.
If we go to the Course's website and go to Lectures,
I myself am going to just scroll down to source code.
I'm going to download a zip of that source code.
Once I unzip it, it's going to end up on my desktop
and it's going to be a directory called Source Zero.
And in there is all of tonight's examples in advance
in case we want to pull
up something that's been prewritten.
And what I'm going to do now for those less familiar, let's see.
Actually, I'm going to do this the easy way.
I'm going to open up my finder, I'm going to go ahead
and find my own personal jharvard directory and I'm going
to create in this directory a folder called Sites.
Now, I had no idea that I was supposed
to create a folder called Sites
until I read this little cheat sheet that popped
up automatically when XAMPP was installed.
Now tragically, there is a typo in the little cheat sheet here
and it says Create a Folder Called Sites-Folder,
there should be no dash, there should be no folder,
it's just a folder called Sites.
But now that I've done this, anything I put in there is going
to be accessible on that web server running locally
as though I had put it there via FTP or SFTP.
All I'm going to do is start putting my files in there.
So for simplicity, what I'm going
to do is drag my Source Zero directory
into my Sites directory so that for the rest of tonight,
everything is in that folder and now I argue
that it's accessible via my browser.
So let me prove that.
Let me go back to my browser,
let me go to http colon slash slash localhost.
Unfortunately, I still see this default screen
and XAMPP has taken it upon itself
to redirect me even more deeply into the server but I'm going
to say no, I want to go to tilde jharvard and then hit Enter
and now I see the contents of John Harvard's Sites folder.
And so what's in there now is my Source Zero directory
and now we can resume our look
at this really poorly implemented website
for the course now that we have a web server running locally,
now that I've copied the distribution code for tonight
into that public directory and now that I've pulled
up that appropriate URL in my browser connecting
to that local web server.
All right.
That was perhaps a lot that was new.
Again, the project specification will recap any details you need
to repeat yourself but any questions conceptually
or technologically as to what we just did?
Yeah?
[ Inaudible Remark ]
Sure.
[ Inaudible Remark ]
They do.
[ Inaudible Remark ]
This I believe comes of its own installation of Apache
so the little white lie I'm telling here is
that Mac OS actually comes with its own instance of Apache.
The upside of using XAMPP is that it works the same
across various versions, Lion, Mountain Lion of Mac OS.
So the-- there's much-- many fewer technical difficulties
that we run into than having everyone turn on Apache
which is not turned on by default by Apple.
And this way too, when you upgrade Mac OS,
XAMPP should not break
on you 'cause everything is isolated to one folder.
Yes?
>> So, I don't know why, I think my apache is on.
>> OK.
>> I don't know how I got a Site folder inside the
"My Folder" thing.
>> OK.
>> I can't open another site folder so now it's not working.
What should I do?
>> OK. You have a Sites folder called S-I-T-E-S?
>> Yeah, exactly.
>> And what's inside of that?
>> It's like images and the index.html folder.
[ Multiple Speakers ]
>> Oh, I wonder if that ended up in I have another account
on this laptop and maybe that guy got that.
OK. So I think it's safe for you to delete the images folder,
delete the index.html folder and then you will be in the state
that I'm in by dragging the source directory
into that folder.
>> So, I'll just keep that Sites folder?
>> Keep the Sites folder, empty it though
and just put Source Zero in there.
That just sounds like it's sample code that comes
with XAMPP when you install it
in a default account which I did not do.
[ Inaudible Remark ]
Then you have something else that's doing that.
Let me propose that we will focus
on that one on one at the break.
How about it?
>> All right.
>> All right, excellent, see corner case.
So second white lie I've told tonight is
that this is not simplified things.
All right, other questions?
Other questions?
All right, OK.
So let me do this, in our Source Zero, whether
or not you're using XAMPP or just following along visually
or using whatever other web server you prefer
to run on your own laptop.
I'm going to go into my CS76 directory and I'm going to go
to the HTML directory where here I see,
albeit in a desktop browser,
the exact same portally designed website that we saw a moment ago
in that screen shot of an iPhone.
And indeed, if I right click on here and choose view page source
or control click on your white background,
you'll see that here is the source code for this page
and here, we have some very simple HTML,
as predicted there's an unordered list as you said.
There's a list item, there's an H1, a body, and all of this
and there's also this meta tag.
And that's what makes things look better
within the confines of this browser.
But can we improve the aesthetics still?
Well, let me go back and go into the CSS directory and viola,
what a pretty looking website now
and we've done this entirely by using CSS.
And it does look, up until two weeks ago when Apple decided
that all of iOS was changing aesthetically,
this looks like what?
An iPhone or if we at least size it to the appropriate size.
So let me go ahead here, doesn't that look like your iPhone?
So kind of does with a typical menu at the top in the sort
of a tabular list of menu options.
And indeed, if I go ahead and click this, we see the sub page
which is Lecture 0 or Lecture 1
and if I keep clicking I'll see more.
But what did we not get?
What features did not just happen on the screen?
[ Inaudible Remark ]
There's no animation, right?
If you're a fanboy or girl of iOS and Apple more generally,
you know that it's these little touches like the sliding
from side to side that sort
of makes the experience feel the way it typically does.
But this, let me go back and do it again,
if I hit the Back button and then click Lectures again,
it just flips like a normal web page.
So we're sort of mimicking the aesthetics of iOS,
we haven't really re-created it.
So how could we go about getting some form of animation?
Well, we probably need some more sophisticated CSS
or some JavaScript, some actual logic
to move content from side to side.
But before we do that, let's go to the source of this page just
to get a sense of what was going on here.
So this is the source for this page and if I maximize my window
and zoom in here, there's only one line
of code that's different, what jumps out at you.
[ Inaudible Remark ]
Yes, so it's just the link tag up here,
href equals iOS dot CSS, the relation is style sheet.
So let's see what that is.
Now, as you probably know from web development, I can just go
up here and I can say iOS dot CSS,
Enter and I can see this page.
And we won't dwell too much on the details here,
but here's where I'm sending some font stuff
and some margins.
H1, so that was the title of the web page that said CSCIS76,
we have a background color that I chose
to mimic what Apple itself uses for its default blue shade.
We're using a background image here to actually do a gradient.
What does dash WebKit dash Gradient mean?
Most CSS properties and values don't begin with dashes.
>> Browser prefix.
>> Yes, it's a browser prefix.
What does that mean?
>> So even when your CSS properties are different
by your browsers so I can't remember,
I think WebKit and [inaudible].
>> WebKit is Safari and Chrome.
Yes, exactly and MOZ is Firefox for Mozilla.
So that's exactly right.
There's often unsupported or new up and coming features of CSS
that the various browsers begin to implement on their own.
But if they don't necessarily adhere to a standard
or if it's just a browser-specific feature,
they'll typically prefix that property or that value
with a dash then their unique identifier.
WebKit is the engine that underlies Chrome,
at least right now in Safari,
dash MOZ is the same thing for Mozilla.
So this just means this is not a feature that's going
to work probably on IE or on Firefox.
But that's fine because we're narrowing our focus for now just
on WebKit or Chrome in this case
but it would work on Safari as well.
And then, I'm going to wave my hand at the rest of the details.
But suffice it to say that if we tinkered enough
with the CSS even starting from a clean slate,
we could replicate this iOS looking website
so that it ultimately looks like the familiar UI.
But we don't get any of that scrolling
with which users are familiar.
So let's go back in to one last directory
and let's introduce a framework here that's called
jQuery Mobile.
So you're probably familiar with jQuery
if you know any JavaScript.
If not, we'll dive into a bit of it tonight.
But what you might not be familiar
with are various frameworks for actually helping
with the development of mobile-based websites.
So if we look to pass this example here,
we'll mention three tonight.
So jQuery Mobile as the name suggests is a jQuery library,
very popular library that's specifically geared
around mobile user interface details.
So we'll glance at some of its capabilities now.
PhoneGap is another framework that we won't look at tonight
but PhoneGap is sort of this best
of both worlds whereby it's a framework, so downloadable code
that someone else wrote that you can use
to implement native applications using HTML and JavaScript.
So you don't even have to know Objective-C yourself
and we'll peel back that layer eventually but for now,
know that someone else has taken the trouble to figure out how
to write the bare amount of Objective-C code
that then embeds the equivalent of a web page inside
of a native application so that we can just write web-based code
but still put it in the App Store, give it an icon
on the Home page so that it actually feels more
like a native application even though it's running somewhere
else typically on some web server.
So that's another framework of interest.
And then Sencha Touch which is similar in spirit
to jQuery Mobile, it helps us make aesthetics
that are mobile friendly
but it's definitely a more complex framework
than jQuery Mobile so we'll just focus on the first of these.
So if I go back to my other screen here and I go
into the framework sample code for today, now, we have a UI
that looks almost the same
but there is a little something that's different.
Anyone recall what was absent last time?
Yes, so these little iOS looking arrows and if we go ahead
and click on this row,
notice that it's also highlighting just a little bit
which is nice at least in the desktop environment.
Now, we have a little bit of sliding that goes on so
that too is pretty nice.
But let's dive a bit deeper, we'll come back to this
in a week or two but I haven't advanced
in [inaudible] application called iOS Simulator.
So this is a software that Apple distributes with Xcode
which is their integrated development environment
for writing iPhone applications and Mac software.
And if I pull it up here, it looks like this,
so it looks like the screen shots I've been using earlier.
And if I go up to Safari and click here,
so even though it looks like a phone,
I'm controlling everything with my keyboard and touchpad here.
I'm going to go to http colon slash slash localhost slash
tilde jharvard.
Damn it, what a bad mobile website.
So why is this page so small all of sudden again?
So whereas up until now, all of the examples we've been looking
at were written by me and I included that meta tag.
This particular page was generated automatically by whom?
This is just a directory listing.
Let me zoom in, so if you hold down and we'll get to this
in a couple of weeks, if I hold down option when clicking,
I can pretend to have two fingers on my laptop screen.
And then I just have to kind of scroll to get back
to where I want at the top.
So there's the text we were looking at.
Who generated this directory listing?
Yes?
>> Apache?
>> Yes, it was Apache.
So much like you've seen on the internet, any web server
if you go to a folder that has the appropriate permissions will
just show you all of the files in that particular directory.
Apache's doing that, Apache doesn't know I'm
in a mobile device and whoever wrote the Apache code didn't
know or care about this meta tag for the viewport settings,
so it's just super small.
So at least when navigating these folders
for Apache we're going
to get this annoyingly small screen, but that's OK.
Let me just deal with it for a few moments.
Go into my CS76 directory, zoom in again, move it over here
and then go into framework.
And now, it does look a lot more
like a native iOS application, right?
So we're not just fooling by using Chrome,
this is the actual simulator and it would work the same
on your phone, the only catch is my phone probably can't talk
to my laptop unless I jump through some hoops
to get the WiFi to cooperate to make that work.
But now, let me go ahead and click on lectures just
as I did before, let's click Lecture 0.
Damn it, I've paid a price again.
What's happening?
Yes?
[ Inaudible Remark ]
Yes, so I'm loading a new page
and as you might have just noticed in using an iPhone
or an iPod Touch for sometime, anytime you click a link
on a new web page, the default Safari behavior inside
of an iPhone or an iPod Touch is
to very briefly show you the address bars
because the URL is changing then it will push it away
if you so choose.
The problem is that there goes our mimicry
of an actual native application.
So again, we've paid this price.
But someone argue in favor of nonetheless proceeding
to implement, say, the course's website using HTML, CSS,
maybe some JavaScript without ever touching
or learning Objective-C.
Works on all devices.
It would work on an Android phone, Windows mobile phone.
It wouldn't look like it belongs on either of those devices
but it would certainly still work.
>> Speed of development.
>> Speed of development, sort of 15 minutes later we're done
with the course's websites so we don't even have to look
at a line of Objective-C and it will be more complex.
[ Inaudible Question ]
What's that?
[ Inaudible Question ]
Yes, exactly.
It's a lot easier to update
because even though I'm using this local web server right now,
if you imagine just uploading that to the real internet
and some commercial web post, I can just upload my code
in one central place and no one has
to update their native software.
They don't have to go into the App Store to run an update.
It's just anytime they visit my page it's just going
to be the way I intend it.
So that's a lot of arguments in favor
but we are paying some prices.
There's the aesthetic blips that are happening whether we use CSS
or even a little bit of JavaScript.
There is going to be some latency.
In fact, one of the biggest complaints
against making apps web based is
that they just tend to feel slower.
If you're a Facebook user, up until a year or more ago,
a lot of the Facebook application even though it
looked like a native application was using embedded Safari
windows inside of it and grabbing content
from Facebook's web servers which is nice
because they are already very good at serving up web content
and all they had to do is implement a minimum amount
of code to wrap those web pages but a lot of people,
maybe you're among them,
griped about the speed of the application.
Remember the past year or more it's gotten much faster
because there's a lot more native code.
So just some of the tradeoffs to consider, yes?
[ Inaudible Remark ]
So that's another good one too and we'll come back
to that later in the semester
but there's some really cool hardware underneath the hood
in these iOS devices, right?
You have things like a compass, you have an accelerometer,
a gyroscope and other hardware still and most,
some of that hardware is just not accessible
to JavaScript or to a web browser.
That's slowly beginning to change and you can access more
and more via JavaScript and we'll see a little bit
of that tonight but there are some things
that are beyond your reach.
[ Inaudible Remark ]
And that's a big one too.
The fact the you can put a native app
in the Apps Store whether for free or for some number of cents
or dollars is pretty compelling because it's hard
to convince anyone to buy or pay for access to a website
in the same way that they do something
through the Apps Store, yes?
[ Inaudible Question ]
Good question.
Could you put the mobile website into a frame, an iFrame
or an actual HTML frame so that it's the URL
of the innermost frame that's changing?
Yes, you could, the only thing is the URL
at the top will never change and maybe that's OK
but then you'll lose the ability to deep link to specific pages.
But a good work around.
All right, so let's just take a quick look
at how we implemented this jQuery Mobile version.
We won't spend much time on it.
You'll be welcome to use it for the first project
and its documentation online is ample but let's take a look
at the underlying source code for that third
and final incarnation of the super simple course website.
Notice at the top, we've added another CSS file,
this one happens to belong to jQuery Mobile itself
so I just read that off from the documentation.
We've got our meta tag just like before.
I've got a script tag, this time importing jQuery
and if unfamiliar with jQuery or if unfamiliar
with JavaScript itself, we'll come back
to that shortly tonight and then one other script tag referencing
this jQuery Mobile site and then if we scroll down below,
you'll actually see that I'm making use
of a pretty handy HTML 5 feature.
So what attributes are jumping out at you
at perhaps being completely new?
>> Data dash role.
>> Yes, so data dash role.
That's not an actual valid HTML attribute and what else?
Data dash theme, that's pushing it further.
That too is not a standard attribute in HTML 5
but this is actually a feature of HTML 5.
If you prefix an attribute with data hyphen,
you can create any attributes you want
and they will not be flagged as invalid by a validator.
The browsers won't choke on them so this is a way
of storing metadata often inside of your web page
in a way that's going to be very accessible via something
like JavaScript but without resorting to hacks and coming
up with your own tags and your own attributes
which the world did do for sometime with HTML 4 and XHTML
which often made browsers unhappy.
So this is like a nice way
of including metadata alongside your own data but as
for what jQuery Mobile is doing, well, why did I put data-role?
Why did I put data-theme?
I just read the documentation for jQuery Mobile
and jQuery Mobile essentially told me to make one div for each
of the screens that I want to exist in that foo application,
the first one being the home page,
the next one being the lecture's page,
the third one being the Lecture 0 page
so I just have a div here including some links
and if we keep scrolling down further,
you'll see another bunch of content, another page
so to speak for lectures.
And so in short, the folks at jQuery Mobile decided
to leverage these arbitrary data attributes
to create their own markup language still using valid HTML
5 and what do you think their JavaScript file does upon being
loaded into this page for those familiar already
with some JavaScript?
How does jQuery Mobile turn this HTML
into the user interface we saw as this?
What would you do if you were a library written
in some language called JavaScript that's being loaded
into the web page at the top and you know that lying ahead
of you is markup that looks like this?
What does jQuery Mobile presumably do
to turn this into that?
So if I were jQuery Mobile, I would probably search
through the web page somehow looking for all divs
that have what associated with them?
A data role of page.
I'm not asking you how to do this,
just high level conceptually so if I were jQuery Mobile,
I'd probably do some kind of search
of the whole web page looking for divs that have a data role
of "page" and then I'm going
to do something aesthetically probably involving some CSS
to create that rectangle that looks like a screen
of a native application and I can do that again and again
and again for each of the pages that are defined in here
and meanwhile, anytime I encounter a div
who has a data role of header, for instance, well,
that's one I'm going to deploy some of that nice gradients
with the blue shading and I don't know how I'm going to do
that but at least at a high level,
that's all this library is doing and so what's nice
about jQuery Mobile is that you don't even need
to know JavaScript to use it.
You need to just follow their directions and mark
up your own content using this div approach
with these data attributes.
Sencha Touch, by contrast,
one of the other frameworks I mentioned,
very much the opposite.
You instead write a whole lot of JavaScript code
to create your user interface.
jQuery Mobile is meant to be much more lightweight
and much simpler, yes?
[ Inaudible Question ]
So it's a good question.
Let me summarize as doesn't this get confusing
or doesn't this pinch you into a corner if things changed
over time or you just have to remember all
of the various aspects of some fairly proprietary
if open source design.
Short answer, yes and that's sort of one
of the tradeoffs you make whether
or not you implement something entirely
on your own using pure raw HTML, your own CSS,
your own JavaScript code or you try to save time and stand
on the shoulders of other people
who hopefully have a good community behind them,
who have good documentation behind them
to save yourself the hour, the ten hours, the hundred hours
that it would otherwise take just to kind of come
up with this overarching framework so short answer, yes.
It's definitely a downside
but if it means you can finish the project in 10 percent
of the amount of time, that too could be compelling.
You could implement it 10 times over the next few years
as things change but definitely a challenge overall.
Other questions, yes?
[ Inaudible Question ]
Indeed.
[ Inaudible Question ]
With jQuery Mobile, at least
with this particular user interface that I've chosen, yes.
Every-- all of the HTML and all of the pages are
in one arguably big HTML file and the motivation
for that is largely so that you can do the seamless transitions
with as latency as possible.
If you instead have to fetch more content
with every transition, you might introduce a second,
maybe even two seconds or more of delay,
and that would make it feel even less like a native app.
You can do that and you can tell the browser
to go fetch those pages dynamically
which frankly is necessary if you had more than three pages,
maybe had 3,000, you just wouldn't want
to send a 10 megabyte file down but that too was a tradeoff
and you have to decide where the line is
between convenience and size.
Good question.
All right, so let's talk of a few smaller details,
smaller features of HTML 5 that we can leverage here in order
to make pages all the more mobile-friendly so,
if I switch back to this screen here
and move us ahead to here, there we go.
So here's a new one, another meta tag,
so Apple has made ample use of this meta tag which again today,
some of you have probably never used or you've used it
for some search engine optimizations
so here is one called Apple mobile web app capable.
If its content is "yes", what do you think this means?
[ Inaudible Remark ]
It is indeed mobile web app capable.
What does that actually translate into?
So most iPhone users don't actually do this
but you might know that if you're visiting a webpage
in Safari and you decided, I really like this website,
I want to return to it in the future, you can either one,
bookmark it, just very 1990 style or what else can you do
if you've ever actually done this?
What's that?
>> Add it to the Home screen.
>> So you can actually add it to the Home screen.
So if I go to-- let's go back to my iOS simulator
which again will have you download
in a week or two's time.
And I go back to my directory of code.
Let me go back, and back, and let me go into tonight's--
well, that would spoil the surprise
of what I see here, yes?
[ Laughter ]
I'll fix that that later.
So if I go into my HTML 5 page-- folder and scroll down here.
And I go to, let's say, app.html.
This is a super simple app.
I spent like 5 seconds making it, all it has is an image tag.
But I really like this image and so I want
to not only bookmark it, I actually want to have an icon
on my Home screen that forever shows this icon complete
with glistening Apple sparkles that makes it look
like a very three-dimensional button.
But how do you that?
Well, let me go to the same page in my browser just so I can zoom
in on it over here and you'll see the same boring website
but underneath the hood and the source,
notice that I've included this.
And I've also jumped the gun and also included this
which aptly named makes the Apple mobile web app status bar
style "black".
So instead of getting the default blue
or some other color, I just want the status bar,
the top of my Safari instance to be black in this case.
So if I go to my mobile browser and click on this icon here,
which any iPhone user has.
Notice here in the middle,
I have an icon, add to Home screen.
If I did not have
that mobile-friendly feature enabled, we couldn't do this.
I'm going to go ahead and add this to my Home screen.
It's called Harvard App.
It's pulling that from the title tag of the webpage.
And now it's here on my desktop.
And now, I have an icon on my desktop.
So I can now forever get back to this app by clicking this,
and notice the status bar is black,
and notice you can't quite see my fingers doing this.
But if I click on the screen or touch the screen and try
to drag down, what is absence?
Yes, so the Address bar.
The URL bar that's usually there.
But this is Safari, but it's mimicking the idea
of a native application by not revealing
to me that it's Safari.
But the only reason it did that was because in my HTML,
I proactively, if verbosely, told the browser
that it is mobile web app capable.
So that's all that meta tag does.
And there's a bunch of others that do similar tweaks
to your interface, the status bar style we just saw,
the Apple Touch icon can also be defined here.
So if you define Apple Touch icon to be some ping
and there's actual pixel specifications you can read
up online or just match the one that we included here.
That's how you can specify what icon shows up.
So it's not the default favicon or whatever black
and white icons there by default.
You can do a precomposed one.
So if you really don't like Apple sort
of three-dimensional glistening of your icons which they add
for you, to your icon, you can say, "I have a precomposed ping
which means I'm really good at Photoshop.
I made the three-dimensional button myself.
Don't add additional gloss to it."
So there's that feature as well and then Startup Image.
If you have a really crappy website
that takes a really long time to load, you can show the user
in image as it's loading up.
And that isn't necessarily a bad website.
It might just be one that has to request a whole lot of data.
If Gmail frankly needs to request a lot of data
so that you can begin interacting with your folders
and labels and your inbox, so Gmail, for instance,
might have an icon implemented in this fashion here.
So any questions on those more aesthetic tweaks
that you can apply?
All right, so where that does leave us in order to get
that slightly more dynamic interface even though it was
imperfect with jQuery mobile.
We added this last line of yellow text
in a language called JavaScript.
Some of you, many of you might not even know JavaScript
or at least the aspects of it that we're going to leverage
from mobile but let's pause here,
take a look at the course itself before diving back
into actual development.
So, this is Building Mobile Applications.
What does that actually mean?
The prerequisites for the class, as you might have seen
in the course catalog or simply these,
prior programming experience in any Object-oriented language.
So that could be something like Java, C++,
C# or any number of other languages.
But the goal is to have students
in this course have comfort already on the way
in with the notion of classes and objects,
and instance variables, and class variables even
if you know some of those things by different names.
So if you're on the fence about your preparedness for the course
or not sure if what you learned is consistent
with our expectations, during the break that we'll take
in a bit or at the end of this class tonight.
Do come up to chat with me or others
of the staff we'll introduce in a bit to see if we're
on the same page as you.
So that frankly you don't have a bad experience
over the next several weeks simply
because you don't have the requisite knowledge.
Six, seven weeks is going to really fly by
and if you're trying to learn the prerequisites
for the course while trying to follow the course,
it could certainly be more than an arduous task.
So touch base with us if unsure, comfort with HTML and CSS.
If you didn't really bat an eye
at anything we just did, that's good.
If you're unfamiliar with HTML or CSS, it's probably not going
to be ideal but in fairness, we'll spend just a week or two
on the mobile web aspect of the course.
So if you're really here and fired up about the Objective-C
and the iOS aspect, talk to us too during the break or after
about exactly what you do or don't have as experience.
You don't as you've perhaps inferred need an actual iPhone,
iPad or iPod for the course.
You can do everything in the confines of a simulator.
You do pay a price for that in that you can't have access
to like the accelerometer.
So like even checking your laptop is not going
to do anything to the simulator so you do not have quite
as much functionality but if you do have an iOS device
of some sort, you can use it for the course certainly
to test your mobile apps but also your native apps.
The catch is that Apple doesn't
like to let us install software rewrite
on our own hardware unless we pay Apple for that privilege.
So you actually, typically need to sign
up for what's called an iOS Developer account
which typically is 99 dollars if you plan
on doing iOS development after the course,
so seven week [inaudible].
It's probably a good thing to sign
up for anyway even right now so that you use your Apple ID,
so that you can download betas.
For instance, I'm running iOS 7 on my phone already
because it's accessible to people who are
in the developer program.
But if you think at the end of the semester, you're not going
to try to put something in the App Store
and you therefore don't really need access for a year,
it's an annual fee, we have an academic account
which won't let you submit to the App Store
but will let you install software that you write
on your computer, onto your phone, or your iPad or iPod.
So we'll set you up with that in a couple of weeks' time
and we'll ask you for your Apple IDs and more at that point.
So you don't have to pay for anything.
You don't have to sign up for anything.
But if you're going to be doing this for the next year,
you might as well do it sooner rather than later
so you don't have to transition from our account to yours
in a couple of months' time.
Any questions on prerequisites?
All right, so expectations, pretty straightforward,
to attend all of the lectures and labs, more on those
in just a moment and submit all of the projects,
more on those in a moment.
Lectures. This is lecture.
The focus will be on five-- one week web apps, namely this one
with a project that itself will take two weeks, and then five
of the course's weeks on native applications; Objective-C,
iOS and related features thereof.
This is an incomplete list of the topics and the concepts
that we'll be looking at.
We'll go into more detail over the coming weeks
as to what it means to develop native applications.
We definitely will not cover the entirety of the iOS SDK.
As Apple likes to say, they just released another 1,500 APIs
as of two weeks ago with iOS 7.
There's thousands of method.
APIs for them means method or variable apparently.
But the API itself is very rich.
There's things like the Map SDK with which you can embed maps,
and there's the touch interface, and there's a storage layer,
there's a database layer, and all sorts of ancillary ones.
What we'll do in our time together over the summer is try
to focus on really the most fundamental and the ones
that are most representative of other SDKs so that
when you decide to write your own application,
even if we never, for instance, used the gyroscope,
at least the framework and the mental model will be similar
from aspects of the language that we did do.
Oops, let's just zoom out for a moment
and then zoom back in on labs.
So what are labs?
So per the course catalog, labs are going
to be the hands-on aspect of the course
that will take place same time but on Wednesdays
of each week led by the course's teaching fellows
and this will be opportunities for you
to bring your laptops as well.
We'll meet, not here, but in a more classroom structured
environment across the hall and set up workstations for everyone
and it will be a mixture of hands-on opportunities
to explore recent materials, so things similar in spirit
to what we did tonight.
To explore the week's projects and to get some hints,
some tips, and tricks as to how to dive into those,
and also an opportunity for a one-on-one Q&A
with the course's staff.
Generally, toward the end
of those labs we'll reserve some time
for office hours-like environment so you can work
on your projects alongside classmates
but have the support structure of some of us there
to fill the questions for you.
The website is here as you might have found already, cs76.net.
Discuss is the web-based tool that we'll use over the course
of the summer to interact rather than rely on email which ends
up going only to us and back to you.
We'll generally point you toward Discuss
which is the course's discussion forums.
You can still post questions to the staff privately there.
There's a link on the course's website to Discuss
and what we'll ask that you do
for the first project is say hello to your classmates.
So, if you like to get ahead, there's a general category
in the Discuss boards, and you are welcome to say hello,
a little something about yourself,
and perhaps why you are interested in iOS development.
There's more, OK.
Projects, so the projects are really
where you'll get your hands dirty in the course
and retain the most and I think learn the most.
There'll be three total projects.
Two of them are our choices of specifications.
We will specify exactly what the challenges are.
The third one though will be your choice for you to propose
to the course's staff and then design
and implement your very own project.
The first two that are assigned, one will be themed mobile local,
more on that Wednesday.
But it will involve using browser's geolocation API using
open datasets and mashing things together into an interface
that allows users to explore news and weather all based
on their current location.
Evil Hangman meanwhile will be an implementation in iOS
of Hangman but much more evil than you're used
to whereby rather than just have you guess the letters
that the computer is thinking of,
which is a very boring game once you're a few years older
than when you probably last played it.
The Evil Hangman version of this cheats,
such that any time you guess a letter like E, the computer
or in this case your phone or iPad or iPod is going
to change the word it was thinking of
and re-choose a word that's the same length but that has no Es.
And when you proceed to guess A,
it's going to throw away the word it was thinking about
and make sure it has no Es or As.
And when you choose C,
it's going to make sure the word it's thinking
of is still the same length but has no Es, As,
or Cs until finally, it beats you by coming up with the word
like dog which you should have thought of, but damn it,
the thing was cheating the whole time.
And so, implementing this and calling it not Evil Hangman
but Hangman and having your friends play it is a wonderful
way to make them think that they are awful at Hangman.
All right, so more on that to come.
Grades in the course, it's fairly straightforward.
Performance in the course will be determined by the projects.
No exams, no attendance records,
nothing beyond the course's actual workload and immersion.
We'll evaluate them on four different axes.
Scope, the extent to which you tackle the project itself.
Did you bite off all of the features
or did you only even try half of it.
Correctness, to what extent is it consistent
with our expectations.
Design, how good is it underneath the hood,
how well designed is it so, a more subjective measure.
And style, a more aesthetic measure,
are your variables well named, are things nicely indented,
or is everything pretty printed so to speak.
These are the four axes and they'll be weighted roughly
in order in which you'll spend time on them
with style being weighted the least but still important.
Correctness being worth the most because that's arguably
where you'll spend most of your time getting things
to work just right, and the app party.
So at the very last week of the class, Wednesday,
August 7th at 6:30 p.m., we will meet standing up with laptops
and with some cake and more.
You're welcome to bring family and friends
and this will be an opportunity really just to share and demo
for each other the individualized projects
that you chose to do or even your own implementations
of Mobile Local or Evil Hangman to share
with the class the different design directions that you chose
and see exactly what everyone accomplished.
So it should be a fun way to end the term.
The cameras meanwhile in the class,
technically this class is not on the internet.
It's an on-campus class only.
But what we always do in the summer is try to experiment
with new approaches to videography,
try out new things, new experiments.
This TV is new and this is my first time using it.
So again, forgive any gaps,
we can fix them all in post-production.
But what we will do
on an experimental basis is post the videos
that we're taking tonight and in subsequent classes online
on the course's website.
So if you absolutely can't make it some night
or if I was particularly confusing one night and you want
to re-watch it or fast forward or rewind or slow down,
we'll start posting within a few days the course's videos
so that you have those there as a reference as well.
If you're camera shy and don't want to be on the internet
and on YouTube and the like, we'll always reserve this swathe
of seats so all of you folks will not appear into any
of tonight's footage, even accidentally,
so those first two columns of seats in the middle
if you just never want to be seen whatsoever,
we'll always set aside seats there.
Lastly or second to lastly, let me introduce two
of the fellows sitting over here, RJ [assumed spelling]
and Rob [assumed spelling], who will on board
as the course's teaching fellows working with us in labs
on Wednesdays providing feedback on work,
answering questions with me on Discuss.
Would you each like to come up and say a word?
[ Pause ]
Surprise. You have to talk--
You just have to talk close to my chest.
[ Laughter ]
Because of the microphone.
>> Hi. That's one word.
Rob.
>> I'm Rob.
>> So, all right, I'll redeem this.
So, Rob recently graduated from the college and is going
to be working with us in an academic capacity
over the coming years with courses like this one.
RJ is a rising senior at the college
and is also a teaching fellow for one
of our undergraduate classes as well.
So, that was RJ and Rob.
Lastly, before we take a break, one of the goals
of bringing this TV online tonight was
so that we could have a little of this in motion,
so why don't we-- first, let me change state here.
Pull this up and let's take a five or so minute break.
[Background Music] Whoever would like to come up
and play Fruit Ninja on the TV is welcome to, and RJ, Rob,
and I will field questions off to the side
and about five minutes from now, we'll regroup.
There are bathrooms down at the other end of the hallway.
If you also go to the other end of the hallway and turn left
and go down the smaller hallways,
there's vending machines, candy and soda.
We'll see you in a few.
[ Music ]
Someone better come up quick.
[ Music ]
So we are back and we are about to teach all of JavaScript,
so that we can then dive
into the project this coming Wednesday,
so the assumptions I'd like to make here is one,
that folks are familiar with some Object-oriented language.
JavaScript as we'll see is Object-oriented.
It doesn't have classes per se.
But you'll see a lot of the same ideas
that you've seen in other languages.
We'll focus too on just the very basics of syntax.
You should find that it's incredibly similar
to most any C style language, C, C++, and so forth.
And you will also find that it has most of the constructs,
objects, arrays, that you might expect
in a higher level language like this.
And we'll work our way from the simplest of examples
to things more complex, ultimately ending with things
like Ajax, asynchronous JavaScript and XML
which will underlie the programmatic features
that we need for this coming first project.
So, first is a snippet again of HTML.
So, this is an HTML5 web page,
but we can also call this is a DOM, Document Object Model,
which is just a fancy way for saying tree.
Even though, we draw the HTML like this,
you can actually think of it
like in a family tree whose root node
so to speak is the HTML node.
So, let's throw away the doctype declaration
which actually doesn't really fit
into this mental model for now.
But the root of this page is the HTML tag,
and how many children would you say that this root
of the family tree has?
[ Pause ]
So it has two, one of which is head and?
>> Body
>> And body.
So, there's head and then there's body and in turn,
head and body have some number of children.
So head seems to have how many children?
So, one. As an aside if you really want to be nit picky,
technically head has as many
as three children 'cause there are some white space here
and there, and there's also some white space after the title.
Most browsers throw this away
and you don't have to worry about it.
But as an aside, technically,
you could argue there's three nodes.
All right, but we'll assume that it's just one.
It's a title, how many children does the title element have?
[ Pause ]
So it is one.
So, we won't spend-- dwell on this,
but there are different types of nodes in a DOM, different types
of nodes in this tree.
One of which is an element node and an element is the result
of having a start tag and some stuff and a close tag.
A start tag and an end tag.
An open tag and a close tag.
Those collectively compose what's known as an element.
Meanwhile, this would be known as a text node.
There's also comment nodes
which we don't have the examples off here,
but if you do open bracket bang dash dash,
that begins what would be called a comment node.
But we'll focus just on these two most common ones.
So, meanwhile, the body tag or the body element
to be proper has how many children?
[ Pause ]
Two, each of which in turn seems to have one child.
Now, there is an anomaly here.
There's this href which I didn't bother giving a URL
to 'cause it would-- it's not really necessary for discussion.
But this-- is href a child of the anchor tag?
So, it's not.
It doesn't really fit into the same hierarchical mental model
that we're describing here.
So, we're going to draw it a little differently.
Indeed if I were to draw this picture
as a tree just using rectangles to represent the nodes,
I might draw it as this.
I have one, a document node
and this is the detail I said I was going
to wave my hand at earlier.
It turns out that there is an uber node, the document node
and for those familiar with JavaScript,
you might have seen this before, the document global variable.
We'll come back to that, but here's our root element,
HTML indeed has two children, head and body.
Each of which has a title tag over here and a child of that.
This guy has an anchor tag and an H1 tag.
Each of which has a textual child and then just
because it doesn't belong below the node,
implying that it's child,
arbitrarily draw the attribute laterally off to the side.
So, it's an attribute of the node
but it's not a child per se.
So, who cares about this detail?
Well, if you start thinking about the HTML you see
and the HTML you write as ultimately constituting a tree,
once that HTML is parsed, that is read top to bottom,
left to right by a browser, loaded into memory
as an actual data structure, namely a tree.
This is what it might look like inside of your computer's RAM.
And this is a useful way of thinking about it,
because now that we-- as we begin to dive into JavaScript,
JavaScript is increasingly being used to take a tree like this
and massage into a different tree adding nodes,
subtracting nodes.
Already if you think-- if you're a Facebook user or a Gmail user,
things happen quite dynamically these days.
If you get an email with Gmail,
the whole page does not reload certainly these days instead you
just get a new row in the middle of the web page.
That row is probably a TR or something like that inside
of a table tag maybe or maybe it's a div,
but something like that.
How is Gmail updating the inside of its web page?
It's using JavaScript to insert more rectangles
like these somewhere into the middle of the page.
Facebook, when you get a Facebook chat
or status notification,
or a tweet that pushes everything else down,
what's happening?
This language called JavaScript is inserting a new node
or rectangle into the tree and pushing everything else down
or to the side depending on how the programmer decided to do it.
So that's what's been happening all this time underneath the
hood and we'll see how to do that ourselves momentarily.
So JavaScript, how do you go about writing JavaScript?
Well, historically it runs client side,
inside of a browser.
So if you've got a website written in PHP or Python
or Ruby, you might have JavaScript in that site
but it's not getting executed by your server.
It's being sent to the server via HTTP over the internet
and then the browser is reading that JavaScript code just
like it reads the HTML, top to bottom, left to right,
and executing it in on your own Mac or PC.
So, where do you put the JavaScript?
Well, we've seen already you can have script tags.
We haven't seen them with stuff in between, but the simplest way
to start writing JavaScript as we'll see is to put it inside
of an open script and a closed script tag just like that.
But of course, you're probably more familiar already
with this format.
Just to recap, what does this line of HTML do,
what does it tell a browser to do?
Exactly, loadFile.js and treat it
as a file containing JavaScript code.
So if there's code in it, it should be executed,
top to bottom, left to right.
So we'll see how to actually embed that in a web page.
What about the language itself?
Here, I'm going to take a shortcut and just wave my hand
at all of the syntactic features of JavaScript?
Why? Most of these keywords if not all
of them are probably familiar
to you no matter what language you've actually used before.
A couple might be new, might not have used the
for in construct before, might have not used try-catch
if you're not familiar with exceptions,
might not have seen var before, but it's just what we use
to declare a variable.
But you can probably guess what most of these do.
So, break is usually used inside of a loop
or a switch to break out of it.
And we'll go through this quickly.
These are the details we'll come back to over time as needed,
and any number of online references can reinforce.
Cons specifies that it should be a constant value.
Continue means to do another iteration of a loop
without necessarily proceeding further
down below the line of code.
Do-while means do something again and again
but check the condition at the bottom instead of at the top.
For starts a loop.
For in is useful when you want to iterate over an array.
It's just a shorthand way of typing out a traditional
for loop as we'll eventually see.
Function says here comes a function and you have
to explicitly say here comes a function with that keyword.
If/else, got to be familiar.
Return, got to be familiar.
Switch is just a different way of writing an if/else,
if/else, if/else statement.
Throw relates to exceptions.
You'll see this a little bit in JavaScript
but we won't spend much time on them.
They are also present in iOS but not super commonly used,
at least in the APIs we'll mostly spend our time in,
but it's a way of handling errors.
Instead of returning negative one or returning false, or null,
or some sentinel value like that.
Throw and try and catch are mechanisms in languages
like JavaScript that allow your code to just throw up an error
and typically they'll kill the program unless you have written
code defensively to catch a potential such thrown exception.
And we'll see if these come up today or in the future.
Var lets you declare a variable and while there starts a loop.
And there's a few other things, but the rapidity
with which we just went through that is just
to suggest the JavaScript even if new
to you is probably pretty familiar based
on most any other language you've used.
How do you declare an array?
So in array, what's really nice about JavaScript is
that it makes nice use of syntactic sugar
which means using shorthand notation to do common things,
open square bracket,
closed square bracket gives you an empty array.
You can also write out the word ARRAY,
capital A-R-R-A-Y open paren closed paren calling effectively
a constructor for the array class,
but it's not really called a constructor
and it's not really called the class.
So the more common way of seeing it any way is just
to have open bracket square bracket.
So we'll see that in some examples eventually.
And to get an empty object we use curly braces.
And we're back.
So, let's go about actually implementing some simple
JavaScript examples working our way
up to more compelling examples, particularly ones
that leverage some mobile specific features.
For instance, we'll leverage a feature
of HTML 5 that's particularly useful in a mobile context
if you want to store data persistently even offline
potentially without internet access called local storage.
We'll also take a look at the Geolocation API which allows you
in JavaScript code to ask the browser
and in turn the iOS phone or iPad or iPod where am I
in the world, and actually get back some GPS coordinates
and also a measurement of just how accurate that estimation is.
So let me go back to the sample code for tonight.
I'm inside of the JS directory and let me go
into the dom0.html file.
So again, if you go to cs76.net, if you haven't already,
you can download all of this code to play along at home.
And if you pull up this page, you get a super simple example.
It apparently is a form with a text field
and with a form field.
And let me go ahead and view the pages source
so we can see what's going on underneath the hood here
and let's first focus on what's familiar.
Let me scroll to the bottom and we see a body tag.
We see inside of that body a form tag and ID.
What's an ID attribute used for if you've not used it before,
or if you have used it before?
[ Inaudible Remark ]
Exactly, so if you've not used it before, the ID attribute
which can be applied to most any HTML tag allows you
to uniquely identify it in the dom.
It's totally the honor system.
It's up to you, the developer, to make sure
that you don't give any other element the same ID,
but it allows you to have quick access
to a particular element not only in CSS and in your style sheets
but also as we'll see in JavaScript code.
So you don't have to go searching
through the whole tree trying to find a node of interest.
So that will come back to onsubmit, let's dive into input.
So I have apparently given an ID of name to an input tag
that has a placeholder.
So this is interesting.
It turns out that in HTML 5 there's actually a few useful
attributes that you might not have seen before.
So let's actually suspend this thread for just a moment.
Let me go back into our earlier directory just
to make sure folks have seen this.
And if I go into inputs.html, notice this too,
is a form without even a submit button 'cause my goal isn't
to submit this form but just
to demonstrate different types of form fields.
Now they're going to wrap a little bit 'cause the lines are
long, but notice in this form I have three input tags
and I've got an auto capitalize equals "off" attribute.
You probably guess what that does.
It tells the phone, in most cases,
don't try auto capitalizing this, which an be annoying,
auto complete equals "off",
that just disables the little dropdown that will often appear
if you previously typed something into the field.
It's pretty common on desktop browsers.
Autocorrect equals off, increasingly helpful
on mobile devices and also supported on more
and more desktop browsers just means don't correct my spelling.
Placeholder equals quote and quote,
that puts what in the textbox?
>> A placeholder text.
>> A placeholder text, a grayed out text that's there
until you click on it or start typing,
so it's just useful for instructions.
And then finally type, this is interesting too.
This first one has type equals text which is old school,
but notice in HTML 5 you can have type equals email
and type equals URL.
Now, that does not mean that the browser is going
to validate the field for you.
You can type in any word you want into an email field
and you won't get yelled at just because it doesn't look
like an email address.
Similar for the URL, you can type in any word you want,
even if it's not a URL,
the browser is not going to yell at you.
So why in the world would the browser care what type
of field this should be?
[ Inaudible Remark ]
What do you mean add the at symbol?
[ Inaudible Remark ]
So the keyboard, but not my physical keyboard.
[ Inaudible Remark ]
Yeah, so indeed if I-- let's go back to Safari
in the simulator here.
Let's go back to the directory listing and go to inputs.
And now notice what happens.
If I click on the first of these inputs, the very top one
which is type equals text, notice that I get this keyboard.
OK, pretty uninteresting, done.
Now if I click on the email field,
see how good your recall is, what changed?
So you get a smaller spacebar and the at sign there.
So it's just for the user's convenience.
And what are we probably going to see
if we instead dismiss this and click the URL field?
[ Inaudible Remark ]
Exactly, it changes ever so slightly
and also we get the slash for easy access.
So, it's just a little bit of icing on the cake for the user
to make it easier to interact with your site.
All right.
So now, let's go back to the example we were at before
which was not this one here, but with just the dom0 file
and the JS directory that look like this.
So notice at the bottom I've added a couple of other things
to the input tag, placeholder equals "name" just
to be explanatory, type equals text, so no special keyboards.
Finally, an input of type equal submit.
But there's something else here
that you might not have used before,
but you can probably guess what it does,
this attribute called onsubmit presumably tells the browser
to-- yeah, call a function, call the greet
when the form is submitted.
How do you submit a form?
Well, you either click the physical submit button.
Or if you're on a desktop computer, you hit the enter key.
That will often do it as well.
So in either case, the act of submitting a form happens.
But with this onsubmit attribute,
you're telling the browser,
listen for that event, so to speak.
And JavaScript and web programming more generally is
very much event driven.
When that form is submitted an event happens
and onsubmit is an event handler,
a listener that's waiting to hear that event of submission.
And what should it do?
Well, we don't know much JavaScript yet most likely
but it looks like code
and indeed I should call a greet function with no arguments
and then I should return false.
And we'll come to the-- back to greet in a second, return false.
What would that possibly mean, to return false inside
of an attribute, inside of a form tag?
Exactly. So what might you want to stop
when a form is submitted?
Well, the form being submitted itself to the server.
If the whole point right now is to start writing code that runs
on the client side inside of the browser,
we don't even need a server once we've downloaded the HTML,
and the CSS, and the JavaScript, right?
We can lose internet connectivity altogether
potentially if all of the code is running locally on my phone
or iPad or iPod right now.
So onsubmit just says call a greet function
but no matter what happens do not actually submit this form.
So it's your chance to intervene.
So now let's scroll up to the top of the file.
Most of it is pretty boring HTML, title tag,
head tag and all of that.
But notice toward the top of the file I've introduced
that script tag, and then I've put right there
in the script tag function greet.
So we promise that the function keyword means here comes
a function.
Then open paren closed paren means it takes no arguments.
Open curly brace, closed curly brace defines the scope
of a function and it's a one line function.
It turns out in JavaScript there is a function that's super
useful but not to be used in production code
that just opens a pop-up.
If you remember 8-- 10 years ago when pop-ups were very much
in vogue and alerts were very much in vogue,
that's how you invoke them.
That's one way of opening prompts on the user screen.
So what is this going to do?
Well, let's take a quick glance at some syntax,
but you can probably guess what this is doing based
on other languages.
It's wrapping a bit 'cause the line is long.
But this is calling alert passing
in a single argument of type string.
So JavaScript does have the notion
of data types as we'll see.
Quote unquote with the comma hello.
What do you think the plus is doing?
Concatenation.
So you've seen this in Java.
If you're a PHP programmer, you've seen dot.
Other languages use different symbols.
Now document.getElementById of name.
I had no idea until a second ago that function existed
but it seems that a function called getElementById exists.
It's associated with some kind
of global variable called documents.
So more properly it's a method inside
of an object called document.
What is that object called document?
Well, if we go back to the screen from earlier,
recall that, the document node.
If you've programmed JavaScript already
and you every used document dot something,
you've essentially been talking to that guy
who has some special functionality built in
and clearly he's important 'cause he can see the entirety
of the tree from his vantage point.
So if we now go back to my own code,
document.getElementById does exactly what you think it does.
Give me the element from the tree.
Give me the rectangle whose ID is quote unquote name
which is what type of element, just to be clear?
Not a string per se.
What type of HTML element was it?
An input. So give me the rectangle
that represents the input whose ID is name
in that tree structure.
Why? Because I then want to dive in deeper and get its value.
So here is the object oriented nature of JavaScript.
The dot means go inside of this object, go inside of this object
and get some member function or member variable data field.
So documents and object, it has a method called getElementById.
That method returns apparently an object or rectangle
that represents that node from the tree and one
of its property, something inside
of that rectangle is apparently a property, a data field,
data value, whatever you want to call it,
an instance variable called value.
That gives you the value that the user typed into that field.
So what is the net effect in layman's terms of this line
of code, to trigger an alert with what text?
[ Pause ]
[ Inaudible Remark ]
Hello, so and so, whatever your name actually is.
So let's give this a try.
Let's go back to the web page itself.
Let me go ahead and type in Rob and click submit,
and there it is, "Hello Rob."
It's definitely a poor man's user interface
and that we're just triggering this browser dependent screen.
Chrome even gives its own logo here.
So there's other ways of doing this
but clearly we have dynamically gotten some data
from that DOM element.
But hopefully we can do a bit better.
So let me actually roll back not to zero but to dom1.html.
The form is going to be the same,
but let's instead introduce a slightly different
approach here.
So, in this version what appears to be different at first glance,
even if you can't read all of the lines in question?
I moved the script, I moved the script down below.
All right, why did I do that?
Or what's the effect of this?
There's a few things different here.
Well let's take a look.
So one, it's an important detail
that the form is now coming before the script because one
of the conclusions we reached earlier is
that JavaScripts reading of a--
or browsers parsing the page is synchronous,
it do these things one at a time, at a time, at a time.
So, in fact as a tangent,
if you've ever used Google Analytics or you used
like the Facebook like button,
actually Google Analytics specifically tells you
to put their code where?
Sorry? At the end, right above the closed body tag.
Why? Well, just in case Google servers are slow
or the user has a slow connection to Google but not
to you, Google doesn't want to be responsible for slowing
down the loading of your web page lest the user see nothing,
and so Google also loads its JavaScript cookie tracking code
at the bottom.
Now, the last time I looked, Facebook tells you
to put their code where?
[ Inaudible Remark ]
OK, right after the open body tag thereby giving it
more priority.
But in their defense, the way Google loads code
into your page is they actually retroactively go back
and inject it into the top of the page,
so it's not actually a blocking call.
So, different subtleties that we'll not spend time on here,
but that's the motivation
for those different design decisions is how will the pages'
loading be affected.
So, let's see what the relevance here is.
Here is my form.
I've this time given it an ID of demo
so that I can uniquely identify the form element itself.
I have the same input and submit button as before,
and then down here I have a script.
But notice my code has changed a little bit.
What's the first syntactic difference
that you see this time that wasn't here before?
Yeah?
[ Inaudible Remark ]
OK, good. So, notice that return false is below the HTML itself,
it's not inside of the HTML.
In fact there is no onsubmit attribute anymore.
Instead, we seem
to be manipulating a property called onsubmit.
So again to the object oriented nature of JavaScript,
it turns out that just
as there's this global document object,
inside of which is a method called getElementById,
that in turn is going to return the element whose ID is demo.
And which element is that?
What type of element?
It's a form.
It turns out that form elements have a property called onsubmit.
And this is not a property whose value is supposed
to be a number or a string.
It's supposed to be a function pointer so to speak,
a reference to a function, the address of a function.
Think of it however you'd like based
on what language you have as a background.
So, onsubmit equals, what does this mean?
Notice that on the right hand side here there's the keyword
function again, open paren, closed paren,
but what is absent this time from the function declaration?
There's no name of this function,
but it doesn't matter, right?
Because what I'm actually doing here is clearly creating what
seems to be an anonymous function.
It's a function with no name otherwise known
as a lambda function.
And when you call the function keyword in this way,
notice I have the open curly brace, then some stuff,
then closed curly brace semicolon.
So, I've declared in these few lines of code
in anonymous function,
but because I have an equal sign right before it,
I'm essentially storing the address of that function,
a pointer there too, were our reference to that function
where as the value of this onsubmit property.
The browser has been defined meanwhile to know
if this onsubmit property, previously null,
is set to a valid reference of a function.
When the form is actually submitted by the user
by clicking submit or hitting enter on a physical keyboard,
find this value, call that function and return true
or false based on what it tells you to do.
So, clearly it's returning false, what else is it doing?
It's also doing the alert
but the alert thing is the same as before.
So, what have we done?
We've removed the onsubmit attribute from the HTML,
replaced it instead with pure JavaScript code.
Why? What's an argument in favor of this approach?
Yeah?
>> For some reason if the browser doesn't like JavaScript
or if the JavaScript [inaudible] to form itself is not going
to crash your browser.
>> OK, good.
So, just in case we're using a browser
that has some incompatibilities, by moving the code outside
of the context of the form, the script is less--
is more likely to be ignored and indeed that should be the case.
Even browsers that have JavaScript off should just
ignore the contents of this tag.
So, it's not a bad thought.
In reality I don't think it would end up being a problem
because if the browser just doesn't support JavaScript,
the fact that we had onsubmit equals quote unquote something
should also be ignored in the same way,
but not a bad approach.
Yeah?
[ Inaudible Remark ]
Good. So, we'll come to the jargon of MDC probably in a week
or two, but for now let's summarize it as--
my code was getting a little sloppy.
Not only did I have HTML and then also some CSS in that file
up above in previous examples, now I'm putting actual logic,
programming code inside
of my markup language whose name suggest it should be for markup,
making things bold, making things centered.
Structuring a page should have nothing
to do fundamentally with codes.
So, in the interest of keeping my coding life separate
from my markup life, this is generally a better approach.
It's not perfect 'cause frankly it's like half a foot away
from where it was before.
So, we haven't really solved this problem,
but keeping code separate from logic
and presentation is a key theme that we'll come back
to because it permeates the iOS SDK and the environment
for running iPhone apps,
but this is at least a step toward that.
And also, if we're only calling this function onsubmit,
we definitely don't need to give it a name.
If I'm the only person ever calling this code,
I called it greet before, but I didn't even really need
that name 'cause clearly I can do without it entirely.
[ Inaudible Remark ]
Good question.
In JavaScript, none.
I'm in the habit lately of using all single quotes for JavaScript
and all double quotes for HTML,
but there's functionally no difference in JavaScript.
He is referring to the single quotes I had
around demo for instance.
This would be a matter of style too.
For the projects if you have religion about single
and double quoting, that's fine, just be self-consistent
with respect to your own code.
All right, so now let me go into this file and let's see,
I'll use the simplest of programs on Mac OS TextEdit,
and I'm going to go into--
remember John Harvard's sites folder which is
where we put this code.
I'm going to go into source zero, go into JavaScript,
and go into dom1.hmtl.
So, here is that web page, but now it's an uneditable program.
I'm going to scroll down and I'm going to do things the opposite,
I'm going to delete the script tag, and I'm going to put it
above the form, and then I'm going to save the file.
I'm going to go back to my browser.
I'm going to reload the page.
So, indeed the browser now sees the change I made in TextEdit.
I'm going to go back to the page itself and reload this.
So, the form has been reloaded on the page, and now I'm going
to go ahead and type in Rob again and submit,
and it seems to have broken.
In fact I see a question mark in the URL
which usually means a form has physically been submitted
to a server which I did not intend.
There were supposed to be a return false.
So, let me start diagnosing things.
So, when doing the first projects in the course,
much as Apple like Safari,
using Chrome is probably the better browser to use
from a development perspective 'cause it has additional
features, one of which is this inspector element at the bottom
which Safari has its own variant of, but I think you'll find
that Chrome is useful both for mobile and desktop developments.
And I'm going to go into the console window here
for a moment, and that's interesting.
The red text which if I zoom in says,
on type error cannot set property onsubmit of null.
So, that's kind of a mouthful.
I didn't really understand the first half,
but onsubmit looks familiar and null sounds worrisome.
So, let's see where in my code I used the keyword onsubmit.
So here is my code.
Onsubmit can't call this with respect to null.
So, again the error was, cannot set property onsubmit of null.
So, what does this suggest is null?
[ Inaudible Remark ]
But no demo.
Specifically the return value of the method getElementById
when passed an argument
of "demo" is apparently now returning not a rectangle,
but null, and null is the null object that has no property,
certainly not one called onsubmit
which is why Chrome is freaking out and not doing anything.
And in fact, Chrome and most browsers approach
when there's a JavaScript error is just to forge ahead blindly.
In this case, it submitted the form irrespective
of my return false.
Why is all of a sudden the demo element null?
Yeah?
[ Inaudible Remark ]
Exactly. It's because the browser is parsing this code top
to bottom, left to right, and at this point in the story
when I'm reading the script tag in its new location,
I can call getElementById of "demo" all I want.
It won't exist until we get down there, but I'm calling this line
of code here which is why sort
of coincidentally my code worked fine before even though I put my
script tag still in the file but below.
But these two, in the spirit of keeping my code separate
from my HTML feels a little hackish to just solve all
of my JavaScript problems by putting my code
at the very bottom of my file.
So, hopefully there's a better way than that.
And there is.
If we scroll back to our demos here, and let me go
into the last version of DOM, DOM2, which hopefully works.
Hello Rob in fact works.
Let's take a look at this code here
and see what's different, all right?
My HTML seems to have been vastly simplified
and I'm now practicing what I've been preaching
about not commingling code with my raw markup.
In fairness, I've just moved it up to the top,
but at least now what's inside of the head element
which at least is sort of conceptually distinct
from the body which is where the actual aesthetics
of my page should be.
And frankly, at this point, we could rip
out this code and put it where?
In a separate file called like file.js
like I suggested earlier.
So, we're almost there but we'll just leave it with this example.
But now, I see some scary looking syntax
and also one new script tag.
What are we apparently loading into memory here?
Yeah, jQuery.
So, jQuery is a super, super popular library for JavaScript,
so popular that many people confuse JavaScript
with jQuery itself and they say, "I know jQuery,"
when really they know JavaScript and they also know jQuery,
but they're not alternatives to one another.
What jQuery does is it allows you
to dramatically simplify the amount and the complexity
of code that you need to write because some very smart people,
one in particular, has spent a number of years now building
up a corpus of code that just makes everyone's life easier.
And it's all open source.
You can read through it.
It's thousands of lines long,
but for our purposes let's just focus on some of the highlights
and some of the features
that we'll see commonly throughout any library you might
use for this first project
or really desktop development in general.
So, there turns out there's a dollar sign
which is a popular aspect of jQuery.
What does the dollar sign represent in jQuery?
[ Pause ]
What special significance does the dollar sign have
in JavaScript?
>> It's a selector.
So, it is but let's focus not so much on its functionality
but just syntactically.
What--
>> Syntactic sure.
>> Is it syntactic sure?
Oh, it kind of is but it's not even--
I'm not even sure I'd call it that.
It is just a valid symbol for a variable.
So, whereas in some languages dollar sign has special meaning,
like in PHP it demarks an actual variable's beginning
or in some languages you just can't use it,
you can't have a dollar sign in a variable's name.
JavaScript doesn't care.
You can absolutely have a dollar sign
as the name of your variable.
Now, jQuery, the folks who wrote it just realized, "Oh,
this would be kind of sexy if we just started using dollar sign
to represent our class called jQuery."
But what this really is, is if I go into my code,
and this is again dom2.html, for those who've been using jQuery
for some time and just taking it for granted,
this is equivalent to that.
There is a-- we'll call it a class,
even though it's not quite a class, called jQuery
and it takes an argument
and that argument can be a CSS selector.
In this case, it's the actual name
of a global variable document, but that's all it is.
So, it's not quite syntactic sugar
and that it has no fundamental special significance.
We humans just view it as something special.
All right, so more properly jQuery is a function
and there's a hell of a lot of functionality built
into that one particular function
and among the things it does, and let's go back
to the common case of having dollar signs,
is it wraps traditional DOM nodes.
So, all of those rectangles we've been talking about,
jQuery, wraps them in the sense of making them a little wider
and a little taller and adding more properties
and more methods to them.
On the end of the day, inside
of it is still the original rectangle,
but they've simplified the means by which you can talk
to that rectangle from the tree.
So, dollar sign, open paren, closed paren document takes
that document node from the top of the tree
and just gives it more functionality,
more power, if you will.
Dot ready is a shorthand way of saying,
no matter how big this web page is, no matter how many lines
of HTML there are, only call the following function
when the entire page has been loaded top
to bottom, left to right.
So, what this means is that this line of code can now be anywhere
in our page, in the head, in the body, in another file,
it doesn't matter whatsoever.
That means wait until the entirety
of the page is literally ready.
So, what am I passing to the ready method?
So, the ready method expects an argument whose data type is
apparently a function pointer, so to speak.
It expects a function as its argument.
And now what am I doing?
It's an anonymous function 'cause I don't care what the
thing is called, it just needs to exist and be callable.
Open curly brace, and it's a little messy
but here is the other curly brace closed parenthesis.
So, it's starting to get a little hard to read,
but notice open paren and closed paren, so those are balanced.
Open paren, open curly, closed curly, closed paren.
So everything else is inside of this anonymous function.
What is inside of this anonymous function?
It turns out I'm doing the same kind of trick in the next line.
Dollar sign "sharp demo".
So those of you familiar very well
with CSS, this represents what?
The CSS selector for the odd node whose ID is demo.
So the hash sign means give me the node whose ID is demo.
If you instead had dot demo, that means give me the node
that has a class of demo,
and there's some other selectors as well.
But this one means give me the one node call whose ID is demo.
Dot submit, they've simplified the wording,
and jQuery does more than this.
But rather than call it onsubmit,
it's just called submit.
And what does the submit function expect as its argument?
It expects its own function, an anonymous function,
but it's kind of tuck away and call only when what happens?
That element's submit handler is needed.
So, this is just a third and final way
of associating an action, an event handler,
a function with an event, like form submission.
So what happens next?
Finally, it's boring again, alert, hello, so and so.
And in fact, I'm cheating here or I'm mixing my syntax.
What should this line 11 really be by going to that code?
Let me open up notepad again, open up DOM2.
And based on that lesson learned,
what can I actually change this to?
Dollar sign and hash name.
So that's what I mean in part
by jQuery simplifying otherwise fairly verbose code.
Document.getElementById can literally be summarized
as dollar sign.
Because the jQuery function dollar sign knows
that when it's passed an argument,
that's not a global variable like document
which just gets immediately wrapped with a bigger rectangle
when it realizes, "Oh, this is a string."
But the string starts with a hash sign,
it knows that that means the rest
of the word is the ID for a node in my DOM.
So, here again, it's just how jQuery simplifies
or like even though at first glance it absolutely looks more
cryptic, but really, it's ultimately saving us time.
And again, we could factor out that code further into a JS file
so that it doesn't even appear anywhere in our raw HTML.
[ Inaudible Remark ]
Good question.
Is it required to have a unique ID?
It is an error of syntax to you--
for you to give two elements in a web page the same ID.
[ Inaudible Remark ]
You might get back-- I don't know offhand.
You might get back an array of two or more nodes
but I think it's fair to say,
and I think the spec probably says the behavior is undefined,
certainly for a JavaScript library.
But I don't know offhand.
Other questions?
OK.
[ Inaudible Remark ]
No longer--
[ Inaudible Remark ]
It's not quite that.
It's just-- this is literally the honor system.
Like, for the web to work, all of us have to agree
on some rules, and one of those rules is do not screw up
and give two elements in a web page the same ID.
And if you do, we're not sure what's going to happen.
At least, I'm not sure.
There might be some formal definition.
I'll look it up later, tonight.
[ Inaudible Remark ]
That's fine.
If you have two elements with the same class,
you'll get back an array and the following function will be
applied to that array effectively.
Even though it's not quite an array,
it's in a wrapper that jQuery returns.
OK. All right, so, not bad.
But thus far, all we're doing is manipulating DOM elements.
It would be nice to start introducing some functionality.
So why don't we go ahead and introduce a bit
of storage capability.
So, where we left off, we had this thing here.
And let's jump ahead to--
I'm getting much better with this-- local storage.
So, where can you store information in a browser
when programming in JavaScript?
Some of you might know from past experience,
or now that you know JavaScript runs client side,
you have very few options to begin with.
In window.
So there's this global object called window
that in theory you can store data in.
But if that window closes, for instance, the browser quits,
what happens to any variables you've tucked away there?
They disappear.
And this is what a lot of popular libraries do.
They'll tuck important stuff in the window object.
It's effectively putting--
making something a global variable,
but it's not persistent.
So where else can you put it?
The-- obviously, the answer is going to be local storage.
But leading up to local storage, where else can you put it?
Cookies. So, you can actually write JavaScript code
to plant cookies on the user's computer that didn't come
from the server, they came from your local JavaScript code.
But what's the downside of using cookies?
[ Inaudible Remark ]
Correct. There's a size limit, which is generally pretty small
and they also can sometimes be disabled by users.
They might not persist as long as intended if you're
in an incognito mode and the like.
So there're a number of reasons where cookies get tripped off.
And we're not going to solve all of those problems
but those are a couple of barriers.
What else?
If you have a server, you could just put it
in a database certainly.
But maybe that's not ideal, especially if you're trying
to make a mobile app that is fast
by using local data as much as possible.
So it turns out that local storage is a relatively new
feature, popular in HTML 5, that gives you access
to another global variable, really inside the window,
that is called localStorage, capital S.
And it has a few methods associated with it,
among which are clear, which means just clear
out anything I've put there already, getItem,
which means give me the value of an item with a certain key.
So getItem takes one argument, a string, which is the identifier
of whatever you put there.
So, for those familiar, localStorage is a hash table
or it's a dictionary or it's any number--
an associative array can be though
of as any number of these things.
RemoveItem does the opposite of setItem
because setItem takes two arguments, a key and a value,
and it stores it locally in the browser.
The upside of which is if you close the window,
quit the browser, and don't clear the history
in the computer-- in the browser entirely,
it's still going to be there later.
So why might this be useful?
Storing things like your address book for auto completion,
storing things like your inbox potentially,
if it's a mail application, storing a nontrivial amount
of data for easy ready access.
So let's take a quick look at an example involving storage.
So if we go back to today's sample code in storage.html,
I have apparently visited this page zero times.
All right, if I dismiss this alert, reload this page,
I have now visited this page one time before.
All right, can you guess where this is going?
Reload the page.
Two times before.
But we just cited any number of ways
where we could be storing the number two
and then the number three and number four.
It could be in a var, a variable in the web page itself.
So this isn't all that interesting.
But let me go ahead and copy the URL so I don't have
to remember what it was,
open a new browser window, save, ooh, three.
It actually remembered this time.
Let's play with fire.
Quit the browser, reload it, visit it again.
Four times.
So something is persisting.
And it turns out it's relatively easy to actually implement this.
If we look at the source of this page, I really kind
of cut some corners on the aesthetics of the page.
There's nothing actually there other than code.
If we go in here and scroll down to the bottom of the page,
notice that the HTML is super simple.
We've got a title, a head and a body,
and then another HTML attribute, not the only way to do this.
And again, this is kind of a regression to the messier way
but it keeps the code super simple and the focus
on the new stuff for now.
What happens when the body is loaded apparently?
Call the greet function.
So onload is like onsubmit but it's when the body
of the page is loaded.
So now, if we look up here, we have a bunch
of lines of JavaScript codes.
It's a little more complex but notice, there's not much more
in the head, just that familiar meta tag.
And now, the function called greet, what does it do?
So, a little new syntax here.
So there's a few ways to do this, but a really rigorous way
to check whether or not a variable exists in JavaScript is
to take the symbol's name, in this case, localStorage,
capital S, pass it through the typeof operator
and typeof is literally going
to return a string whose value is a number or string or bool
or undefined if that variable has not yet been defined or set.
So I'm literally checking for that.
If the type of local storage is "undefined",
then what is the implication?
Or rather, is not undefined.
Not undefined.
But it looks like I made a typo here.
Not equals equals.
It feels like there's one too many equals for most languages.
But it turns out that JavaScript, like some languages,
does actually support different numbers
of equal signs in certain context.
Let me open the same file with TextEdit just
so I can tweak some things, zoom in here.
You probably would have expected me to type this
and that it would actually work correctly too in all cases.
But it's not quite as rigorous as doing this.
Does anyone know what it means when you do not equals equals,
or if easier to answer the other way,
what this would mean, equals equal equals?
[ Inaudible Remark ]
Same instance-- not quite same instance
but same value and same type.
So, JavaScript, as I've mentioned earlier,
does have disparate types even though you, the programmer,
don't specify them when declaring variables.
You don't say string, you don't say int, you don't say float.
You just have access to those disparate data types.
When I check the type of localStorage
and I say not equals equals, this is making sure
that not only is the return value of typeof not equal
to "string", it is also at least a string itself.
This is in retrospect a bad example
because there is no instance in which this could go awry.
A better example, and I'll think of one in the future,
is that if I were checking the return value of some function
and it could return null for instance
but maybe it could return zero,
those two values are often conflated.
If you want to check a function's return value
that could return null or could return zero, you can't rely
on equals equals because they will implicitly cast
to one another.
Null is the same as zero.
But if you want to check that the return value
of some function is really, really null or really,
really zero, not just some implicit equivalent,
then you use equals equals equals.
Or if you want to check the opposite,
you use bang equals equals.
So I apologize, this wasn't a good way
to introduce that story.
We'll fix it in the video.
[ Inaudible Remark ]
Combining multiple characteristics let's say, sure,
of the values you're checking, both their--
of the storage container you're checking,
both its value and its type.
Long story short, getting into this habit is not a bad thing
because it means your code will never be vulnerable
to those random corner cases
where maybe two values could cast to the same thing.
The number one could cast to true.
The number two could cast to true, but true is true
if you use the identity operator in this way.
OK, let's not get too hung up on that
and instead move on to this.
Same trick as before but let's just take for granted now
that if typeof localStorage open bracket closed quote--
"counter" is undefined, what's the implication?
So let's try to rewind this.
This just says if the type of localStorage is not undefined,
that is equivalent logically to saying is localStorage defined.
Because if it is, I'm using a modern browser, supports HTML 5
and therefore clearly supports localStorage.
This one line of code is only checking does your browser
support localStorage.
Second line is checking not whether localStorage is
supported but specifically whether what is the case?
Is there a variable called counter inside of localStorage?
So localStorage is again a hash table, a dictionary,
an associative array, a key value storage mechanism,
whatever you-- however you want to think of it.
This is just saying if we have never before defined a value for
"counter", what do I want
to initialize its value to apparently?
I want to just give it a value of zero.
So this just means if this is the first time the person has
ever visited the site, obviously,
localStorage isn't even going to know that I care
about a variable called counter so let's make that exist
and assign it the value of zero.
Then let's trigger that alert.
You have visited this many times, and then what do I do?
Increment it again.
So this just ensures that that one time corner case is covered.
Else down here, your browser does not support localStorage,
it's what happens if it is in fact undefined.
So, where am I actually storing the value?
Well, I'm not actually using setItem or getItem,
it actually suffices just to use this array notation.
So, this is because localStorage itself is an object
and we can treat it as though it's an array
with the square bracket notation,
syntactic sugar if you will.
But in this case here, we're setting the value,
and in this case here we're setting the value as well
by just doing a traditional plus plus.
All right, so why might that be useful?
Store and user preferences potentially or other things
where you might want to remember some details about the user
without having to query the server again
and again for the same answer.
All right.
[ Inaudible Remark ]
If you switch the browser in what sense?
[ Inaudible Remark ]
Oh, good question.
That won't work.
This is browser specific.
So if I visit the page in Chrome,
I get localStorage within Chrome.
If I then open Safari,
Safari has its own localStorage container for me.
It does not propagate across browsers.
Yeah.
>> Are there limits to how much data you can store locally?
>> There is.
I don't remember the value offhand.
It's much bigger than a cookie but not infinite.
If that helps.
That will be my other mental note to check
and as RJ is probably reminding me now.
Yeah.
[ Inaudible Remark ]
Yeah. So I believe one of the various settings in Chrome,
let's see, clear browsing data, one of these should apply to--
it's probably the one that's simplified as empty the cache.
That probably includes localStorage.
Good question.
And then you can programmatically clear
by calling the clear method.
All right.
So let's introduce one other,
let's one particularly cool feature that we can leverage
in a mobile context by introducing this guy.
So it turns out, and this is retro if you were
around when the internet was popular with Netscape Navigator,
the navigator global object similar in screen to window
in document has special properties or methods associated
with it and navigator in this case, navigator refers
to the browser itself as opposed to the window or the document
that you're actually viewing.
Dot geolocation is an API,
an application programming interface, a set of functions,
maybe properties that you the programmer can use
to talk to the browser.
Inside of this API is at least one method
of interest today, getCurrentPosition.
Now this is a method that we can call just like getItem
or setItem but it works a little differently
that it doesn't just give me back the value right away.
Finding the user's location is what's called an asynchronous
problem to solve, right, because it might take a few seconds
to turn on the WiFi antennas or the GPS radio and figure
out where the user is and one of the key design features
of JavaScript is that as much as possible, things are--
should be asynchronous so that when something is happening
over here, it doesn't block something else
from happening here.
You don't want the whole browser to lock up while you're trying
to figure out the user's location.
It'd be nice if they could keep doing other things.
So the means by which you can implement that design goal is
by way of what are called callback functions
and we've seen these already
but now we can use them even more deliberately
with this geolocation example so let me go back
to my directory listing and go into geolocation0.html
and I actually don't see anything yet
but what do I see apparently in my browser.
Local host wants to use your computer's location
so my computer's location physically, GPS,
latitude and longitude.
Thankfully, Chrome is giving me a little bit of defense here
and not just telling a random website even though it happens
to be running on local host where I am in the world.
I mean this could get down to a pretty precise location.
You don't want just to give that information
out to anyone that asks for it.
So if I go over here, I can deny or allow this.
Well, let's allow this and now let's see what happens.
Apparently, this page's purpose in life is just
to tell me my GPS coordinates with some degree of confidence.
So we're at 42.3, negative 71.1.
So if we look that up on Google Maps, we'll probably end
up in roughly that location.
Let's actually see if we can search Google
by GPS coordinates.
Let's go to the actual maps.google.com.
Search here and indeed, we are-- turn on satellite view.
My laptop is underneath the grass there
and that's actually-- well, it's true.
We are in the basement.
So, it's pretty darn accurate.
So how in the world does my laptop,
which does not have a GPS radio, I'm not using my phone
or anything in this context,
how does Google know where my laptop is?
So WiFi, how do you mean?
>> The WiFi has its own [inaudible].
>> OK. So these-- there are WiFi antennas, there's one, two,
three, four, five, six of them in this room alone at least
and those WiFi radios all have unique identifiers of some sort.
They have the SSID to which we connect like Harvard University
and they other metadata associated with them.
For years, there was a technique known as wardriving which was
like literally people in cars driving around trying
to find open access--
WiFi access points for various reasons.
And companies among them Google do, do this too to figure
out just by driving around for instance
where do you hear Harvard University and they carry
around the GPS radio with that computer program to say,
"I heard Harvard University at these GPS coordinates."
But the world has gotten even more sophisticated
than 10 years ago.
Nowadays, we don't need cars driving around campus.
Who is doing all of the snooping for us?
Like all of us idiots, right?
Every one of us that has one of these cellphones in our pockets
that has a GPS radio and also has WiFi or 3G
or LTE access can be phoning home to Apple in this case,
or if you have an Android phone to Google in that case,
if you have a Windows phone, to Microsoft in that case,
telling the world when you're
on the Harvard University network what your GPS
coordinates are.
When you're on the Starbucks network,
what its GPS coordinates are.
So all of us are effectively phoning home
and training these big companies to know with some degree
of probability where we are.
And clearly, it works pretty well.
But that's because we've all been helping them for some time.
So putting aside the fear factor, let's just focus
on the positive which is what we can now do
with this functionality.
So apparently, I, any random guy
on the internet making a web page who knows some JavaScript
and has a web server can write JavaScript code
that asks the user for his or her location
and then does something with it.
In this case, totally underwhelming
and that we just prompted the user with their GPS coordinates.
But what could you use the location
for to be more a sexier application?
>> Show location on the map.
>> You can show the user's location on the map, right?
I kind of implemented that myself manually by going
to Google Maps and pasting it in.
We could do that programmatically
by using the Google Maps API.
The website could tell me
where the nearest Starbucks is based on my location.
It could tell me what the news is for Cambridge, Massachusetts
or the weather for Cambridge, Massachusetts 'cause it knows
where my coordinates are.
So, there's a number of things they can just lower the bar
to giving me things that I might be interested in.
So, it's a pretty compelling user feature albeit
at utter cost of privacy.
So, how do we go about leveraging this?
Let's look at the source code.
This is geolocation0.html.
Notice again, the body of the page is super simple
with an on-load attribute whose value is geolocate,
arbitrary named function that I wrote,
could have called it whatever we want.
Open paren and close paren means call it.
And now if we look at the head of my page where the script is,
again I could be putting this code in a separate file
but I've kept in the HTML file,
so all the demos are self-contained.
Notice that we have two functions.
One is literally called callback
and it takes an argument called position.
Let's come back to that in a moment,
one is called geolocate, no arguments.
What does it do?
If first checks if the type
of navigator.geolocation is not undefined.
So, what does it mean if geolocation is not undefined?
[ Pause ]
The browser supports it which means we can proceed to use it
without throwing one of those red error messages where like
"Symbol not found" or something like that.
So navigator.geolocation.get
currentposition and then I'm passing in what?
Callback, but notice, there's a close paren around callback
but what is there not?
There's not a pair
of parentheses right next to callback itself.
So, am I calling callback here?
So, no, I'm just passing its address effectively.
I'm passing a reference to that function
to the function called getCurrentPosition
so that he can call callback when he's ready.
Now, why might it take some time?
Well, we just saw an example.
If the browser prompts me, the human, to decide yes
or no, share my location.
That could be a minute later or a second later, an hour later.
You don't want-- necessarily want the whole web page
to lockup while you're waiting for the user's input.
So instead, you do this asynchronous trick whereby this
function getCurrentPosition will return immediately.
Close paren, semicolon, called,
but it will call my callback function when it's ready
to give me the GPS coordinates which could be a second,
a minute, an hour later.
That function when called takes an argument called position,
it turns out and I figured this
out by reading the documentation.
Inside of the position as returned by this function,
as passed by this function is another property called coords,
coordinates.
Inside of which more specifically is a latitude
coordinate and a longitude coordinate.
So by accessing latitude and longitude
and just concatenating them with a comma and a space,
I get that very simple prompt that we saw a moment ago.
So, it's as simple as that.
But we can refine this a little bit.
Let me open up geolocation one which looks
like it has the same behavior
but if I view the page source this time,
what have I done differently?
I'm trying-- I'm sort of learning from past mistakes
or reapplying past improvements.
[ Pause ]
What's different fundamentally about this example?
It's not undefined, so this we had before though.
[ Inaudible Remark ]
Yes, so I have a lambda-- an anonymous function,
a nameless function where?
Here. So, what function name did I used to use?
Literally callback, it could have been called anything.
I just called it a callback but if it's a callback whose purpose
in life is to get called once and only one location
and never again, why am I wasting time confusing me
and subsequent readers of the code with multiple functions?
Just put it where I want it.
Now, notice function open paren, close paren position,
so I'm still taking the same arguments.
I'm just not bothering to give it a name then I call the alert
and I have to be careful.
Notice I have open paren, open paren, close paren,
so those are balanced.
Open curly brace, so down here, I have to remember
to close the curly brace, close the close paren.
So, that's the only price you pay in just a bit
of syntactic potential for confusion.
All right, pretty cool what you can do with the browser.
Questions?
[ Pause ]
All right, let's do one last big feature
that will take us home here.
So here, I have an example called ajax0.html.
I said a moment ago, Ajax is asynchronous JavaScript and XML.
Though that's kind of a white lie these days 'cause it doesn't
always and if ever use XML these days.
What does it do, Ajax, for us?
[ Pause ]
[ Inaudible Remark ]
And so it lets asynchronously load data
from servers or asynchronously.
So, both actually.
So, the A means asynchronously.
You can run it in both modes.
And it looks like this which is a wonderful picture
which makes this super simple.
Oh, it's actually pretty simple once we look at it.
So, here we go.
Ajax is just a technique.
It is the application of built-in features of JavaScript
to programmatically get more data from a web page
after the original web page is loaded.
So, we've seen this for years.
Thanks to things like Google Maps.
For instance, when you click and drag
on a Google Map before you see more of the Earth,
you often see little gray tiles, gray squares,
before those portions of the map have downloaded.
But thanks to Ajax the code Google wrote
in JavaScript can ask Google.com, "Give me more tiles.
Give me more tiles."
Sometimes that takes a few seconds if the network is slow
and that's why those tiles only gradually appear.
Twitter, and Facebook, and Gmail, Gchat, all of these tools
with that you might-- that you might use
that update themselves overtime are using Ajax
to go get more data.
Rewind 10, 15 years when you had sites like Map Quest,
which still exist and I think you still use it
in the same way.
When you click the Up arrow, or the Down,
or the Left to the Right arrow to move the map,
it would reload the whole darn page.
That's before the days of Ajax.
So, Ajax let's us create the illusion
of the dynamically changing content
without having the force reload some whole page.
All right.
So, here's a picture that makes it less clear.
So, we have a user interface named "Little Browser,"
use some JavaScript in step one.
And this is actually worth knowing
or at least talking away this feature of JavaScript
that makes this possible is called an XML HTTP
request object.
So, much like we saw Geolocation,
much like we saw the local storage,
this is another key word introduced
to JavaScript a few years ago that allows us
to make these asynchronous calls back to the server.
All right.
Once you have instantiated one of those objects
as we'll see you send an HTP request, whoop, to the server.
Can't do that anymore.
Send an HTP to the server, it responds years ago with XML data
and occasionally still today.
And then your JavaScript code parses this thing called XML.
If unfamiliar, XML is like home made HTML.
It's make your own tags, make your own attributes,
but there's a simple format these days called JSON, J-S-O-N,
which is more popular and lighter weight.
So, when you get this XML back, you then do something with it.
So, this is a cryptic five-step way of explaining how Google
and Facebook and Gchat and Twitter go
about dynamically updating their DOMS
without reloading a whole page.
They're just making more HTP requests across the wire.
And, we can probably see this.
What might be-- Let's see if I can pick a site
that without logging in would do this for us.
Let's-- What is a site that could do this.
Google live stream?
No. That doesn't work.
Twitter? Yeah.
Who's the fam-- Who is famous-- well, no, no, that won't work.
We need someone.
Almost every site on the internet does this today.
And I can't think of one.
[ Inaudible Remark ]
OK. What's trending [inaudible].
And let's draw something acceptable?
[ Inaudible Remark ]
Oh, only I am seeing the material.
There you go.
All right.
What's happening right now?
What's popular today?
News.
[ Laughter ]
All right.
In five hours ago or three minutes ago--
well, let's see there must be some aspects here.
Let's see if we can cheat.
[ Pause ]
This is a horrible demo.
[ Laughter ]
OK. So, let me fake the story
and then I'll come better equipped.
I will stop doing spontaneous demos.
That's what I'll do.
So, what I did was I opened the same tool that we opened earlier
which is Chrome's Inspector tab and again Safari and IE
and Firefox have the same kinds of tools.
And-- Oh, there we go.
And I clicked on the Network tab
because as I expected we would have [laughter] this little row
appear here.
And if we waited long enough--
so, what happened is apparently Twitter's JavaScript code is
making an Ajax call every half a minute, minute,
however often that's going to flash on the screen.
And if I click Hover on this, you can see that the URL
that was requested was this long one here, twitter.com/i/search.
And that is because Twitter instantiated one
of those XML HTP request objects and just made an HTP request
from the client's side JavaScript code
that I downloaded a minute ago back
to there servers presumably checking for more tweets.
And there might not be new tweets,
but they're at least pulling their servers to check
for some amount of time.
And indeed, if I click on this request,
we won't go into much detail here on this
but you can see all of the HTTP headers.
You can see exactly what came back in their response.
Apparently, there were more items.
There's a key called has more items.
So Twitter is actually using JSON,
JavaScript Object Notation instead of XML.
But any side, if you are a Facebook user, Gmail,
Gchat user, tonight and you use Chrome, log-in into one
of those websites and just watch the network tab
of the Chrome inspector
and you'll see pretty constant traffic.
Certainly if there's a busy side or if you're chatting back
and forth with friends, you'll see all of these HTTP requests.
This is arguably what makes the web
or web development really interesting these days
and that you can make much, much more dynamic sites as a result.
So this site as we'll see allows me to get a stock quote.
Let me type in something like GOOG
which is the ticker symbol for Google.
Get quote and there's an error with the Ajax call.
So why might this be?
So let me go back over here to my-- oh, tsk, tsk, tsk.
Let's see how to do this.
Let's open Ajax 0.
Ah, that's why, typo.
GOOG, get quote.
There we go.
So I renamed the file earlier and forgot
to change it in the HTML.
So, apparently, as of 4:30 p.m. or so today,
the Google stock price is 869 dollars and 79 cents.
So I did not know that in advance though technically I
could have just hard coded this I supposed
after 4:30 p.m. for a 6:30 class.
But this was in fact fetched dynamically
and if you use the same demo tomorrow morning,
you would get a different answer slightly and certainly
for other websites, we could get back different stock quotes.
So let's see how this is working underneath the hood.
If I do the page source, let's scroll
down to the easier part first.
There's some HTML at the bottom
and it's really just a super simple form that borrow some
of the lessons learned from earlier
on submit called what function.
Quote, this is in a built-in function,
this is apparently one I wrote up above
that we'll look at in a second.
Return false so that it doesn't actually submit to the server
in the traditional way.
So Ajax is all about sending data to the server.
It's just I don't want it to be submitted via that form per se.
I want it to be submitted via my code, my event handler up above.
So this symbol is an input.
Autocomplete is off.
It has an ID of, let's scroll to the right, "symbol".
That's probably going to be useful
so I can uniquely identify what the user typed in.
So let me zoom out and scroll back up and you're going
to see some mess of a code.
And here to jQuery, we'll make our lives better.
So at the top of my script tag, I have a variable called XHR,
could have called it anything, XMLHttpRequest initializing it
to null just so that the variable exists for me.
Down here, I have a function called quote
with some simple comments above it to remind me.
And now, we have kind of a mess of code
that again is dramatically simplified by libraries.
But I'm going to try
to instantiate a new XMLHttpRequest object.
If something goes wrong,
something called an exception is going to be thrown,
the browser specifically if it has no idea what this symbol is,
XMLHttpRequest 'cause I'm using Netscape 1.0
or many versions of IE.
It will throw an exception that I am prepared to catch.
If I do catch it, I am going to reasonably but not definitively
and assume that it's what browser.
Yeah. So there's a lot of this kind of code on the internet
because IE 6 and 7, and 8,
and 9 to some extent have not always played so nicely
with certain standards and all the browsers kind
of cut corners here and there.
But this is just an example of error checking code
and what jQuery will do for us
in just a few moments is collapse all of these messiness
and all of these care about what browser the user is using
into a simple function call.
But what's really going underneath the hood is something
like this.
So this is raw JavaScript code.
I proceed to check if the XHR object is null, then I'm going
to return in alert saying, "Ajax is not supported
in your browser," but we didn't see that.
And then down here, I'm going to do just a little bit more work
to make this magic happen.
I'm going to declare a variable called URL whose value is
quote.php and it happens to be written in PHP
but that's just 'cause it's a language I know.
It's-- I'm running it on a PHP-supported server.
XAMPP comes with support for a PHP.
Question mark symbol equals and then what am I concatenating
on is the value of that URL, its parameter,
whatever the symbols value is
that the user typed into the DOM.
So the only thing new in this example besides the exception
handling stuff is the fact that I'm using PHP,
but we're not even going to look at the PHP code.
Just know that it's returning dynamically a price using some
PHP code, talking to Yahoo Finance in real time.
[ Inaudible Remark ]
Yes. We will simplify all this code in a moment with jQuery
to get rid of most of these lines.
So the last thing I need to do is actually contact the server.
All I've done this far is create a string,
a variable that is a URL.
Now, I need to do something with that URL.
So I need these three lines.
My XHR object which again is my sort of gateway to the server
for this feature called Ajax.
Horrible property name, onreadystatechange,
what am I going to call?
Call my handler function.
So in a moment, we'll see a function called handler
and this is just my way of saying, "Hey, special object,
when you change state, when you turn on, when you turn off,
call this function so I can check what's going on,"
is what that boils down to.
Open is opening a TCP connection to the server,
HTTP specifically connection using the GET method,
if familiar.
If not, don't worry.
It's the opposite of post
to this URL making the call asynchronous.
Asynchronous means this function will return immediately
and handler will get called when the server,
if the server eventually replies.
By contrast, if we made this false and said,
make the open call synchronous, that would mean
that this function open would not return
until the server answered back to me which is not what we want.
We don't want the whole page to lock up just
in case the server is slow.
Finally send null, this means I have no more arguments,
no post data, just send the request.
So some number of milliseconds, seconds, minutes, hours later,
the handler function will get called because the state
of this object will change just because the network responds--
the server responds with an answer.
What does handler do?
It's pretty straightforward.
It first checks this and you would only know this
from looking in the documentation.
If the readyState value of the object is four.
So there's literally a cheat sheet.
Four is good.
Four means the whole thing is done.
A request went, it came back, it's been examined
and it's ready for you.
If you're in request state four
and the server's response was 200, 200 is the opposite
of something like 404, 403, 401, 500 error codes
that if you ever see them are bad.
200 is when you never see 'cause it's good, literally OK.
The request worked, then go ahead and alert the user
with the window to xhr.responseText.
And again, you'd only know this
from looking at the documentation.
responseText is the value of whatever the server spit out.
And in this case, all the server spit out was 800
and some odd dollars just the super simple text string.
In the case of Google Maps, it would have spit
out a ping or a JPEG or a GIF.
In the case of Facebook,
it would have spit out a status update.
In Twitter, it would spit out a tweet and so forth.
And in this case, it's just a stock price.
So how can we simplify this code?
Well, let me go into a slightly cleaned up version--
>> Sir?
>> Yeah?
[ Inaudible Remark ]
Oh sure. It was just a stupid mistake on my part.
If I go into the source of ajax0, I'll--
you'll have to fix this as well and I'll fix this tonight online
and re-upload the file.
I had accidentally called the file quote1.php,
but it's actually quote.php.
I renamed it earlier.
So I'll fix that permanently.
Ajax1.html, so here is a very version
that we had not looked at, at source code but you can kind
of guess that this is a little better.
In what sense is this example about to be better designed?
Yeah.
>> They have annoying alert [inaudible].
>> Yeah, no annoying alert.
We're kind of doing something that approximates the idea
of what Twitter and Facebook do is that they update the DOM.
They change the contents of the webpage itself
by inserting new data dynamically.
So where I say to be determined, let's hope that's actually true.
First, let me look at the source
and make sure I didn't mess up the filename.
It's OK. I did correct this one earlier.
So now if I typed in GOOG, get quote,
the page is dynamically updated itself.
If I reload the page, notice it goes back to its defaults
and now let me show you one other feature
of Chrome inspector and again,
different browsers have this in different forms.
I'm going to go ahead and control click or right click
on the word "determined" or really anywhere in that area.
I'm going to click Inspect Element and notice what happens.
By default, I'm already on this elements tab.
But if I-- I'll zoom it in a moment,
if I choose Inspect Element,
notice that the browser very helpfully expanded the HTML
in this inspector tab and highlighted the actual HTML
that I ask it to inspect.
So no matter how messy your HTML is, which it shouldn't be,
this inspector shows you everything beautifully
hierarchically, essentially giving you a navigable version
of the DOM.
This is the tree and it's indented exactly as it should be
to convey the notion of hierarchy.
So, watch what happens now.
It's going to be a little small so I'm going to do this one.
I'm going to type in GOOG.
I'm not going to hit Enter or submit yet.
I'm going to scroll down to the bottom here and now,
I'm going to hit Enter while this is on screen
and what do you expect should happen to the actual DOM
which again the inspector here is showing me?
It should actually change.
That rectangle's value should be changed from "to be determined"
to 800 dollars something.
So, here we go.
Enter, and indeed, it actually changed.
So, this probably didn't take much effort 'cause we're just
replacing the alert function
with something slightly more elegant and indeed,
if I go into my handler function, notice,
there's only one real change.
I've replaced my alert line with this guy here,
document.getElementById of "price".
But wait a minute.
We haven't seen a price ID before
but you can probably infer where is it probably.
The text, which text.
The "to be determined".
So, let's actually go
to the HTML 'cause I must have made some other change here--
oh, interesting.
So, price colon, it does say "to be determined"
and there was a bold-faced tag but I also wrapped it
with an inline element, a span element which is like a div
but it doesn't force a line break and I gave it arbitrarily
but usefully, an ID at the value of price
so that I can uniquely identify that string there.
So now, up above, let's see what the rest of this line is.
getElementById of price dot innerHTML.
So, there's different ways of doing this
and this is somewhat of a kludgy approach.
The right way to do this would be to create a new text note
to remove the old text note, insert or append the text note
and it would take three lines of code.
It actually tends to be slower at least if you're doing this
for lots of nodes in a DOM like a Facebook or a Twitter does.
InnerHTML literally just says, "Cram the new content
where the old HTML should be,"
without actually parsing it like DOM objects.
So, this gets the job done here.
If I scroll to the right, I'm just pushing the response text,
the 800 dollar string into the innermost HTML of that span
which is why we saw DOM element update a moment ago.
So, if we do it again to recap now with that context
and I pre-type in GOOG.
I don't hit Enter yet, but I instead scroll down to
where it says "to be determined",
is the span tag going to be replaced or the bold tag.
[ Pause ]
>> Bold tag.
>> Just the bold tag because when I uniquely identify the
span element by its ID called "price" and change its innerHTML
that won't blow away the span tag itself, just its innerHTML
which is apparently a bold-faced and a line
of text "to be determined".
So, if I hit Enter, sure enough, that changes.
It would be somewhat counterproductive
if the active updating the span tag with the unique ID
of price has the effect of blowing away that span tag
with the unique ID 'cause then I could never update it a second
time maybe a minute or so later if I actually did this
in a loop with the timer.
All right, let's clean this up ever so slightly more.
In ajax2.html, if I view the source here,
notice that I've done a way with quote.php.
The one thing I don't like about those previous two demos is
that it requires that I'd be running a web server
that supports PHP that I have written
in advance a file called quote1.php and that three,
the reader knows something about PHP to actually look at it.
In reality, it's a super short file.
It's not hard to understand but it's still a dependency.
If the whole point at least of this person of the course is
to do client side development and not have to get tied
down to some language like Java or Python or Ruby or PHP,
it'd be nice if we can eliminate my PHP dependency all together.
Now, the catch is that there's a problem.
Yahoo, as I said before, is the one supplying the data.
Long story short, Yahoo Finance let's you grab data
in CSV format, sort of poor man's Excel format
which is nice 'cause it's just text and I can parse it
by splitting on the commas that separate the values.
The problem though is that because
of a policy called the "Same Origin Policy".
When you write JavaScript code and you query a server
like Yahoo for data using JavaScript, Yahoo can reply
to you and give you that stock price,
but you are not allowed typically to do anything
with the value that involves manipulating your DOM.
In other words, if you have a DOM from your own server
from the HTML and you're running some JavaScript code that talks
to Yahoo and Yahoo says, "Here is a piece of data for you,"
you cannot add that piece of data to your own DOM.
It sort of breaks a barrier that's meant to exist
between your site and others
so that certain threat scenarios don't necessarily arise.
This is obviously kind of a problem.
I worked around this in the first two examples
by writing quote.php who's a middleman, a proxy of sorts
that gets the data from Yahoo then replies to me
so that rather than the data going Yahoo to browser,
Yahoo to browser, it's going server-Yahoo-server-browser.
But now, I'm this middleman, God forbid my server goes down,
then my website won't even work in terms of the PHP code.
So, it's just an unnecessary barrier.
Not to mention, it requires code that I read on the server.
It'd be really nice if I could just talk to Yahoo.
Some companies allow you to grab their data via JSONP format,
JavaScript Object Notation Padded format.
This is just a fancy way of saying,
it's a different type of JSON.
We've seen JSON briefly in the browser,
but it's actually super simple.
You may recall from earlier that--
what is the syntax for an array.
If I have an array, we'll call it "foo".
In JavaScript, how do I get myself an empty array?
Square brackets.
How do I give myself an array containing the number 42
like this?
42, 43-- 42, 43, 44.
So, it's just as you would expect
in most any similar language.
What about now an object?
An object in JavaScript is just the incarnation of a hash table,
an associative array, a dictionary,
a collection of key value pairs.
The syntax for an empty one is this.
How do we have key value pairs?
We only briefly glimpse this earlier but you do it
in this form, key: value.
And if you want another one key2: value and this is a bit
of an oversimplification to be super proper JSON keys
and values need to be coded even though this is the pain
in the neck.
It's not strictly necessary in JavaScript.
It is necessary in JSON.
So, this now is a collection of two key value pairs.
So what if I want to get back an array of objects?
I could get back an array of key colon,
this going to get tedious quickly, value, key2 colon--
oops-- colon value, we'll stop there.
So, you can combine these basic syntactic constructs to come
up with arrays of objects,
objects with arrays inside of them and so forth.
This is essentially JSON.
It's JavaScript Object Notation.
So, when Google sends back data, when Twitter sends back data,
when Facebook sends back data, they're not usually using XML
which looks like HTML these days, they're using this
because it's much lighter weight
and more compact among other reasons.
So, what's the point here?
Well, if Yahoo Finance were spitting out not just JSON
but padded JSON, I could work around the same origin policy
and we won't dwell too much on the details
but padded JSON means that the data coming back
from a server can be embedded into your website.
As you'll see in the first project,
the spect for which will release online on Wednesday,
there is a service that is coincidentally made
by Yahoo called YQL, Yahoo Query Language that simply allows you
to query websites like Yahoo Finance, Facebook, Google,
Twitter, any website on the internet.
And if they expose their data as JSON data or XML data,
Yahoo Query Language will allow you to fetch that data
and it will wrap it in this modified version
of JSON called Padded JSON
so that you can integrate the results into your own page.
So, this will become much more clear in the project spec,
but for now, notice that the solution is as simple
as a URL that looks like this.
So, this URL you'll notice hits Yahoo, their YQL server.
Notice that if I really look hard in here,
you can also see finance.yahoo.com mentioned.
So, this is essentially a URL, took me a couple of minutes
to construct and they have a little GUI that helps you figure
out what the syntax should be,
but these just is a URL that's going
to tell Yahoo's query service to go ask Yahoo Finance
for a stock quote, then return it to me in padded JSON format.
And the only difference with padded JSON is
that whereas Twitter a moment ago returned to us a string
that looks like this,
padded JSON would literally return something that looks
like this so that you are tricking the server effectively
into returning a snippet of JavaScript code
that looks exactly like a function call.
And so long as I, the developer, have written a function called
"callback" or whatever it is, my data will get passed
to that function, thereby circumventing the story
that I've told even though we haven't tripped
over it ourselves.
And again, you'll deliberately encounter this
in the first project and this is why you'll be using YQL
to get data back from a server so that you don't have
to use PHP or Python or Ruby or Java
or anything in the appliance.
All of your code will be client side and you won't run a foul
of this restriction, but we promise to simplify this.
So our last touch to this Ajax example
which still works the same GOOG, pops up the 800 dollars.
If I view the page source,
notice that I can now simplify my code as follows.
I'm still using this longer URL but that's just
so that I'm avoiding the same origin as you.
I can change this back to quote.php.
Here is how in jQuery I can get a quote.
I call $.ajax.
So this looks a little weird.
But again, remember that that dollar sign is just shorthand
notation for a function called jQuery.
So this is jQuery.ajax as is common
in JavaScript is you'll see
with various libraries online many functions take not a comma
separated list of arguments as their values,
they often take a object of key value pairs
so that the order does not matter.
It's just a nice convention.
Pearl does this a lot and Python can do this and other languages.
So this is saying one of the keys being passed
into this method is called data type "jsonp".
I'm just telling jQuery what response to expect back.
The URL is-- has a value of URL and that's it.
There's a little bit of magic.
It turns out and this is just to pave the way
for the first project.
Notice that somewhere in this long URL, I have told Yahoo
that my callback function will be called handler.
The name we view as before.
So jQuery is actually and this is one of these hidden features.
Well, it's in the documentation, but it's not obvious.
jQuery, if it notices that you are contacting a server
with the parameter whose value is callback equals something,
jQuery will very nicely assume that, "Oh, when I get a response
from this URL, I'm going to call your function called handler
which just means that we're on the system here."
I just have to make sure
to implement this thing just like I did before.
So handler expects a response.
I happen to know by reading Yahoo's documentation,
if the response object has a query property,
has account value of one,
that means I got back one stock price, and it took some trial
and error to figure out what the server were sending me,
but I figured out that it should equal one, and when the happens,
I should output response.query.results.
row.price, very convoluted number of steps to get
to that point, but again, you'll see in the first specification
of the project exactly what's that doing
and why it's doing it.
Questions on-- I know that was a lot.
Questions on Ajax having just started JavaScript an hour ago.
[ Inaudible Remark ]
When the-- yes.
When the server calls the callback function,
it passes in the response arguments, also tucked away
in that response argument, which I didn't bother using this time
or the 200 and details like that,
because jQuery similarly checks those kinds of things for me
so I don't have to worry as much about it.
All right.
So that was jQuery.
So that only leaves a semester of Objective-C.
So Objective-C as we will see is much more mind bending at least
at first for most people than JavaScript, but rest assured
that this coming week,
on Wednesday we'll have our first lab with RJ and Rob,
it will be an opportunity to dive in hands on with some
of this code and some of you seemed to be following along
with some of it, but we'll look at other examples
that apply these same concepts and we'll also give you a tour
of the first project which will involve mashing together some
location information, some weather, some news, some HTML,
some JavaScript, and we'll leverage concepts like Ajax
and the like but won't necessarily go
into as much detail as some of these things here
and you'll see the spec too will hold your hand through a tour
of some of these concepts and technologies
that might be unfamiliar.
And two weeks hence in the lab 2,
we'll also offer another opportunity to explore
that material and specifically explore the project
for which there are roughly two-week deadlines
as you can see in the course's syllabus which is at cs76.net,
but very quickly will we transition to Objective-C.
And so what we'll do next Monday when we return for lecture
and I unfortunately have to be at a conference.
Rob will be leading us on Monday.
We'll be diving into Objective-C itself for those unfamiliar, C--
Objective-C is a super set of C. For those unfamiliar with C,
we will give you a crash course on Monday in C
and everything you need to know about memory management
and pointers and the syntax thereof,
so that we can focus really on the OO features of Objective-C
and then transition toward the end of next week--
or rather the start of week three to the iOS SDK,
software development kit,
and even though next week we'll spend some of our time
in Xcode and/or at the command line, ultimately,
we'll spend most of the semester in a tool that looks like this.
I've opened up most of the panels
for this particular screenshot,
but Xcode which is Apple's integrated development
environment, similar in spirit to NetBeans, or IDE,
or similar tools if you're familiar is kind of designed
to make programming fun and look like iTunes
such that once you write your program, all you do is hit Play
and everything just works nicely in the simulator
or if you connect a USB cable, it will burn the software
onto your device if you so choose.
But through this environment, we'll use Objective-C.
We'll use a tool called interphase builder
that allows you to construct fairly simple
but fairly quickly user interfaces that are very similar
in spirit to iOS 6's paradigm.
You'll be then able to compile and run them in the simulator
or if you have a device, again, we'll set you up with that.
Word on iOS 7, the tragedy of summer course and the tragedy
of WWDC, which is Apple's conference, which always happens
like two weeks before the semester begins,
is that they always start to--
they announced that things are changing
and then they actually change like two months later.
So we're in this sort of weird limbo state, but thankfully,
there's nothing-- most of the changes in iOS 7 are aesthetics
so far as we would be concern for a class like this.
Underneath the hood, there's new functionality,
there's some new method, there is new--
some new constants and the like,
but nothing that will fundamentally change any
of the things we do over the next six to seven weeks
so you can rest assured legitimately
with this transition to iOS 6 and 7
that everything we explore will continue to apply,
that wasn't the case from iOS 5 to 6
where some fundamental aspects
of Objective-C itself were altered.
So if you're a bit worried about that, rest assured
that will be OK and the transition
to iOS 7 should be a fairly smooth one for you
if you take things further.
Beyond that, we will ultimately start in a couple of week's time
with the simplest of hello world applications
and then go much, much beyond that.
That's it for tonight.
I'll stick around for questions with Rob or RJ.
Otherwise, we will see you on Wednesday
across the hall and B108.