jQuery
10/21
Today
jQuery
Some cool tools around the web
JavaScript Libraries
Drawing libraries
HTML Frameworks
Conventions
JavaScript in the Real World
You need to make sure your code works on all browsers.
Some very popular browsers don’t implement basic things
according to a standard.
Therefore, you often need to have special cases for basic
things like event handling.
Why People Use Libraries…
People use JavaScript libraries to avoid needing to take care
of all these special cases themselves.
Libraries handle different browser cases so you don’t have to.
jQuery
One of the most popular JavaScript libraries.
If you don’t use it, you will at least need to deal with it.
What it does.
Allows you to easily select HTML elements
Allows you to manipulate these elements, define event handlers,
do animation, and do AJAX calls more easily
Getting jQuery
Download the JavaScript library from http://jquery.com
Can also use hosted locations like Google Library API
http://code.google.com/apis/libraries/
Also links you to some of the most popular JavaScript libraries.
Things jQuery can do
1. Make it easy to run a function when your page loads.
2. Select a bunch of DOM elements and do something with
them
3. Handle events
4. Do AJAX calls easily
1. Run something when the page
loads
There are 4 overloads total, I will only discuss 2 today.
jQuery(function (){…}):
function passed in gets executed when the DOM loads.
Equivalent to calling document.ready(); which is when all the
DOM elements have loaded (but not necessarily all images).
similar to window.onload = function() {…} except
window.onload waits for images to load too.
Loading example…
Pop up an alert saying “hello, world!” once the
document loads.
$(document).ready(function() {
alert("hello world");
});
OR
$(function(){
alert("hello, world!");
});
OR
function helloWorld() {
alert("hello world");
}
$(helloWorld);
2. Select a bunch of DOM elements
and do something with them
jQuery has a focus on queries:
You do a query to get a list of objects back (jQuery objects).
You can then do interesting things with these objects.
jQuery defines one global function: jQuery()
So commonly used that jQuery defines a global symbol, $ for it.
jQuery Basics
jQuery() function (or, $()) is ‘overloaded’
Remember when I said JavaScript doesn’t support overloading?
Well, you can write overloading yourself by checking your
parameters.
Most basic parameter to $(): string representing a “css selector”
A “CSS Selector” is a string (query) which
selects some subset of elements in your DOM.
For example, $("div") gets all divs,
$(".className") gets all elements whose class is
className.
jQuery example
For loop that turns all h1 elements red
var h1s = $("h1");
for (var i = 0; i < h1s.length; i++) {
h1s[i].style.color="red";
}
css()
css() allows you to either get the css properties of an element
or set the css properties of an element.
Method is overloaded by checking for existence of variables.
Setting the text color of element with myId to red:
$("#myId").css({color: "red"});
If multiple elements returned, executes on all elements found.
Returns list of modified elements (chainable!)
css()
Getting the text color of element with id “myId”:
$(“#myId”).css(“color”);
If multiple elements returned, executes on first element found.
Does not return a list (terminates your chain).
Setting the text color of element with id “myId” red:
$(“#myId”).css({color: “red”});
More Useful CSS Functions
Add a CSS class to an element:
$("#myId").addClass("myClassName");
Toggle a CSS class:
If element has the class, remove it. If it doesn’t have the class,
add it.
$("#myId").toggleClass("highlight");
More at http://api.jquery.com/category/css/
Getting/Setting HTML Content
text() gets/sets the inner text of an element and its children.
html() gets/sets the inner HTML of an element and its children.
Example: Get the text of the first h1 element:
$(“h1”).text();
Example: Set the text of each h1 element to be “foobar”
$(“h1”).text(“foobar”);
Example: Add section numbers to each header element
$(“h1”).text(function(n, current){
return “section “ + (n+1) + “: “ + current
});
Getting/Setting Element
Position
offset() gets/sets the position of an element relative to the entire
document.
position() gets/sets the position of an element relative to its
parent.
Example: scroll all elements with class “scrolling” left to right:
function scrollText(){
$(".scrolling").offset(function(index, curpos){
return {
left: (curpos.left + 5) % $(window).width(),
top: (curpos.top)
};
});
setTimeout(scrollText, 30);
}
data()
Allows you to associate data with any jQuery object (i.e.
object that’s a result of a query).
Example: set some data for all div elements:
$("div").data("x",5);
Example: query data:
$("div").data("x"): get “x” property
$("div").data(): return object with all properties.
Manipulating Document
Structure
Methods that add/remove elements to your HTML
document.
You can either pass in Element objects or HTML strings.
$("#myId").append(document.createElement("h
r"));
Adds an <hr> element at end of element with id myId
$("#myId").after("<hr />")
Inserts an <hr> element directly after element with id myId.
Method Chaining Example
Most jQuery methods operate on a list of objects, then return
the modified list.
This allows you to chain methods, i.e. do multiple things on one
line
Example:
Set text color of all h1 elements to green and add an hr element
before and after these elements:
Method Chaining Example
Most jQuery methods operate on a list of objects, then return
the modified list.
This allows you to chain methods, i.e. do multiple things on one
line
Example:
Set text color of all h1 elements to green and add an hr element
before and after these elements:
$(“h1”).css({color: “green”}).before(“<hr />”).after(“<hr />”);
Method chaining explained
$(“h1”).css({color: “green”}).before(“<hr />”).after(“<hr />”);
Method chaining explained
$(“h1”).css({color: “green”}).before(“<hr />”).after(“<hr />”);
<h1>
<h1>
<h1>
Method chaining explained
$(“h1”).css({color: “green”}).before(“<hr />”).after(“<hr />”);
<h1>
<h1>
<h1>
<h1>
<h1>
<h1>
Method chaining explained
$(“h1”).css({color: “green”}).before(“<hr />”).after(“<hr />”);
<h1>
<h1>
<h1>
<h1>
<h1>
<h1>
<hr/>
<h1>
<hr/>
<h1>
<hr/>
<h1>
Method chaining explained
$(“h1”).css({color: “green”}).before(“<hr />”).after(“<hr />”);
<h1>
<h1>
<h1>
<h1>
<h1>
<h1>
<hr/>
<h1>
<hr/>
<h1>
<hr/>
<h1>
<hr/>
<h1>
<hr/>
<hr/>
<h1>
<hr/>
<hr/>
<h1>
<hr/>
end result
3. Event Handlers in jQuery
Event handling is especially annoying because IE implements
a different event API than other browsers.
Instead of addEventListener, uses attachEvent
Makes it a big pain to do event handling cross-browser.
jQuery makes it much easier for us to do event handling.
Event Registration in JQuery
Example: clicking on <p> element toggles its background
color.
Define class “highlighted” to have a grey background color.
$("p").on("click", function(){
$(this).toggleClass("highlighted");
})
Event Registration Details
jQuery does pass in parameters to the event handler
First argument is the event object, contains info about the event.
Stuff like target, clientX, etc.
For more information:
http://api.jquery.com/category/events/event-object/
Return value of your event handler is important:
If it returns false the default action of event and any future
propagation are canceled
Types of events handlers
scroll()
click()
change()
dblclick()
focus()
hover()
keypress()
load()
Many more at http://api.jquery.com/category/events/
Event Handler example
Useful debugging blurb that shows you the position of your
mouse relative to the window.
Animations in jQuery
jQuery has pretty powerful animation framework which
allows you to smoothly change css properties of DOM
elements.
Animations add polish to your site.
Examples of animations:
http://api.jquery.com/fadeIn/
Animation Basics
Every function has a duration that says how long the effect
should last for.
Specify in ms or a string. “fast”, “slow”.
Animations are asynchronous.
Can specify a second parameter to your animation: the function
to execute when your animation is complete.
Basic Visual Effects
fadeIn(speed, callback):
$("div").fadeIn(); fades in all divs.
$("div").fadeIn("fast"); fades in all divs fast.
fadeOut(speed, callback)
fadeTo({fade options such as opacity to fade to}, speed,
callback);
Basic Visual Effects
hide():
Animates width and height to 0
show():
Animates width and height from 0
Toggle()
Toggles between show and hide.
Queueing Animations
You can execute one animation after another by doing:
$("#myElement").fadeIn().fadeOut();
Custom Animations
Use animate() to specify custom animation of css styles.
$("img").animate({height: 0}, {duration:
"fast", complete: function(){…})) quickly
animates all images to have a height of 0 and executes a
specified function on completion.
The first parameter specifies what properties you should
animate to.
The second parameter (function object) is optional.
Stopping and Delaying
Animations
Some people find animations jarring.
jQuery.fx.off = true disables all jQuery animations.
To stop a current element from animating, you can use
stop(). This stops the current element from animating.
You can also use delay(ms) to delay animations
Example
Fading images on mouseover
$("img").mouseover(function(){
$(this).stop().fadeTo(300, 1.0);
};
$("img").mouseout(function(){
$(this).stop().fadeTo(300, 0.5);
}
Example taken from JavaScript: the definitive guide by David Flanagan
Example
Fading images on mouseover
$("img").mouseover(function(){
$(this).stop().fadeTo(300, 1.0);
};
$("img").mouseout(function(){
$(this).stop().fadeTo(300, 0.5);
}
Example taken from JavaScript: the definitive guide by David Flanagan
4. AJAX calls
getting or saving data from servers somewhere
not getting into it in this class but check out $.ajax, $.get,
$.post if you're interested.
Shout out to other useful
JavaScript Libraries
UnderscoreJS
jQuery
PrototypeJS
MooTools
UI Frameworks
jQuery UI
jQuery Mobile
Bootstrap
YUI
MVC Framework Tools
AngularJS
Backbone
Drawing Libraries
Raphaël
ProcessingJS
PaperJS
Web Effects
http://acko.net/blog/this-is-your-brain-on-css/
http://www.nike.com/jumpman23/aj2012/
http://www.inception-explained.com/
© Copyright 2026 Paperzz