Javascript & jQuery
CDGD304 - Fall 2011
http://bit.ly/massart-304-8
HTML/CSS Are Static
(Now only mostly true, as you can add interactivity via CSS Hover, Animation)
Anything else dynamic is "programmed"
Animation effects
Sliders
Drag and Drop
Autocomplete
Ajax
And, unless it's flash..
It's programmed in Javascript
"Lingua Franca" of the Web
Disclaimer:
Programming is Hard
We'll do our best..
But you're not going to learn it in a day. It take a lot longer than that...
About Javascript
First created in '96
Nothing, whatsoever to do with Java.
People hated it for a long time. Now people love it.
Now can be used for:
Client Side
Server Side
Mobile (iPhone, Android)
Desktop
Javascript is both:
-
The worlds most popular language (beat Visual Basic)
-
The world's most unpopular language (people love to complain about it)
Why so much hate for JavaScript?
Incompatible Implementations
OO, but not a classical inheritance
Initial Implementation were slow
It looked like a silly toy next to Flash
No AJAX to start with (while Flash did)
What Changed?
The "Gmail" and "Goole Maps Era" (2004-2005)
Google Maps
"Framework Era" (2005-Today) jQuery
The "javascript MVC era" (2010-Today) salon.io
Where does Javascript go?
Similar to CSS - multiple options (notice: type='text/javascript' NOT required in HTML5):
- Include external .js file via:
<script src='file.js'></script>
- Include in the <head> tag
<script>
Our Javascript Code Goes Here
</script>
- Include in the <body> tag
<script>
document.write("Let's write some HTML right here!");
</script>
- Include as an event
<a href='javascript:void(0);' onclick='alert("Hello World!");'>
Where do we prefer?
Also Similar to CSS - the less 'inline' the better. (Generalization)
Downright Bad: Include as an event
Even Less Good: Include in the <body> tag
Less Good: Include in the <head> tag
Best: Include external .js file
Again, we're not really teaching "programming"
There's way too much to try to cover in 1 class
We're really want to be able to use jQuery
And need just enough Javascript to get by.
3 Main Goals for today
-
Be able to read and understand some JavaScript
-
Be able to manipulate documents with jQuery
-
Be able to use jQuery plugins
What is jQuery?
-
Most of what we do in Javscript is manipulate the DOM and Ajax
-
These are very long and cumbersome to do in straight javscript
-
On top of this, different browsers have different behavior
-
jQuery is a library that makes this easy and clean and consistent
-
Works with CSS selectors
What pieces of Javascript do we need to understand?
-
Strings and numbers - basic pieces of information
-
Variables - where to store pieces of information
-
Functions - how to call reusable pieces of code
-
Callbacks - functions that get called in response to something else
-
Arrays - store a list of values (like a list of variables)
-
Objects - We just need to understand a little bit on these
-
Conditionals - controlling what parts of a program executes
A Little Demo
The goal is to understand everything in here by the end of class today
Javascript Housekeeping
Hello World!
Call the built in 'alert' function and have it say "Hello World!" We don't use this all that often (it's ugly) - but it's really useful for debugging.
Our friend the console and console.log
Puts a result in the console - use Chrome or Firebug (must be open)
What is a variable?
-
Stores a value
-
Defined with “var” keyword*
-
Can be assigned with a single "="
-
Can be changed with +=, -=, *=, etc. (which are just shortcuts to ( i = i + 1 )
-
Are assigned by value to simple types, reference for objects.
Variables
Let's do some math and some string manipulation and write out to the console.
Scope
You can only use variables that are defined in the scope you call them.
Functions
Created with the "function" keyword, create reusable pieces of functionality.
Returning from Functions
Use the return keyword to pass a value back to whatever called the function
Timeouts
we can use setTimeout to have something happen later, try it
Anonymous functions, callbacks
We don't have to give our callback function a name, we can do it anonymously
Why callbacks?
A lot of stuff on the web happens "Asynchronously" - AJAX, user actions, etc
Arrays
-
Stores an “array” of values.
-
Usually created with the bracket [ ] operator:
var arr = [ 10, 20, 30 ];
-
Pull out a value using square brackets [] starting at 0:
arr[0] // 10
arr[1] // 20
-
get the number of entries with .length
arr.length // 3
Playing with arrays
Objects
Objects
Conditionals
-
Things in javascript are either true or not true.
-
0, false, null, "" are all false
-
Everything else is true.
-
Use operands to check relationship between two values:
==, ===, <=, >=, !=
1 == 2 // false
1 == 1 // true
-
Basic conditionals:
Conditional Exercise
Use a conditional to check if a user confirmed a ok/cancel question. Then use prompt and test against a return value.
jQuery Basics
-
Everything is “namespaced” inside of the jQuery object, which is aliased with “$”
-
...which means everything you do in jQuery starts with a $
-
Uses CSS selectors for picking pieces of the DOM out.
Docs are your Friend
Loading jQuery
Include from a CDN or locally
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
Or
<script src='js/jquery.min.js'></script>
Need to make sure we have the file in the right location, can view in browser if there's a problem.
Using jQuery
Since we often include Javscript in the head of the document, we need to make sure we wait until the
page is loaded before we use it. We can use the jQuery bind function to load stuff at the appropriate point.
<script>
$(document).bind("ready",function() {
// Dom Loaded
});
</script>
Why this is important..
Shorthand
Since this is so common, we can use a shorthand for this of $(function() { }) ...
<script>
$(function() {
// Dom Loaded
});
</script>
Basic selection + manipulation
Let's try out $.text, $.html, $.hide, $.show, $.css, $.attr, $.addClass, $.hasClass, $.removeClass
Selector Docs / Manipulation Docs
Some basic DOM insertion
Let's try out creating elements with $(), then using $.before, $.after, $.append, $.prepend, $.wrap, $.appendTo, both with text and elements.
Fun Stuff: Animation and transforms
$.fadeOut, $.fadeIn, $.slideDown, $.slideUp, $.toggle, $.stop, $.animate
Events
$.bind, $.click, $.dblclick, $.mouseenter, $.mouseleave, $.hover
Demo Revisited
The goal is to understand everything in here by the end of class today
Putting it all together
Let's use two buttons to increase and decrease a counter.
Plugins: Barebones
Let's use the cycle plugin: http://jquery.malsup.com/cycle/ (images from http://lorempixel.com)
Cycle: Style and Options
Ajax
$.ajax, $.get, $.post, $.getJSON
JSONp
Ajax is same-domain only. So there's a hack to pull data across domains called $.getScript
Homework
Coding
-
Through both the beginner and intermediate courses on codecademy