jQuery
CP 221: Internet Programming and
Applications I
What is jQuery?
jQuery is a fast and concise
JavaScript Library that simplifies
HTML document traversing, event
handling, animating, and Ajax
interactions for rapid web
development. (jQuery.com)
About jQuery
• jQuery is a JavaScript Library.
• jQuery simplifies JavaScript
programming.
• jQuery is a lightweight, "write less, do
more", JavaScript library
• The purpose of jQuery is to make it
much easier to use JavaScript on your
website.
• jQuery was originally released in January
2006 at BarCamp NYC by John Resig
Why learn jQuery?
Write less, do more:
◦$
("p.neat").addClass("ohmy").show("s
low");
Performance
Plugins
It’s
standard
… and fun!
How to use jQuery?
Download the jQuery library from
jQuery.com
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
Include jQuery from a CDN, like
Google
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/
3.3.1/jquery.min.js"></script>
</head>
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<div>
<p id="hello">Some random text</p>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js">
</script>
<script>
$(document).ready(function() {
$('#hello').text('Hello, World!');
});
</script>
</body>
</html>
jQuery Syntax
Basic syntax is: $(selector).action()
◦ A $ sign to define/access jQuery
◦ A (selector) to "query (or find)" HTML elements
◦ A jQuery action() to be performed on the element(s)
The Document Ready Event
$
(document).ready(functio $(function(){
n(){
// jQuery methods go
// jQuery methods go here...
here...
});
});
Example: Show/Hide
Button
window.onload
We cannot use the DOM before
the page has been constructed.
jQuery gives us a more
compatibile way to do this.
◦ The DOM way
window.onload = function() { // do stuff with th
◦ The direct jQuery translation
$(document).ready(function() { // do stuff with th
◦ The jQuery way
$(function() { // do stuff with the DOM })
Aspects of the DOM and
jQuery
Identification: how do I obtain a
reference to the node that I want.
Traversal: how do I move
around the DOM tree.
Node Manipulation: how do I
get or set aspects of a DOM node.
Tree Manipulation: how do I
change the structure of the page.
The DOM tree
Selecting groups of DOM
objects
name description
getElementById returns array of descendents
with the given tag, such
as "div"
getElementsByTagName returns array of descendents
with the given tag, such
as "div"
getElementsByName returns array of descendents
with the given name attribute
(mostly useful for accessing
form controls)
querySelector * returns the first element that
would be matched by the
given CSS selector string
querySelectorAll * returns an array of all
elements that would be
matched by the given CSS
selector string
jQuery / DOM comparison
DOM method jQuery equivalent
getElementById("id") $("#id")
getElementsByTagName("tag") $("tag")
getElementsByName("somena $("[name='somename']")
me")
querySelector("selector") $("selector")
querySelectorAll("selector") $("selector")
jQuery node identification
// id selector
var elem = $("#myid");
// group selector
var elems = $("#myid, p");
// context selector
var elems = $("#myid < div p");
// complex selector
var elems = $("#myid < h1.special:not(.classy)");
Exercise
Use jQuery selectors to identify elements
with these properties in a hypothetical page:
◦ All p tags that have no children, but only if they
don't have a class of ignore
◦ Any element with the text "REPLACE_ME" in it.
◦ All div tags with a child that has a class of special
◦ All heading elements (h1, h2, h3, h4, h5, h6)
◦ Every other visible li.
Use the DOM API to target the #square and
periodically change it's position in a random
direction.
Use jQuery selectors instead of the DOM API.
jQuery terminology
the jQuery function
refers to the global jQuery object or the $
function depending on the context
a jQuery object
the object returned by the jQuery function
that often represents a group of elements
selected elements
the DOM elements that you have selected
for, most likely by some CSS selector
passed to the jQuery function and possibly
later filtered further
The jQuery object
The $ function always (even for ID selectors)
returns an array-like object called a jQuery
object.
The jQuery object wraps the originally
selected DOM objects.
You can access the actual DOM object by
accessing the elements of the jQuery object.
// false
document.getElementById("id") == $("#myid");
document.querySelectorAll("p") == $("p");
// true
document.getElementById("id") == $("#myid")[0];
document.getElementById("id") == $("#myid").get(0);
document.querySelectorAll("p")[0] == $("p")[0];
Using $ as a wrapper
$ adds extra functionality to DOM
elements
passing an existing DOM object
to $ will give it the jQuery
upgrade
// convert regular DOM objects to a jQuery object
var elem = document.getElementById("myelem");
elem = $(elem);
var elems = document.querySelectorAll(".special");
elems = $(elems);
DOM context identification
You can
use querySelectorAll() and querySelector() o
n any DOM object.
When you do this, it simply searches from
that part of the DOM tree downward.
Programmatic equivalent of a CSS context
selector
var list = document.getElementsByTagName("ul")[0];
var specials = list.querySelectorAll('li.special');
find / context parameter
jQuery gives two identical ways
to do contextual element
identification
var elem = $("#myid");
// These are identical
var specials = $("li.special", elem);
var specials = elem.find("li.special");
Types of DOM nodes
<p>
This is a paragraph of text with a
<a href="/path/page.html">link in it</a>.
</p>
Traversing the DOM tree
name(s) description
start/end of this node's
firstChild, lastChild
list of children
array of all this node's
childNodes
children
nextSibling, neighboring nodes with
previousSibling the same parent
the element that
parentNode
contains this node
CS380
DOM tree traversal
example
<p id="foo">This is a paragraph of text with a
<a href="/path/to/another/page.html">link</a>.</p>
HTML
CS380
Select First P from
Id Selector Class Selector
Groups
$ $
$
(document).ready(function() (document).ready(function()
(document).ready(function()
{ {
{
$ $
$
("button").click(function(){ ("button").click(function(){
("button").click(function(){
$("#test").hide(); $(".test").hide();
$("p:first").hide();
}); });
});
}); });
});
Select First li from
Select all href Attributes
Groups Select even rows from a
$
$ Table $
(document).ready(function()
(document).ready(function() (document).ready(function()
{
{ {
$
$ $
("button").click(function(){
("button").click(function(){ ("tr:even").css("background-
$("[href]").hide();
$("ul li:first").hide(); color", "yellow");
});
}); });
});
});
jQuery Event Methods
Mouse Keyboard Form Events Document/Window
Events Events Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload
$
$
("#p1").mouseleave(function
$("p").click(function(){ ("#p1").mouseenter(functi
(){
$(this).hide(); on(){
alert("Bye! You now leave
}); alert("You entered p1!");
p1!");
});
$ });
("#p1").mouseup(function( $("input").blur(function(){ $("input").focus(function(){
){ $(this).css("background- $(this).css("background-
alert("Mouse up over color", "#ffffff"); color", "#cccccc");
p1!"); }); });
});
jQuery Effects
FadeOut & FadeIn Effect
Hide & Show Effect $("button").click(function(){
$("#hide").click(function(){ $
$("p").hide(); //.hide(1000); //.toggle(); ("#div1").fadeIn(); //.fadeOut();//.fadeTogg
}); le();
$
$("#show").click(function(){ ("#div2").fadeIn("slow"); //.fadeTo("slow",
$("p").show(); 0.5);
}); $("#div3").fadeIn(3000);
});
Slide up and Slide down Effect $("button").click(function(){
$("#flip").click(function(){ $("div").animate({
$("#panel").slideDown(); left: '250px',
}); opacity: '0.5',
height: '150px',
$("#flip").click(function(){ width: '150px'
$("#panel").slideToggle(); });
}); });
jQuery - Get & Set
$(document).ready(function(){ $(document).ready(function(){
$("#btn1").click(function(){ $("button").click(function(){
alert( $ alert( $("#test").val() );
("#test").text() ); //.text(“setting the txt”); }); //.val(“Jquery is best");
}); });
}) <p>Name:
<p id="test">This is some <b>bold</b> <input type="text" id="test"
text in a paragraph.</p> value="Mickey Mouse">
</p>
<button id="btn1">Show Text</button>
$(document).ready(function(){
$("button").click(function(){ $(document).ready(function(){
alert($("#w3s").attr("href")); $("#btn2").click(function(){
}); alert("HTML: " + $("#test").html() );
}); }); //.html("<b>Hello world!</b>");
<p><a });
href="https://www.w3schools.com" <p id="test">This is some <b>bold</b>
id="w3s">W3Schools</a></p> text in a paragraph.</p>
<button id="btn2">Show HTML</button>
<button>Show href Value</button>
jQuery - Add & Remove
$("p").append("Some appended text."); $("img").after("Some text after");
$("p").prepend("Some prepended text."); $("img").before("Some text before");
$("#div1").remove();
$("p").remove(".test");
$("#div1").empty();
$("p").remove(".test, .demo");
jQuery - CSS Manipulation
.design {
font-weight: bold;
font-size: xx-large;
} $("button").click(function(){
$("button").click(function(){ $("h2").removeClass(“design");
$("h1, h2, p").addClass("design"); });
//.addClass("important blue");
$("div").addClass(“design");
});
$("p").css("background-color", "yellow");
$("button").click(function(){ $("p").css({"background-color": "yellow",
$("p").toggleClass(“design"); "font-size": “20px"});
});
jQuery - Dimensions
jQuery has several important methods for working with dimensions:
• width()
• height()
• innerWidth()
• innerHeight()
• outerWidth()
• outerHeight()
$(document).ready(function(){
$("button").click(function(){
var msg = "";
msg += "Width of div: " + $("#div1").width() + "</br>";
msg += "Height of div: " + $("#div1").height() + "</br>";
msg += "Inner width of div: " + $("#div1").innerWidth() +
"</br>";
msg += "Inner height of div: " + $("#div1").innerHeight();
$("#div1").html(msg );
});
});
<div style=“width:300px; height:100px; background:blue;” id="div1"></div>
<button>click me </button>
jQuery tutorials
Code Academy
http://www.codecademy.com/courses/
you-and-jquery/0?curriculum_id=4fc3
018f74258b0003001f0f#!/exercises/0
Code School:
http://www.codeschool.com/courses/jq
uery-air-first-flight