SlideShare a Scribd company logo
JavaScript
MSc. Hoang Ngoc Long
Outline
• Philosophy of jQuery and API Walkthrough
• Dev Tools
• Bare-bones JavaScript
• jQuery Selectors and Traversing
DOM Scripting
DOM Scripting
•Based on web standards
•Tests features, not browsers
•Unobtrusive
Unobtrusive
custom.js
Behavior Content
index.html
Presentation
style.css
DOM Scripting
•Verbose
if (!document.getElementsByTagName) { return false; }
var quotes =
document.getElementsByTagName("blockquote");
for (var i=0; i<quotes.length; i++) {
var source = quotes[i].getAttribute("cite");
if (source) {
var link = document.createElement("a");
link.setAttribute("href",source);
var text = document.createTextNode("source");//!?
link.appendChild(text);
var para = document.createElement("p");
para.className = "attribution";
para.appendChild(link);
quotes[i].appendChild(para);
}
}
jQuery
Interaction for the Masses
Just a few of jQuery's
Benefits
•Lets you move quickly from beginner to advanced
•Improves developer efficiency
•Excellent documentation // pats self on back
•Unobtrusive from the ground up
•Reduces browser inconsistencies
•At its core, a simple concept
Unobtrusive
jquery.js
custom.js
Behavior Content
index.html
Presentation
style.css
Reduces browser
inconsistencies
•Example:
Get the height of the viewport…
var x,y;
if (self.innerHeight) { // all except Explorer
x = self.innerWidth;
y = self.innerHeight;
}
else if (document.documentElement &&
document.documentElement.clientHeight) {
// Explorer 6 Strict Mode
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
}
else if (document.body) { // other Explorers
x = document.body.clientWidth;
y = document.body.clientHeight;
}
DOM Scripting
var x = $(window).width();
var y = $(window).height();
jQuery
Documentation &
Support
– API: api.jquery.com
– Forum: forum.jquery.com
– IRC: irc.freenode.net, #jquery
– Coming Soon: learn.jquery.com
Download
• Download at https://jquery.com/download/
• Or using jQuery with CDN
<script src="https://code.jquery.com/jquery-3.6.0.min.js></script>
Simple Concept
• Find something
• Do something
Find Something
"Select" elements in the document
$
$( )
$('div')
$('#id')
Do Something
Do Something
1. Let elements "listen" for something to happen …
• the document is ready
• user does something
• another "listener" acts
• a certain amount of time elapses
Do Something
2. … and then do something
a. Manipulate elements
b. Animate elements
c. Communicate with the server
Dev Tools
Dev Tools
• up to five browsers to test against
• Firefox
• Chrome
• Internet Explorer
• Safari
• Opera
• developer tools can make your life much easier
Browser Support
• Modernizr
• http://www.modernizr.com
• Can I Use?
• http://caniuse.com
Code Sharing
• jsfiddle
• http://jsfiddle.net/
• jsbin
• http://jsbin.com
• TextMate
• jQuery Bundle:
http://github.com/kswedberg
• JavaScript Tools Bundle:
http://github.com/subtleGradient
• Sublime Text 2
• MacVim
• Espresso
• jQuery Sugar:
• code.google.com/p/espresso-jquery-sugar
Text Editors
Mac OS X
• E
• jQuery Bundle:
http://github.com/kswedberg
• Eclipse / Aptana
• Notepad++
• Visual Studio
• and so on.
Text Editors
Windows
• Console
• DOMViewer
• JavaScript debugger
• Net view
• Lots of extensions
http://getfirebug.com/wiki/index.php/Firebug_Extensions
Firefox: Firebug
Chrome Developer
Tools
• In many ways, leapfrogging Firebug
• Live debugging, code changing
• Lots of "hidden" goodies
• http://code.google.com/chrome/devtools/
• Paul Irish screencast: http://youtu.be/nOEw9iiopwI
• Included since Safari 3.1
• Similar to Chrome Dev Tools, but not as advanced
• Activate via Preferences > Advanced
Safari: Developer Menu
• Much, much better than in previous versions.
• Finally includes a console.
Internet Explorer 8+:
Developer Tools
• CompanionJS:
tinyurl.com/companionjs
• IETester:
tinyurl.com/dbtester
• MS Developer Toolbar:
tinyurl.com/msdevtoolbar
• Script Debugger:
tinyurl.com/msscriptdebug
• None of them comes even close to the tools available in other
browsers
Internet Explorer <= 7
Bare-bones JavaScript
The Basics
• Strings: textual content. wrapped in quotation marks (single
or double).
• 'hello, my name is Karl'
• "hello, my name is Karl"
• Numbers: integer (2) or floating point (2.4) or octal (012) or
hexadecimal (0xff) or exponent literal (1e+2)
• Booleans: true or false
In JavaScript, you can work with the following things:
The Basics
• Arrays: simple lists. indexed starting with 0
• ['Karl', 'Sara', 'Ben', 'Lucia']
• ['Karl', 2, 55]
• [ ['Karl', 'Sara'], ['Ben', 'Lucia']]
• Objects: lists of key, value pairs
• {firstName: 'Karl', lastName: 'Swedberg'}
• {parents: ['Karl', 'Sara'], kids: ['Ben', 'Lucia']}
In JavaScript, you can work with the following things:
Variables
• Always declare your variables!
• If you don't, they will be placed in the global scope
(more about that later).
• bad: myName = 'Karl';
• good: var myName = 'Karl';
• still good: var myName = 'Karl';
// more stuff
myName = 'Joe';
Variable Scoping
• All var statements hoisted to
top of scope
function foo() {
var x;
x = 2;
// Same as:
function foo() {
x= 2
var x;
§ Two scopes: Global and function local
var globalVar;
function() {
var localVar;
if (globalVar > 0) {
var localVar2 = 2;
}
// localVar2 is valid here
}
localVar2 is hoisted
here but has value
undefined
Conditionals and
Operators
• conditionals:
• if, else
• switch
• operators:
• +, -, *, %, ++, --
• >, <, ==, !=, >=, <=, ===, !==
• !, &&, ||
Loops
• Loops iterate through a list of some kind.
• A common pattern in JavaScript is to build a list, or collection,
and then do something with each item in that list.
Loops
• CSS uses implicit iteration.
• div { color: red; } /* applies to ALL divs */
• JavaScript relies on explicit iteration. Must explicitly loop
through each div
• jQuery allows for both (because it does the looping for you)
Loops
• The two most common loops...
• for loops — for general-purpose iteration. Used with
arrays or array-like objects)
• for-in loops — used with arrays or objects (but don't use
with arrays)
• The other two are...
• while loops
• do-while loops
for (initial value; condition; increment) {
// code block
}
for Loops
• three statements and a code block
1. initial value
2. condition
3. increment
for Loops
for (var i = 0; i < 3; i++) {
alert(i+1);
}
This is your variable, so
it can be anything!
(but developers often
use “i”)
for Loops
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
// do something with each div individually
divs[i].style.color = 'red';
}
for Loops
var divs = document.getElementsByTagName('div');
// better to store length in variable first
var divCount = divs.length
for (var i = 0; i < divCount; i++) {
// do something with each div individually
divs[i].style.color = 'red';
}
for Loops
var divs = document.getElementsByTagName('div');
// can store it directly in the initializer
for (var i=0, divCount=divs.length; i < divCount; i++) {
// do something with each div individually
divs[i].style.color = 'red';
}
for-in Loops
var family = {
dad: 'Karl',
mom: 'Sara',
son: 'Benjamin',
daughter: 'Lucia'
}
for (var person in family) {
alert('The ' + person + ' is ' + family[person]);
}
This is your variable, so
it can be anything!
while and do-while
var i = 1;
while (i < 4) {
alert(i);
i++;
}
var j = 1;
// code block always executed at least once
do {
alert(j);
j++;
} while (j < 4)
Functions
The Basics: Functions
• Functions allow you to define a block of code, name that block, and
then call it later as many times as you want.
• function myFunction( ) { /* code goes here */ } // defining
• myFunction( ) // calling the function myFunction
• You can define functions with parameters
• function myFunction(param1, param2 ) { /* code goes here */ }
• You can call functions with arguments:
• myFunction('one', 'two')
In JavaScript, you can also work with functions:
Functions
// define a function
function doSomething() {
alert('I am something');
}
// call the function
doSomething();
Functions
// define a function
function sumThing(a, b) {
return a + b;
}
// call the function
alert( sumThing(1, 2) );
Functions
// define a function
function sumThing(a, b) {
return a + b;
}
var mySum = sumThing(1, 2);
// call the function
alert( mySum );
The arguments Object
• Every function has an arguments object
• a collection of the arguments passed to the function when
it is called
• an "array-like object" in that it is indexed and has a length
property but can't attach array methods to it
• can be looped through
• allows for variable number of arguments
Functions
// call the function
function logThing() {
for (var i=0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
// call the function
logThing(1, 2, 'three');
/* prints to the console:
>> 1
>> 2
>> three
*/
Exercise
Convert the sumThing function to allow for
variable number of arguments.
function sumThing(a, b) {
return a + b;
}
Use a for loop to loop through the arguments object, adding to a
"sum" variable with each iteration.
After the loop, return sum.
(Simple) Solution
// define a function
function sumThing() {
var sum = 0,
countArgs = arguments.length;
for (var i = 0; i < countArgs; i++) {
sum += arguments[i];
}
return sum;
}
// call the function
console.log( sumThing(1, 2, 4 ) );
function multiple(n) {
function f(x) {
return x * n;
}
return f;
}
var triple = multiple(3);
var quadruple = multiple(4);
console.log( triple(5) ); // 15
console.log( quadruple(5) ); // 20
console.log( multiple(4)(5) ); // 20
Returning Functions
• Functions can return other functions
Named vs.Anonymous
Functions
• Named:
• function foo() { } // function declaration
• var foo = function foo() { }; // function expression
• Anonymous:
• var foo = function() { }; // function expression
Anonymous Functions
• Prevalent in jQuery
• Good for creating closures
• Used as "callback" functions
• Can be used as object properties (methods)
• let’s take a look ...
$(document).ready(function() {
});
Anonymous Functions
• Prevalent in jQuery
function() {
// variables are defined within this scope
// avoid name collisions
}
Anonymous Functions
• Good for creating closures
(function() {
// variables are defined within this scope
// avoid name collisions
})();
Anonymous Functions
• Good for creating closures
• Can be defined and then immediately invoked: “immediately
invoked function expression,” ( a.k.a. IIFE; pronounced “iffy”)
(function($) { // "$" is the function's param
})(jQuery); // function is called with "jQuery"
Anonymous Functions
• Good for creating closures
• Used by plugins to keep jQuery safe.
$('p').slideDown('slow', function() {
// code in here is not executed
// until after the slideDown is finished
// jQuery calls the code in here when effect
ends
});
Anonymous Functions
• Used as "callback" functions
Objects
Objects
• Objects are objects : { }
• Arrays are objects : [ ]
• even Functions are objects : function( ) { }
• jQuery is an object
• Numbers, strings, and booleans (true/false) are primitive data
types, but they have object wrappers.
In JavaScript, everything is an object. Well, almost everything.
Global Object
• location
• parseInt(); parseFloat()
• isNaN()
• encodeURI(); decodeURI()
• setTimeout(); clearTimeout()
• setInterval(); clearInterval()
In the browser environment, the global object is window
It collects all functions and variables that are global in scope.
Usually implied.
Comes with some useful properties and methods:
Date Object
var now = new Date(); // current date and time
var then = new Date('08/12/2000 14:00');
console.log( then.getTime() ); // 966103200000
console.log( then.toString() );
// Sat Aug 12 2000 14:00:00 GMT-0400 (EDT)
console.log( then.getMonth() ); // 7 !!!!
RegExp Object
Regular Expression
• Object constructor
• var re = new RegExp('hello');
• Regular expression literal
• var re = /hello/;
Creating a RegExp
• Object constructor
• var re = new RegExp('hello');
• Regular expression literal
• var re = /hello/;
Using a RegExp
var text = 'The quick brown fox';
var re = new RegExp('quick');
console.log( re.test(text) ); // true
console.log( /brown/.test(text) ); // true
console.log( /red/.test(text) ); // false
RegExp Syntax
• Most characters (incl. all alphanumerics) represent themselves
• Special characters can be escaped with a backslash ()
Character Classes
• /t.p/ matches 'tap' and 'tip' and 'top'
• /t[ai]p/ matches 'tap' and 'tip', not 'top'
• /t[a-k]p/ matches 'tap' and 'tip', not 'top'
• /t[^m-z]p/ matches 'tap' and 'tip', not 'top'
Repetition
• /frog*/ matches 'fro', 'frog', 'frogg', ...
• /frog+/ matches 'frog', 'frogg', ...
• /frog?/ matches 'fro' or 'frog'
• /frog{2,3}/ matches 'frogg' or 'froggg'
Grouping
• Grouping
• /(frog)*/ matches "frog" or "frogfrog"
• Alternation
• /th(is|at)/ matches "this" and "that"
Anchor Points
• ^ matches the beginning of a string
• $ matches the end of a string
• b matches word boundaries
Exercises
Write a regular expression that matches any word that starts
with a vowel.
Write a regular expression that matches any HTML tag.
String RegExp Methods
• str.search(re)
• str.match(re)
• str.replace(re, replacement)
• str.split(re)
String Replacement
var str =
'The quick brown fox jumps over the lazy dog.';
console.log(str.replace(/[aeiou]/, '*'));
// Th* quick brown fox jumps over the lazy dog.
RegExp Flags
• Placed after closing / character
• Global (g): find as many as possible
• Case insensitive (i)
• Multiline (m): ^ and $ work with newlines
String Replacement
var str =
'The quick brown fox jumps over the lazy dog.';
console.log(str.replace(/[aeiou]/g, '*'));
// Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g.
console.log(str.replace(/the/gi, 'a'));
// a quick brown fox jumps over a lazy dog.
Backreferences
var str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.replace(/r(.)/g, '$1x'));
// The quick boxwn fox jumps ove xthe lazy dog.
Replacement Functions
var str = 'Kill 5+9 birds with 2+5 stones.';
function add(match, first, second) {
return parseInt(first, 10) + parseInt(second, 10);
}
str = str.replace(/([0-9]+)+([0-9]+)/g, add);
console.log(str);
// Kill 14 birds with 7 stones.
Exercises
Write a function that uppercases all the vowels in a
string.
Write a function that strips the angle brackets from
around any HTML tags in a string.
Greediness
• Repeat operators usually match as much of the string as
possible; they are greedy
• JavaScript supports reluctant repetition as well
• Append ? to the repeat operator
And Much More
• JavaScript supports most Perl regular expression extensions
• POSIX character classes
• Unicode character escapes
• Look-ahead assertions
Math Object
• Not a constructor, a singleton
• Gathers useful methods and properties
• Math.PI
• Math.abs(), Math.sin(), Math.pow(),
Math.random(),
• Math.max(), Math.min()
• Math.round(), Math.floor(), Math.ceil()
CSS:
h3 {
font-size: 1.2em;
line-height: 1;
}
JS:
var h3 = {
fontSize: '1.2em',
'line-height': 1
};
CSS Tip
• Object literal notation looks a lot like CSS style rule notation!
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
Object Literals
• person is the object
• firstName and lastName are properties
• hello is a method (a property that is a function)
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
},
interests: {
athletic: ['racquetball', 'karate', 'running'],
musical: ['rock', 'folk', 'jazz', 'classical']
}
};
Object Literals
• interests is a property and an object
Object Literals
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
} // ⬅ notice, no comma here!
};
Object Literals
“dot” notation
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
// "dot" notation
person.firstName; // 'Karl'
person.lastName; // 'Swedberg'
person.hello() // 'Hello, my name is Karl Swedberg'
Object Literals
array notation
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
// array notation
person['firstName']; // 'Karl'
person['lastName']; // 'Swedberg'
person['hello']() // 'Hello, my name is Karl Swedberg'
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
},
interests: {
athletic: ['racquetball', 'karate', 'running'],
musical: ['rock', 'folk', 'jazz', 'classical']
}
};
// person['interests']['musical'][1] == ??
// == person.interests.musical[1]
Object Literals
Object Literals
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
person.firstName = 'Karl';
var prop = 'firstName';
person[ prop ]; // 'Karl'
prop = 'lastName';
person[ prop ]; // 'Swedberg'
Object Literals
var blah;
var person = {
firstName: 'Karl',
lastName: 'Swedberg',
hello: function() {
return 'Hello, my name is ' +
this.firstName + ' ' + this.lastName;
}
};
for (var el in person) {
blah = typeof person[el] == 'function' ?
person[el]() :
person[el];
console.log( blah );
}
doSomething({
speed: 'fast',
height: 500,
width: 200,
somethingElse: 'yes'
});
doSomething({width: 300});
Object Literals
• Great as function arguments
• single argument allows flexibility when calling the function
JSON
JavaScript Object Notation
• a data interchange format. In other words, a format for passing
data back and forth
• “discovered” and popularized by Douglas Crockford
• a subset of JavaScript Object Literal Notation
• a tree-like structure of object(s) and/or array(s)
• no functions
• all strings, including object keys, take double quotes
JSON
{
"firstName": "Karl",
"lastName": "Swedberg",
"age": 24,
"interests": {
"athletic": [
"racquetball",
"karate"
]
}
}
JSON
{"firstName":"Karl","lastName":"Swedberg","age":24,"intere
sts":{"athletic":["racquetball","karate"]}}
Referencing Scripts
in the HTML
browser slides
Selectors &
Traversal
At the heart of jQuery...
• Find something
• Do something
CSS Selectors
• element {}
• #id {}
• .class {}
• selector1, selector2 {}
• ancestor descendant {}
• parent > child {}
• :nth-child() {}
CSS Selectors
• $('element')
• $('#id')
• $('.class')
• $('selector1, selector2')
• $('ancestor descendant')
• $('parent > child')
• $(':nth-child(n)')
(jQuery Equivalents)
CSS Selectors
• $('element')
• $('#id')
• $('.class')
• $('selector1, selector2')
• $('ancestor descendant')
• $('parent > child')
• $(':nth-child(n)')
(jQuery Equivalents)
• and others …
• $('prev + selector')
• $('prevAll ~
selector')$(':nth-
child(an+b')$(':not(selector)
')
• $(':checked')
• $(':disabled')
CSS Attribute Selectors
• $('input[name=firstname[]]')
• $('[title]') has the attribute
• $('[attr="val"]') attr equals val
• $('[attr!="val"]') attr does not equal val
• $('[attr~="val"]') attr has val as one of space-sep. vals
• $('[attr^="val"]') attr begins with val
• $('[attr$="val"]') attr ends with val
• $('[attr*="val"]') attr has val anywhere within
Custom Form Selectors
• $('div.myclass :checkbox')
• $(':input') <input>, <textarea>, <select>,
<button>
• $(':text') <input type="text">
• $(':radio') <input type="radio">
• $(':button') <input type="button">, <button>
• $(':selected') <option selected="selected">
• etc.
Custom Misc. Selectors
• $(':animated')
• $(':has(descendant)')
• $(':eq(n)')
• $(':lt(n)')
• $(':gt(n)')
• $(':even')
• $(':odd')
• $(':visible')
$(':hidden')$(':header')$(':
contains(string)')
Selectors
• List of all selectors on the jQuery API site
• http://api.jquery.com/category/selectors
Traversal Methods
• Move Up
• Move Sideways
• Move Down
• Filter
• Context
• Check
<ul> <li>level 1 <ul class="foo"> <li>level 2
<ul> <li class="bottom"><span>level</span>
3</li> </ul> </li> </ul> </li></ul>
Move Up
• parent() : up one level $('li.bottom').parent();
• parents() : up multiple levels $('span').parents('ul');
• parentsUntil() : possibly multiple $('span').parentsUntil('ul');
<ul> <li>level 1 <ul> <li>level 2 <ul>
<li class="bottom"><span>level</span> 3</li>
</ul> </li> </ul> </li></ul>
Move Up
• .closest(selector) : up 0 or more levels
• $('span').closest('ul');
• $('.bottom').closest('li');
Move Sideways
• .siblings()
• .next()
• .nextAll()
• .nextUntil()
• .prev()
• .prevAll()
• .prevUntil()
Move Down
• .children()
• .find()
Filter
• .filter(selector)
• .filter('.some-class')
• .filter(function)
• .filter(function() {
• return $(this).parents('li').length >=
2;
• });
Filter
• .not(selector)
• .not('.some-class')
• .not(function)
• .not(function() {
• return $(this).parents('li').length >=
2;
• });
Filter
• .slice()
• .slice(2)
• .slice(-2)
• .slice(3, 6)
• .slice(2, -1)
• .eq()
• .eq(2)
• .eq(-2)
Context
• $('selector', 'context')
• Different from "or" selector – $('selector1, selector2')
• Same as $('context').find('selector')
• Not worth using; too confusing.
• .add()
• .andSelf()
• .end()
Check
• .hasClass(class)
• .is(selector)
** returns a boolean
Traversal Methods
• List of all traversal methods on the jQuery API site
• http://api.jquery.com/category/traversing
Chaining
• JavaScript has chaining built in.
• 'swap this text'.replace(/w/, 'n').replace(/this/,'that');
• '616-555-1212'.split('-').join('.');
• jQuery takes advantage of this concept by having almost all
methods return the jQuery object.
$('a').parent('li').siblings().find('a')
Chaining
• Chain traversal methods together
$('a').removeClass('old').addClass('new');
Chaining
• Attach multiple behaviors.
$('a').addClass('foo').parent('li').removeClass('foo')
Chaining
• DOM Traversal methods are different from other jQuery chaining
methods!
• New jQuery instance is created with each one.
var lis = $('.container li:first')
.addClass('first-li')
.next()
.addClass('second-li')
.end()
.nextAll()
.addClass('not-first-li')
.end(); // unnecessary; added for symmetry
Chaining
• JavaScript ignores white space, so use it to your advantage.
$('li').removeClass('myclass'); //implicit
$('li').each(function(index) { //explicit
$(this).append( ' #' + (index+1) );
});
Looping
• Implicit Iteration
• Explicit Iteration (Looping)
$('li').each(function() {
console.log( this ); // DOM element
console.log( $(this) );
});
this Keyword
• Refers to the current object
• jQuery sets this to matched elements in the jQuery object.
var $listItems = $('li');
var numItems = $listItems.length
//no need for length check
$listItems.addClass('pretty');
if (numItems) {
// do something with other elements
}
Tips
• Store selectors used more than once in variables
• Use length property to check existence
• ...but often no need for the check
$('#menu li').each(function(index) {
$(this).click(function() {
$('#footer li:eq(' + index + ')')
.addClass('active');
});
});
Tips
• Concatenate to pass in a variable
// bad
$(':checkbox')
// better
$('input:checkbox')
// best
$('input[type="checkbox"]')
Tips
• Avoid jQuery's custom selectors when possible
// uncool
$('div:first')
// cool
$('div').first();
Tips
• Avoid jQuery's custom selectors when possible
// slower
$('li:eq(3)')
$('li:lt(3)')
// faster
$('li').eq(3)
$('li').slice(0, 3)
Tips
• Avoid jQuery's custom selectors when possible
Events
$(document).ready(function(){
//…
});
When the DOM is ready…
• Fires when the document is ready for
programming.
• Uses advanced listeners for detecting.
• window.onload() is a fallback.
// execute always
$(“div”).bind(“click”, fn);
// execute only once
$(“div”).one(“click”, fn);
Attach Event
Possible event values:
blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick,
mousedown, mouseup, mousemove, mouseover, mouseout,
mouseenter, mouseleave, change, select, submit, keydown, keypress,
keyup, error
(or any custom event)
jQuery.Event object
https://api.jquery.com/category/events/
$(“div”).unbind(“click”, fn);
Detaching Events
(Unique ID added to every attached function)
$(“div”).trigger(“click”);
Events Triggering
Triggers browser’s event action as well.
Can trigger custom events.
Triggered events bubble up.
// attach / trigger
elem.blur(fn) / elem.blur()
elem.focus(fn) / elem.focus()
elem.click(fn) / elem.click()
elem.change(fn) / elem.change()
Events Helpers
And many others…
// use different triggering function
$(“div”).triggerHandler(“click”);
Preventing Browser Default Action
// prevent default action in handler
function clickHandler(e) {
e.preventDefault();
}
// or just return false
function clickHandler(e) {return false;}
// stop bubbling, keep other handler
function clickHandler(e) {
e.stopPropagation();
}
Preventing Bubbling
// stop bubbling and other handlers
function clickHandler(e) {
e.stopImmediatePropagation();
}
// or just return false
function clickHandler(e) {return false;}
End of Lecture

More Related Content

PPTX
Awesomeness of JavaScript…almost
PDF
Performance patterns
PDF
fuser interface-development-using-jquery
KEY
#NewMeetup Performance
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
PPTX
Jquery fundamentals
KEY
Introducing the Seneca MVP framework for Node.js
KEY
20120816 nodejsdublin
Awesomeness of JavaScript…almost
Performance patterns
fuser interface-development-using-jquery
#NewMeetup Performance
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Jquery fundamentals
Introducing the Seneca MVP framework for Node.js
20120816 nodejsdublin

Similar to Lecture 03 - JQuery.pdf (20)

PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
PPTX
Building High Performance Web Applications and Sites
PPTX
SharePoint and jQuery Essentials
KEY
User Interface Development with jQuery
PPTX
the next web now
PPTX
JavaScript performance patterns
PDF
The Beauty of Java Script
PDF
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
PPTX
Html5 Overview
PDF
Becoming a better WordPress Developer
PDF
Server Side JavaScript - You ain't seen nothing yet
PPTX
BITM3730 10-4.pptx
PPT
Javascript and Jquery Best practices
KEY
Week 4 - jQuery + Ajax
PDF
The Beauty Of Java Script V5a
PPTX
JavaScript!
PDF
Django at Scale
KEY
[Coscup 2012] JavascriptMVC
KEY
Intro To JavaScript Unit Testing - Ran Mizrahi
Building High Performance Web Applications and Sites
SharePoint and jQuery Essentials
User Interface Development with jQuery
the next web now
JavaScript performance patterns
The Beauty of Java Script
jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
Html5 Overview
Becoming a better WordPress Developer
Server Side JavaScript - You ain't seen nothing yet
BITM3730 10-4.pptx
Javascript and Jquery Best practices
Week 4 - jQuery + Ajax
The Beauty Of Java Script V5a
JavaScript!
Django at Scale
[Coscup 2012] JavascriptMVC
Ad

More from Lê Thưởng (18)

PPTX
Thánh Lễ dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
PPTX
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptx
PPTX
Thánh Lễ shfdshfjadsgdahncvbczvnbcbd.pptx
PDF
dfgdfgggggggggggggggggdfffffffffffffffffffffdf
PDF
ngay hoi hom nay qua da ban da kam gi chua na
PPTX
GIÁO ÁN NGHE NÓI 4_THẦY DANH THƯỞNG.pptx
PPTX
ytyuggtkguygyogugygyuggyguygygtuytt.pptx
PDF
Lecture 01ascaccacaWsacascascsacascascWW.pdf
PDF
Lecture 05 - Creating a website with Razor Pages.pdf
PDF
Lecture 01 - WWW.pdf
PPTX
Bài 4.pptx
PPTX
Lady who sets out in haste.pptx
PPTX
mary nativity.pptx
PPTX
Presentation1.pptx
PPTX
Marial Prayer,.pptx
PPTX
Bday Prayer.pptx
PPTX
synthesis.pptx
PPT
CHƯƠNG 6- CNH,HĐH VÀ HỘI NHẬP KINH TẾ QUỐC TẾ CỦA VN.ppt
Thánh Lễ dfgdgdgdgdfgfgdgdgfgdfgddfg.pptx
Presentation1 gdfgdgdfgdfgdfgdfgdff.pptx
Thánh Lễ shfdshfjadsgdahncvbczvnbcbd.pptx
dfgdfgggggggggggggggggdfffffffffffffffffffffdf
ngay hoi hom nay qua da ban da kam gi chua na
GIÁO ÁN NGHE NÓI 4_THẦY DANH THƯỞNG.pptx
ytyuggtkguygyogugygyuggyguygygtuytt.pptx
Lecture 01ascaccacaWsacascascsacascascWW.pdf
Lecture 05 - Creating a website with Razor Pages.pdf
Lecture 01 - WWW.pdf
Bài 4.pptx
Lady who sets out in haste.pptx
mary nativity.pptx
Presentation1.pptx
Marial Prayer,.pptx
Bday Prayer.pptx
synthesis.pptx
CHƯƠNG 6- CNH,HĐH VÀ HỘI NHẬP KINH TẾ QUỐC TẾ CỦA VN.ppt
Ad

Recently uploaded (20)

PDF
Insiders guide to clinical Medicine.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Insiders guide to clinical Medicine.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Anesthesia in Laparoscopic Surgery in India
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
TR - Agricultural Crops Production NC III.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
102 student loan defaulters named and shamed – Is someone you know on the list?
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPH.pptx obstetrics and gynecology in nursing
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
human mycosis Human fungal infections are called human mycosis..pptx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf

Lecture 03 - JQuery.pdf

  • 2. Outline • Philosophy of jQuery and API Walkthrough • Dev Tools • Bare-bones JavaScript • jQuery Selectors and Traversing
  • 4. DOM Scripting •Based on web standards •Tests features, not browsers •Unobtrusive
  • 6. DOM Scripting •Verbose if (!document.getElementsByTagName) { return false; } var quotes = document.getElementsByTagName("blockquote"); for (var i=0; i<quotes.length; i++) { var source = quotes[i].getAttribute("cite"); if (source) { var link = document.createElement("a"); link.setAttribute("href",source); var text = document.createTextNode("source");//!? link.appendChild(text); var para = document.createElement("p"); para.className = "attribution"; para.appendChild(link); quotes[i].appendChild(para); } }
  • 8. Just a few of jQuery's Benefits •Lets you move quickly from beginner to advanced •Improves developer efficiency •Excellent documentation // pats self on back •Unobtrusive from the ground up •Reduces browser inconsistencies •At its core, a simple concept
  • 11. var x,y; if (self.innerHeight) { // all except Explorer x = self.innerWidth; y = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode x = document.documentElement.clientWidth; y = document.documentElement.clientHeight; } else if (document.body) { // other Explorers x = document.body.clientWidth; y = document.body.clientHeight; } DOM Scripting
  • 12. var x = $(window).width(); var y = $(window).height(); jQuery
  • 13. Documentation & Support – API: api.jquery.com – Forum: forum.jquery.com – IRC: irc.freenode.net, #jquery – Coming Soon: learn.jquery.com
  • 14. Download • Download at https://jquery.com/download/ • Or using jQuery with CDN <script src="https://code.jquery.com/jquery-3.6.0.min.js></script>
  • 15. Simple Concept • Find something • Do something
  • 17. $
  • 18. $( )
  • 22. Do Something 1. Let elements "listen" for something to happen … • the document is ready • user does something • another "listener" acts • a certain amount of time elapses
  • 23. Do Something 2. … and then do something a. Manipulate elements b. Animate elements c. Communicate with the server
  • 25. Dev Tools • up to five browsers to test against • Firefox • Chrome • Internet Explorer • Safari • Opera • developer tools can make your life much easier
  • 26. Browser Support • Modernizr • http://www.modernizr.com • Can I Use? • http://caniuse.com
  • 27. Code Sharing • jsfiddle • http://jsfiddle.net/ • jsbin • http://jsbin.com
  • 28. • TextMate • jQuery Bundle: http://github.com/kswedberg • JavaScript Tools Bundle: http://github.com/subtleGradient • Sublime Text 2 • MacVim • Espresso • jQuery Sugar: • code.google.com/p/espresso-jquery-sugar Text Editors Mac OS X
  • 29. • E • jQuery Bundle: http://github.com/kswedberg • Eclipse / Aptana • Notepad++ • Visual Studio • and so on. Text Editors Windows
  • 30. • Console • DOMViewer • JavaScript debugger • Net view • Lots of extensions http://getfirebug.com/wiki/index.php/Firebug_Extensions Firefox: Firebug
  • 31. Chrome Developer Tools • In many ways, leapfrogging Firebug • Live debugging, code changing • Lots of "hidden" goodies • http://code.google.com/chrome/devtools/ • Paul Irish screencast: http://youtu.be/nOEw9iiopwI
  • 32. • Included since Safari 3.1 • Similar to Chrome Dev Tools, but not as advanced • Activate via Preferences > Advanced Safari: Developer Menu
  • 33. • Much, much better than in previous versions. • Finally includes a console. Internet Explorer 8+: Developer Tools
  • 34. • CompanionJS: tinyurl.com/companionjs • IETester: tinyurl.com/dbtester • MS Developer Toolbar: tinyurl.com/msdevtoolbar • Script Debugger: tinyurl.com/msscriptdebug • None of them comes even close to the tools available in other browsers Internet Explorer <= 7
  • 36. The Basics • Strings: textual content. wrapped in quotation marks (single or double). • 'hello, my name is Karl' • "hello, my name is Karl" • Numbers: integer (2) or floating point (2.4) or octal (012) or hexadecimal (0xff) or exponent literal (1e+2) • Booleans: true or false In JavaScript, you can work with the following things:
  • 37. The Basics • Arrays: simple lists. indexed starting with 0 • ['Karl', 'Sara', 'Ben', 'Lucia'] • ['Karl', 2, 55] • [ ['Karl', 'Sara'], ['Ben', 'Lucia']] • Objects: lists of key, value pairs • {firstName: 'Karl', lastName: 'Swedberg'} • {parents: ['Karl', 'Sara'], kids: ['Ben', 'Lucia']} In JavaScript, you can work with the following things:
  • 38. Variables • Always declare your variables! • If you don't, they will be placed in the global scope (more about that later). • bad: myName = 'Karl'; • good: var myName = 'Karl'; • still good: var myName = 'Karl'; // more stuff myName = 'Joe';
  • 39. Variable Scoping • All var statements hoisted to top of scope function foo() { var x; x = 2; // Same as: function foo() { x= 2 var x; § Two scopes: Global and function local var globalVar; function() { var localVar; if (globalVar > 0) { var localVar2 = 2; } // localVar2 is valid here } localVar2 is hoisted here but has value undefined
  • 40. Conditionals and Operators • conditionals: • if, else • switch • operators: • +, -, *, %, ++, -- • >, <, ==, !=, >=, <=, ===, !== • !, &&, ||
  • 41. Loops • Loops iterate through a list of some kind. • A common pattern in JavaScript is to build a list, or collection, and then do something with each item in that list.
  • 42. Loops • CSS uses implicit iteration. • div { color: red; } /* applies to ALL divs */ • JavaScript relies on explicit iteration. Must explicitly loop through each div • jQuery allows for both (because it does the looping for you)
  • 43. Loops • The two most common loops... • for loops — for general-purpose iteration. Used with arrays or array-like objects) • for-in loops — used with arrays or objects (but don't use with arrays) • The other two are... • while loops • do-while loops
  • 44. for (initial value; condition; increment) { // code block } for Loops • three statements and a code block 1. initial value 2. condition 3. increment
  • 45. for Loops for (var i = 0; i < 3; i++) { alert(i+1); } This is your variable, so it can be anything! (but developers often use “i”)
  • 46. for Loops var divs = document.getElementsByTagName('div'); for (var i = 0; i < divs.length; i++) { // do something with each div individually divs[i].style.color = 'red'; }
  • 47. for Loops var divs = document.getElementsByTagName('div'); // better to store length in variable first var divCount = divs.length for (var i = 0; i < divCount; i++) { // do something with each div individually divs[i].style.color = 'red'; }
  • 48. for Loops var divs = document.getElementsByTagName('div'); // can store it directly in the initializer for (var i=0, divCount=divs.length; i < divCount; i++) { // do something with each div individually divs[i].style.color = 'red'; }
  • 49. for-in Loops var family = { dad: 'Karl', mom: 'Sara', son: 'Benjamin', daughter: 'Lucia' } for (var person in family) { alert('The ' + person + ' is ' + family[person]); } This is your variable, so it can be anything!
  • 50. while and do-while var i = 1; while (i < 4) { alert(i); i++; } var j = 1; // code block always executed at least once do { alert(j); j++; } while (j < 4)
  • 52. The Basics: Functions • Functions allow you to define a block of code, name that block, and then call it later as many times as you want. • function myFunction( ) { /* code goes here */ } // defining • myFunction( ) // calling the function myFunction • You can define functions with parameters • function myFunction(param1, param2 ) { /* code goes here */ } • You can call functions with arguments: • myFunction('one', 'two') In JavaScript, you can also work with functions:
  • 53. Functions // define a function function doSomething() { alert('I am something'); } // call the function doSomething();
  • 54. Functions // define a function function sumThing(a, b) { return a + b; } // call the function alert( sumThing(1, 2) );
  • 55. Functions // define a function function sumThing(a, b) { return a + b; } var mySum = sumThing(1, 2); // call the function alert( mySum );
  • 56. The arguments Object • Every function has an arguments object • a collection of the arguments passed to the function when it is called • an "array-like object" in that it is indexed and has a length property but can't attach array methods to it • can be looped through • allows for variable number of arguments
  • 57. Functions // call the function function logThing() { for (var i=0; i < arguments.length; i++) { console.log(arguments[i]); } } // call the function logThing(1, 2, 'three'); /* prints to the console: >> 1 >> 2 >> three */
  • 58. Exercise Convert the sumThing function to allow for variable number of arguments. function sumThing(a, b) { return a + b; } Use a for loop to loop through the arguments object, adding to a "sum" variable with each iteration. After the loop, return sum.
  • 59. (Simple) Solution // define a function function sumThing() { var sum = 0, countArgs = arguments.length; for (var i = 0; i < countArgs; i++) { sum += arguments[i]; } return sum; } // call the function console.log( sumThing(1, 2, 4 ) );
  • 60. function multiple(n) { function f(x) { return x * n; } return f; } var triple = multiple(3); var quadruple = multiple(4); console.log( triple(5) ); // 15 console.log( quadruple(5) ); // 20 console.log( multiple(4)(5) ); // 20 Returning Functions • Functions can return other functions
  • 61. Named vs.Anonymous Functions • Named: • function foo() { } // function declaration • var foo = function foo() { }; // function expression • Anonymous: • var foo = function() { }; // function expression
  • 62. Anonymous Functions • Prevalent in jQuery • Good for creating closures • Used as "callback" functions • Can be used as object properties (methods) • let’s take a look ...
  • 64. function() { // variables are defined within this scope // avoid name collisions } Anonymous Functions • Good for creating closures
  • 65. (function() { // variables are defined within this scope // avoid name collisions })(); Anonymous Functions • Good for creating closures • Can be defined and then immediately invoked: “immediately invoked function expression,” ( a.k.a. IIFE; pronounced “iffy”)
  • 66. (function($) { // "$" is the function's param })(jQuery); // function is called with "jQuery" Anonymous Functions • Good for creating closures • Used by plugins to keep jQuery safe.
  • 67. $('p').slideDown('slow', function() { // code in here is not executed // until after the slideDown is finished // jQuery calls the code in here when effect ends }); Anonymous Functions • Used as "callback" functions
  • 69. Objects • Objects are objects : { } • Arrays are objects : [ ] • even Functions are objects : function( ) { } • jQuery is an object • Numbers, strings, and booleans (true/false) are primitive data types, but they have object wrappers. In JavaScript, everything is an object. Well, almost everything.
  • 70. Global Object • location • parseInt(); parseFloat() • isNaN() • encodeURI(); decodeURI() • setTimeout(); clearTimeout() • setInterval(); clearInterval() In the browser environment, the global object is window It collects all functions and variables that are global in scope. Usually implied. Comes with some useful properties and methods:
  • 71. Date Object var now = new Date(); // current date and time var then = new Date('08/12/2000 14:00'); console.log( then.getTime() ); // 966103200000 console.log( then.toString() ); // Sat Aug 12 2000 14:00:00 GMT-0400 (EDT) console.log( then.getMonth() ); // 7 !!!!
  • 72. RegExp Object Regular Expression • Object constructor • var re = new RegExp('hello'); • Regular expression literal • var re = /hello/;
  • 73. Creating a RegExp • Object constructor • var re = new RegExp('hello'); • Regular expression literal • var re = /hello/;
  • 74. Using a RegExp var text = 'The quick brown fox'; var re = new RegExp('quick'); console.log( re.test(text) ); // true console.log( /brown/.test(text) ); // true console.log( /red/.test(text) ); // false
  • 75. RegExp Syntax • Most characters (incl. all alphanumerics) represent themselves • Special characters can be escaped with a backslash ()
  • 76. Character Classes • /t.p/ matches 'tap' and 'tip' and 'top' • /t[ai]p/ matches 'tap' and 'tip', not 'top' • /t[a-k]p/ matches 'tap' and 'tip', not 'top' • /t[^m-z]p/ matches 'tap' and 'tip', not 'top'
  • 77. Repetition • /frog*/ matches 'fro', 'frog', 'frogg', ... • /frog+/ matches 'frog', 'frogg', ... • /frog?/ matches 'fro' or 'frog' • /frog{2,3}/ matches 'frogg' or 'froggg'
  • 78. Grouping • Grouping • /(frog)*/ matches "frog" or "frogfrog" • Alternation • /th(is|at)/ matches "this" and "that"
  • 79. Anchor Points • ^ matches the beginning of a string • $ matches the end of a string • b matches word boundaries
  • 80. Exercises Write a regular expression that matches any word that starts with a vowel. Write a regular expression that matches any HTML tag.
  • 81. String RegExp Methods • str.search(re) • str.match(re) • str.replace(re, replacement) • str.split(re)
  • 82. String Replacement var str = 'The quick brown fox jumps over the lazy dog.'; console.log(str.replace(/[aeiou]/, '*')); // Th* quick brown fox jumps over the lazy dog.
  • 83. RegExp Flags • Placed after closing / character • Global (g): find as many as possible • Case insensitive (i) • Multiline (m): ^ and $ work with newlines
  • 84. String Replacement var str = 'The quick brown fox jumps over the lazy dog.'; console.log(str.replace(/[aeiou]/g, '*')); // Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g. console.log(str.replace(/the/gi, 'a')); // a quick brown fox jumps over a lazy dog.
  • 85. Backreferences var str = 'The quick brown fox jumps over the lazy dog.'; console.log(str.replace(/r(.)/g, '$1x')); // The quick boxwn fox jumps ove xthe lazy dog.
  • 86. Replacement Functions var str = 'Kill 5+9 birds with 2+5 stones.'; function add(match, first, second) { return parseInt(first, 10) + parseInt(second, 10); } str = str.replace(/([0-9]+)+([0-9]+)/g, add); console.log(str); // Kill 14 birds with 7 stones.
  • 87. Exercises Write a function that uppercases all the vowels in a string. Write a function that strips the angle brackets from around any HTML tags in a string.
  • 88. Greediness • Repeat operators usually match as much of the string as possible; they are greedy • JavaScript supports reluctant repetition as well • Append ? to the repeat operator
  • 89. And Much More • JavaScript supports most Perl regular expression extensions • POSIX character classes • Unicode character escapes • Look-ahead assertions
  • 90. Math Object • Not a constructor, a singleton • Gathers useful methods and properties • Math.PI • Math.abs(), Math.sin(), Math.pow(), Math.random(), • Math.max(), Math.min() • Math.round(), Math.floor(), Math.ceil()
  • 91. CSS: h3 { font-size: 1.2em; line-height: 1; } JS: var h3 = { fontSize: '1.2em', 'line-height': 1 }; CSS Tip • Object literal notation looks a lot like CSS style rule notation!
  • 92. var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; } }; Object Literals • person is the object • firstName and lastName are properties • hello is a method (a property that is a function)
  • 93. var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; }, interests: { athletic: ['racquetball', 'karate', 'running'], musical: ['rock', 'folk', 'jazz', 'classical'] } }; Object Literals • interests is a property and an object
  • 94. Object Literals var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; } // ⬅ notice, no comma here! };
  • 95. Object Literals “dot” notation var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; } }; // "dot" notation person.firstName; // 'Karl' person.lastName; // 'Swedberg' person.hello() // 'Hello, my name is Karl Swedberg'
  • 96. Object Literals array notation var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; } }; // array notation person['firstName']; // 'Karl' person['lastName']; // 'Swedberg' person['hello']() // 'Hello, my name is Karl Swedberg'
  • 97. var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; }, interests: { athletic: ['racquetball', 'karate', 'running'], musical: ['rock', 'folk', 'jazz', 'classical'] } }; // person['interests']['musical'][1] == ?? // == person.interests.musical[1] Object Literals
  • 98. Object Literals var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; } }; person.firstName = 'Karl'; var prop = 'firstName'; person[ prop ]; // 'Karl' prop = 'lastName'; person[ prop ]; // 'Swedberg'
  • 99. Object Literals var blah; var person = { firstName: 'Karl', lastName: 'Swedberg', hello: function() { return 'Hello, my name is ' + this.firstName + ' ' + this.lastName; } }; for (var el in person) { blah = typeof person[el] == 'function' ? person[el]() : person[el]; console.log( blah ); }
  • 100. doSomething({ speed: 'fast', height: 500, width: 200, somethingElse: 'yes' }); doSomething({width: 300}); Object Literals • Great as function arguments • single argument allows flexibility when calling the function
  • 101. JSON JavaScript Object Notation • a data interchange format. In other words, a format for passing data back and forth • “discovered” and popularized by Douglas Crockford • a subset of JavaScript Object Literal Notation • a tree-like structure of object(s) and/or array(s) • no functions • all strings, including object keys, take double quotes
  • 102. JSON { "firstName": "Karl", "lastName": "Swedberg", "age": 24, "interests": { "athletic": [ "racquetball", "karate" ] } }
  • 104. Referencing Scripts in the HTML browser slides
  • 106. At the heart of jQuery... • Find something • Do something
  • 107. CSS Selectors • element {} • #id {} • .class {} • selector1, selector2 {} • ancestor descendant {} • parent > child {} • :nth-child() {}
  • 108. CSS Selectors • $('element') • $('#id') • $('.class') • $('selector1, selector2') • $('ancestor descendant') • $('parent > child') • $(':nth-child(n)') (jQuery Equivalents)
  • 109. CSS Selectors • $('element') • $('#id') • $('.class') • $('selector1, selector2') • $('ancestor descendant') • $('parent > child') • $(':nth-child(n)') (jQuery Equivalents) • and others … • $('prev + selector') • $('prevAll ~ selector')$(':nth- child(an+b')$(':not(selector) ') • $(':checked') • $(':disabled')
  • 110. CSS Attribute Selectors • $('input[name=firstname[]]') • $('[title]') has the attribute • $('[attr="val"]') attr equals val • $('[attr!="val"]') attr does not equal val • $('[attr~="val"]') attr has val as one of space-sep. vals • $('[attr^="val"]') attr begins with val • $('[attr$="val"]') attr ends with val • $('[attr*="val"]') attr has val anywhere within
  • 111. Custom Form Selectors • $('div.myclass :checkbox') • $(':input') <input>, <textarea>, <select>, <button> • $(':text') <input type="text"> • $(':radio') <input type="radio"> • $(':button') <input type="button">, <button> • $(':selected') <option selected="selected"> • etc.
  • 112. Custom Misc. Selectors • $(':animated') • $(':has(descendant)') • $(':eq(n)') • $(':lt(n)') • $(':gt(n)') • $(':even') • $(':odd') • $(':visible') $(':hidden')$(':header')$(': contains(string)')
  • 113. Selectors • List of all selectors on the jQuery API site • http://api.jquery.com/category/selectors
  • 114. Traversal Methods • Move Up • Move Sideways • Move Down • Filter • Context • Check
  • 115. <ul> <li>level 1 <ul class="foo"> <li>level 2 <ul> <li class="bottom"><span>level</span> 3</li> </ul> </li> </ul> </li></ul> Move Up • parent() : up one level $('li.bottom').parent(); • parents() : up multiple levels $('span').parents('ul'); • parentsUntil() : possibly multiple $('span').parentsUntil('ul');
  • 116. <ul> <li>level 1 <ul> <li>level 2 <ul> <li class="bottom"><span>level</span> 3</li> </ul> </li> </ul> </li></ul> Move Up • .closest(selector) : up 0 or more levels • $('span').closest('ul'); • $('.bottom').closest('li');
  • 117. Move Sideways • .siblings() • .next() • .nextAll() • .nextUntil() • .prev() • .prevAll() • .prevUntil()
  • 119. Filter • .filter(selector) • .filter('.some-class') • .filter(function) • .filter(function() { • return $(this).parents('li').length >= 2; • });
  • 120. Filter • .not(selector) • .not('.some-class') • .not(function) • .not(function() { • return $(this).parents('li').length >= 2; • });
  • 121. Filter • .slice() • .slice(2) • .slice(-2) • .slice(3, 6) • .slice(2, -1) • .eq() • .eq(2) • .eq(-2)
  • 122. Context • $('selector', 'context') • Different from "or" selector – $('selector1, selector2') • Same as $('context').find('selector') • Not worth using; too confusing. • .add() • .andSelf() • .end()
  • 124. Traversal Methods • List of all traversal methods on the jQuery API site • http://api.jquery.com/category/traversing
  • 125. Chaining • JavaScript has chaining built in. • 'swap this text'.replace(/w/, 'n').replace(/this/,'that'); • '616-555-1212'.split('-').join('.'); • jQuery takes advantage of this concept by having almost all methods return the jQuery object.
  • 128. $('a').addClass('foo').parent('li').removeClass('foo') Chaining • DOM Traversal methods are different from other jQuery chaining methods! • New jQuery instance is created with each one.
  • 129. var lis = $('.container li:first') .addClass('first-li') .next() .addClass('second-li') .end() .nextAll() .addClass('not-first-li') .end(); // unnecessary; added for symmetry Chaining • JavaScript ignores white space, so use it to your advantage.
  • 130. $('li').removeClass('myclass'); //implicit $('li').each(function(index) { //explicit $(this).append( ' #' + (index+1) ); }); Looping • Implicit Iteration • Explicit Iteration (Looping)
  • 131. $('li').each(function() { console.log( this ); // DOM element console.log( $(this) ); }); this Keyword • Refers to the current object • jQuery sets this to matched elements in the jQuery object.
  • 132. var $listItems = $('li'); var numItems = $listItems.length //no need for length check $listItems.addClass('pretty'); if (numItems) { // do something with other elements } Tips • Store selectors used more than once in variables • Use length property to check existence • ...but often no need for the check
  • 133. $('#menu li').each(function(index) { $(this).click(function() { $('#footer li:eq(' + index + ')') .addClass('active'); }); }); Tips • Concatenate to pass in a variable
  • 134. // bad $(':checkbox') // better $('input:checkbox') // best $('input[type="checkbox"]') Tips • Avoid jQuery's custom selectors when possible
  • 135. // uncool $('div:first') // cool $('div').first(); Tips • Avoid jQuery's custom selectors when possible
  • 136. // slower $('li:eq(3)') $('li:lt(3)') // faster $('li').eq(3) $('li').slice(0, 3) Tips • Avoid jQuery's custom selectors when possible
  • 137. Events
  • 138. $(document).ready(function(){ //… }); When the DOM is ready… • Fires when the document is ready for programming. • Uses advanced listeners for detecting. • window.onload() is a fallback.
  • 139. // execute always $(“div”).bind(“click”, fn); // execute only once $(“div”).one(“click”, fn); Attach Event Possible event values: blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error (or any custom event)
  • 141. $(“div”).unbind(“click”, fn); Detaching Events (Unique ID added to every attached function)
  • 142. $(“div”).trigger(“click”); Events Triggering Triggers browser’s event action as well. Can trigger custom events. Triggered events bubble up.
  • 143. // attach / trigger elem.blur(fn) / elem.blur() elem.focus(fn) / elem.focus() elem.click(fn) / elem.click() elem.change(fn) / elem.change() Events Helpers And many others…
  • 144. // use different triggering function $(“div”).triggerHandler(“click”); Preventing Browser Default Action // prevent default action in handler function clickHandler(e) { e.preventDefault(); } // or just return false function clickHandler(e) {return false;}
  • 145. // stop bubbling, keep other handler function clickHandler(e) { e.stopPropagation(); } Preventing Bubbling // stop bubbling and other handlers function clickHandler(e) { e.stopImmediatePropagation(); } // or just return false function clickHandler(e) {return false;}