Lecture # 3
Introduction to jQuery
A Quality of Life by jQuery:
$(“#firstName”).text(“Joe Black”);
$(“button”).click(function() {alert “Clicked”;});
$(“.content”).hide();
$(“#main”).load(“[Link]”);
$(“<div/>”).html(“Loading…”).appendTo(“#content”);
Very compact and fluent programming model
?What is jQuery
jQuery is a lightweight, open-source
JavaScript library that simplifies
interaction between HTML and
JavaScript
It was and still being
developed
by John Resig from
Mozilla and was first
announced in January 2006
It has a great community, great
documentation, tons of plugins, and also
adopted by Microsoft
Getting Started
Download the latest version from
[Link]
Reference it in your markup
<script src=“[Link]”/>
[Link] should contain a copy of the compressed
production code
Reference it in your JS files:
///<reference path=“[Link]”/>
… or just drag it into the file
jQuery Core Concepts
The Magic $() function
var el = $(“<div/>”)
Create HTML elements on the fly
The Magic $() function
$(window).width()
Manipulate existing DOM elements
The Magic $() function
$(“div”).hide();
Selects document elements
(more in a moment…)
The Magic $() function
$(function(){…});
Fired when the document is ready for programming.
Better use the full syntax:
$(document).ready(function(){…});
jQuery’s programming philosophy is:
GET >> ACT
$(“div”).hide()
$(“<span/>”).appendTo(“body”)
$(“:button”).click()
Almost every function returns jQuery, which
provides a fluent programming interface and
chainability:
$(“div”).show()
.addClass(“main”)
.html(“Hello jQuery”);
Three Major Concepts of jQuery
The $() function
Get > Act
Chainability
jQuery Selectors
All Selector
$(“*”) // find everything
Selectors return a pseudo-array of jQuery elements
Basic Selectors
By Tag: $(“div”)
// <div>Hello jQuery</div>
By ID: $(“#usr”)
// <span id=“usr”>John</span>
By Class: $(“.menu”)
// <ul class=“menu”>Home</ul>
Yes, jQuery implements CSS Selectors!
More Precise Selectors
$(“[Link]”) // tag and class
$(“table#data”) // tag and id
Combination of Selectors
// find by id + by class
$(“#content, .menu”)
// multiple combination
$(“h1, h2, h3, [Link]”)
Hierarchy Selectors
$(“table td”) // descendants
$(“tr > td”) // children
$(“label + input”) // next
$(“#content ~ div”) // siblings
Selection Index Filters
$(“tr:first”) // first element
$(“tr:last”) // last element
$(“tr:lt(2)”) // index less than
$(“tr:gt(2)”) // index gr. than
$(“tr:eq(2)”) // index equals
Visibility Filters
$(“div:visible”) // if visible
$(“div:hidden”) // if not
Attribute Filters
$(“div[id]”) // has attribute
$(“div[dir=‘rtl’]”) // equals to
$(“div[id^=‘main’]”) // starts with
$(“div[id$=‘name’]”) // ends with
$(“a[href*=‘msdn’]”) // contains
Forms Selectors
$(“input:checkbox”) // checkboxes
$(“input:radio”) // radio buttons
$(“:button”) // buttons
$(“:text”) // text inputs
Forms Filters
$(“input:checked”) // checked
$(“input:selected”) // selected
$(“input:enabled”) // enabled
$(“input:disabled”) // disabled
Find Dropdown Selected Item
<select id=“cities”>
<option value=“1”>Tel-Aviv</option>
<option value=“2” selected=“selected”>Yavne</option>
<option value=“3”>Raanana</option>
</select>
$(“#cities option:selected”).val()
$(“#cities option:selected”).text()
SELECTORS DEMO
Document Traversal
A Selector returns a pseudo array of
jQuery objects
$(“div”).length
Returns number of selected elements.
It is the best way to check selector.
Getting a specific DOM element
$(“div”).get(2) or $(“div”)[2]
Returns a 2nd DOM element of the selection
Getting a specific jQuery element
$(“div”).eq(2)
Returns a 2nd jQuery element of the selection
each(fn) traverses every selected element
calling fn()
var sum = 0;
$(“[Link]”).each(
function(){
sum += (+[Link]);
});
this – is a current DOM element
each(fn) also passes an indexer
$(“table tr”).each(
function(i){
if (i % 2)
$(this).addClass(“odd”);
});
$(this) – convert DOM to jQuery
i - index of the current element
Traversing HTML
.next(expr) // next sibling
.prev(expr) // previous sibling
.siblings(expr) // siblings
.children(expr) // children
.parent(expr) // parent
Check for expression
$(“table td”).each(function() {
if ($(this).is(“:first-child”)) {
$(this).addClass(“firstCol”);
}
});
Find in selected
// select paragraph and then find
// elements with class ‘header’ inside
$(“p”).find(“.header”).show();
// equivalent to:
$(“.header”, $(“p”)).show();
Advanced Chaining
$(“<li><span></span></li>”) // li
.find(“span”) // span
.html(“About Us”) // span
.andSelf() // span, li
.addClass(“menu”) // span,li
.end() // span
.end() // li
.appendTo(“[Link]-menu”);
Get Part of Selected Result
$(“div”)
.slice(2, 5)
.not(“.green”)
.addClass(“middle”);
HTML Manipulation
Getting and Setting Inner Content
$(“p”).html(“<div>Hello $!</div>”);
// escape the content of div.b
$(“div.a”).text($(“div.b”).html());
Getting and Setting Values
// get the value of the checked checkbox
$(“input:checkbox:checked”).val();
// set the value of the textbox
$(“:text[name=‘txt’]”).val(“Hello”);
// select or check lists or checkboxes
$(“#lst”).val([“NY”,”IL”,”NS”]);
Handling CSS Classes
// add and remove class
$(“p”).removeClass(“blue”).addClass(“red”);
// add if absent, remove otherwise
$(“div”).toggleClass(“main”);
// test for class existance
if ($(“div”).hasClass(“main”)) { //… }
Inserting new Elements
// select > append to the end
$(“h1”).append(“<li>Hello $!</li>”);
// select > append to the beginning
$(“ul”).prepend(“<li>Hello $!</li>”);
// create > append/prepend to selector
$(“<li/>”).html(“9”).appendTo(“ul”);
$(“<li/>”).html(“1”).prependTo(“ul”);
Replacing Elements
// select > replace
$(“h1”).replaceWith(“<div>Hello</div>”);
// create > replace selection
$(“<div>Hello</div>”).replaceAll(“h1”);
Replacing Elements while keeping the
content
$(“h3”).each(function(){
$(this).replaceWith(“<div>”
+ $(this).html()
+ ”</div>”);
});
Deleting Elements
// remove all children
$(“#mainContent”).empty();
// remove selection
$(“[Link]”).remove();
// change position
$(“p”).remove(“:not(.red)”)
.appendTo(“#main”);
Handling attributes
$(“a”).attr(“href”,”[Link]”);
// <a href=“[Link]”>…</a>
// set the same as the first one
$(“button:gt(0)”).attr(“disabled”,
$(“button:eq(0)”).attr(“disabled));
// remove attribute - enable
$(“button”).removeAttr(“disabled”)
Setting multiple attributes
$(“img”).attr({
“src” : “/images/[Link]”,
“alt” : “Smile”,
“width” : 10,
“height” : 10
});
CSS Manipulations
// get style
$(“div”).css(“background-color”);
// set style
$(“div”).css(“float”, “left”);
// set multiple style properties
$(“div”).css({“color”:”blue”,
“padding”: “1em”
“margin-right”: “0”,
marginLeft: “10px”});
Dimensions
// get window height
var winHeight = $(window).height();
// set element height
$(“#main”).height(winHeight);
//.width() – element
//.innerWidth() – .width() + padding
//.outerWidth() – .innerWidth() + border
//.outerWidth(true) – including margin
The default unit is Pixel (px)
Positioning
// from the document
$(“div”).offset().top;
// from the parent element
$(“div”).position().left;
// scrolling position
$(window).scrollTop();
Events
When the DOM is ready…
$(document).ready(function(){
//…
});
Fires when the document is ready for
programming.
Uses advanced listeners for detecting.
[Link]() is a callback.
Attach Event
// execute always
$(“div”).bind(“click”, fn);
// execute only once
$(“div”).one(“click”, fn);
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)
[Link] object
Detaching Events
$(“div”).unbind(“click”, fn);
(Unique ID added to every attached function)
Events Triggering
$(“div”).trigger(“click”);
Triggers browser’s event action as well.
Can trigger custom events.
Triggered events bubble up.
Events Helpers
// attach / trigger
[Link](fn) / [Link]()
[Link](fn) / [Link]()
[Link](fn) / [Link]()
[Link](fn) / [Link]()
And many others…
Preventing Browser Default Action
// use different triggering function
$(“div”).triggerHandler(“click”);
// prevent default action in handler
function clickHandler(e) {
[Link]();
}
// or just return false
function clickHandler(e) {return false;}
Preventing Bubbling
// stop bubbling, keep other handler
function clickHandler(e) {
[Link]();
}
// stop bubbling and other handlers
function clickHandler(e) {
[Link]();
}
// or just return false
function clickHandler(e) {return false;}
Live Events
// attach live event
(“div”).live(“click”, fn);
// detach live event
(“div”).die(“click”, fn);
Currently supported events:
click, dblclick, mousedown, mouseup, mousemove,
mouseover, mouseout, keydown, keypress, keyup
EVENTS DEMO
Effects
Showing or Hiding Element
// just show
$(“div”).show();
// reveal slowly, slow=600ms
$(“div”).show(“slow”);
// hide fast, fast=200ms
$(“div”).hide(“fast”);
// hide or show in 100ms $
(“div”).toggle(100);
Sliding Elements
$(“div”).slideUp();
$(“div”).slideDown(“fast”);
$(“div”).slideToggle(1000);
Fading Elements
$(“div”).fadeIn(“fast”);
$(“div”).fadeOut(“normal”);
// fade to a custom opacity
$(“div”).fadeTo (“fast”, 0.5);
Fading === changing opacity
Detecting animation completion
$(“div”).hide(“slow”, function() {
alert(“The DIV is hidden”);
});
$(“div”).show(“fast”, function() {
$(this).html(“Hello jQuery”);
}); // this is a current DOM element
Every effect function has a (speed, callback)
overload
Custom Animation
// .animate(options, duration)
$(“div”).animate({
width: “90%”,
opacity: 0.5,
borderWidth: “5px”
}, 1000);
Chaining Animation
$(“div”).animate({width: “90%”},100)
.animate({opacity: 0.5},200)
.animate({borderWidth: “5px”});
By default animations are queued and than
performed one by one
Controlling Animations Sync
$(“div”)
.animate({width: “90%”},
{queue:false, duration:1000})
.animate({opacity : 0.5});
The first animation will be performed immediately
without queuing
EFFECTS DEMO
AJAX with jQuery
Loading content
$(“div”).load(“[Link]”);
// passing parameters
$(“#content”).load(“[Link]”,
{“id”:”33”,
“type”:”main”});
Sending GET/POST requests
$.get(“[Link]”, {id:1},
function(data){alert(data);});
$.post(“[Link]”, {id:1},
function(data){alert(data);});
Retrieving JSON Data
$.getJSON(“[Link]”, {id:1},
function(users)
{
alert(users[0].name);
});
Retrieving JS Files
$.getScript(“[Link]”,
function()
{
doSomeFunction();
});
AJAX DEMO
Extending the Library
Adding Methods
// definition
[Link] = function(s) {
return jQuery(this).each(function() {
[Link](“<div>”+ s +“</div>”);
});
};
// usage
$(“#log”).printLine(“Hello”);
Do not use $ in the method
(at least not until next slide)
Closure to solve the $ issue
(function ($) {
[Link] = function(s) {
return $(this).each(function() {
[Link](“<div>”+ s +“</div>”);
});
};
})(jQuery);
Custom Selectors
$.expr[‘:’].test = function(o, i, m, s) {
// o – current object in the selection
// i – loop index in the stack
// m – meta data about your selector
// s – stack of all the elements
// return true to include the element
// return false to exclude the element
};
LIBRARY EXTENSION DEMO
More things to explore
More Functionality on every aspect
URL parameters parser
Browser and features detection
Data Cache
Utilities Helper functions
Various Plug-ins
Where to go next
jQuery web-site: [Link]
jQuery API: [Link]
Many many blogs
jQuery in Action book: