Jquery 170413145400
Jquery 170413145400
Jquery 170413145400
INTRODUCTION
•jQuery is an Open-Source JavaScript framework that
simplifies cross-browser client side scripting.
• Animations
• DOM manipulation
• AJAX
Tip: In addition, jQuery has plugins for almost any task out
there.
ADDING JQUERY TO YOUR
WEB PAGES
$(document).ready(function(){
$
$()
$(‘div’)
$(‘#id’)
DO SOMETHING
$('element')
$('#id')
$('.class')
$('selector1, selector2')
$('ancestor descendant')
$('parent > child')
$(':nth-child(n)')
CSS SELECTORS
(jQuery Equivalents)
Example
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
SYNTAX
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the
hiding/showing, and can take the following values:
"slow", "fast", or milliseconds.
The optional callback parameter is a function to be
executed after the hide() or show() method completes
JQUERY TOGGLE()
With jQuery, you can toggle between the hide() and
show() methods with the toggle() method.
Example
$("button").click(function(){
$("p").toggle();
});
SYNTAX
$(selector).toggle(speed,callback);
The optional speed parameter can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be
executed after toggle() completes.
JQUERY EFFECTS - FADING
With jQuery you can fade elements in and out of
visibility.
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
JQUERY FADEOUT() METHOD
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
JQUERY FADETOGGLE()
METHOD
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
JQUERY FADETO() METHOD
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
JQUERY EFFECTS - SLIDING
$("#flip").click(function(){
$("#panel").slideDown();
});
JQUERY SLIDEUP() METHOD
The jQuery slideUp() method is used to slide up an
element.
Syntax:
$(selector).slideUp(speed,callback);
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the sliding completes.
EXAMPLE
$("#flip").click(function(){
$("#panel").slideUp();
});
JQUERY SLIDETOGGLE()
METHOD
$("#flip").click(function(){
$("#panel").slideToggle();
});
JQUERY EFFECTS -
ANIMATION
jQuery Animations - The animate() Method
The jQuery animate() method is used to create custom
animations.
Syntax:
$(selector).animate({params},speed,callback);
The required params parameter defines the CSS
properties to be animated.
The optional speed parameter specifies the duration of
the effect. It can take the following values: "slow", "fast",
or milliseconds.
The optional callback parameter is a function to be
executed after the animation completes.
EXAMPLE
$("button").click(function(){
$("div").animate({left: '250px'});
});
$("button").click(function(){
var div = $("div");
div.animate({height: '300px', opacity: '0.4'}, "slow");
div.animate({width: '300px', opacity: '0.8'}, "slow");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "slow");
});
JQUERY STOP ANIMATIONS
The jQuery stop() method is used to stop an animation or
effect before it is finished.
The stop() method works for all jQuery effect functions,
including sliding, fading and custom animations.
Syntax:
$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the
animation queue should be cleared or not. Default is false,
which means that only the active animation will be stopped,
allowing any queued animations to be performed
afterwards.
The optional goToEnd parameter specifies whether or not to
complete the current animation immediately. Default is
false.
So, by default, the stop() method kills the current animation
being performed on the selected element.
EXAMPLE
$("#stop").click(function(){
$("#panel").stop();
});
A callback function is executed after the current effect is
100% finished.
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
EXAMPLE WITHOUT
CALLBACK
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
JQUERY - CHAINING
$("#p1").css("color", "red").slideUp(2000).slideDown(2000
);
When chaining, the line of code could become quite long.
However, jQuery is not very strict on the syntax; you can
format it like you want, including line breaks and
indentations.
This also works just fine:
Example
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
GET CONTENT AND
ATTRIBUTES
JQuery contains powerful methods for changing and
manipulating HTML elements and attributes.
DOM Manipulation:
One very important part of jQuery is the possibility to
manipulate the DOM.
JQuery comes with a bunch of DOM related methods that
make it easy to access and manipulate elements and
attributes.
TEXT(), HTML(), AND VAL()
Three simple, but useful, jQuery methods for DOM
manipulation are:
text() - Sets or returns the text content of selected
elements
html() - Sets or returns the content of selected elements
(including HTML markup)
val() - Sets or returns the value of form fields
GET ATTRIBUTES - ATTR()
The JQuery attr() method is used to get
attribute values.
Example:
$("button").click(function(){
alert($("#w3s").attr("href"));
});
SET CONTENT AND
ATTRIBUTES
Set Content - text(), html(), and val():
We will use the same three methods from the
previous page to set content.
Example:
$("p").append("Some appended text.");
Example:
$("img").after("Some text after");
Example:
function afterText()
{
var txt1 = "<b>I </b>";
var txt2 = $("<i></i>").text("love ");
var txt3 = document.createElement("b");
txt3.innerHTML = "jQuery!";
$("img").after(txt1, txt2, txt3);
<img>
}
JQuery - Remove Elements:
With jQuery, it is easy to remove existing HTML
elements.
Remove Elements/Content:
To remove elements and content, there are mainly two
jQuery methods.
remove() - Removes the selected element (and its child
elements)
empty() - Removes the child elements from the selected
element
Example:
$("p").remove(".test");
JQUERY - GET AND SET CSS CLASSES
With JQuery, it is easy to manipulate the CSS of elements.
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
JQuery css() Method:
The css() method sets or returns one or more style
properties for the selected elements.
Return a CSS Property:
To return the value of a specified CSS property, use
the following syntax:
css("propertyname");
Example:
$("p").css("background-color");
Set a CSS Property:
To set a specified CSS property, use the following syntax:
Syntax:
css("propertyname","value");
Set Multiple CSS Properties:
To set multiple CSS properties, use the following syntax:
Syntax:
css({"propertyname":"value","propertyname":"value",...});
Example:
$("p").css({"background-color": "yellow", "font-
size": "200%"});
JQuery - Dimensions
Example:
$("button").click(function()
{
var txt = "";
txt += "Width: " + $("#div1").width() + "</br>";
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
JQuery innerWidth() and innerHeight() Methods:
The innerWidth() method returns the width of an element
(includes padding).
The innerHeight() method returns the height of an
element (includes padding).
Example:
$("button").click(function()
{
var txt = "";
txt += "Inner width: " + $("#div1").innerWidth()
+ "</br>";
txt += "Inner height: " + $("#div1").innerHeight();
$("#div1").html(txt);
});
JQuery outerWidth() and outerHeight() Methods:
The outerWidth() method returns the width of an element
(includes padding and border).
The outerHeight() method returns the height of an element
(includes padding and border).
Example:
$("button").click(function()
{
var txt = "";
txt += "Outer width: " + $("#div1").outerWidth()
+ "</br>";
txt += "Outer height: " + $("#div1").outerHeight();
$("#div1").html(txt);
});
Note: The outerWidth(true) method returns the width of an
element (includes padding, border, and margin).
The outerHeight(true) method returns the height of an
element (includes padding, border, and margin).
JQuery More width() and height():
It returns the width and height of the document (the
HTML document) and window (the browser viewport).
Example:
$("button").click(function()
{
var txt = "";
txt += "Document width/height: " +
$(document).width();
txt += "x" + $(document).height() + "\n";
txt += "Window width/height: " + $(window).width();
txt += "x" + $(window).height();
alert(txt);
});
JQUERY TRAVERSING
Traversing:
JQuery traversing, which means "move through", are used
to "find" HTML elements based on their relation to other
elements.
Start with one selection and move through that selection
until you reach the elements you desire.
The image below illustrates a family tree.
With JQuery traversing, We can easily move up, down
and sideways in the family tree, starting from the
selected element.
This movement is called traversing - or moving through
- the DOM.
An ancestor is a parent, grandparent, great-grandparent,
and so on.
A descendant is a child, grandchild, great-grandchild,
and so on.
Siblings share the same parent.
Traversing the DOM:
JQuery provides a variety of methods that
allows us to traverse the DOM.
The largest category of traversal methods are
tree-traversal.
The next chapters will show us how to travel
up, down and sideways in the DOM tree.
JQUERY TRAVERSING - ANCESTORS:
An ancestor is a parent, grandparent, great-grandparent,
and so on.
With jQuery you can traverse up the DOM tree to find
ancestors of an element.
Example:
$(document).ready(function()
{
$("span").parentsUntil("div");
});
Example returns all ancestor elements
between a <span> and a <div> element
JQuery Traversing - Descendants:
A descendant is a child, grandchild, great-
grandchild, and so on.
With jQuery you can traverse down the DOM tree to
find descendants of an element.
Example:
$(document).ready(function()
{
$("h2").siblings();
});
JQuery next() Method:
The next() method returns the next sibling element of
the selected element.
It returns the next sibling of <h2>
Example:
$(document).ready(function(){
$("h2").next();
});
JQuery nextAll() Method:
The nextAll() method returns all next sibling
elements of the selected element.
Example:
$(document).ready(function()
{
$("h2").nextAll();
});
JQuery nextUntil() Method:
The nextUntil() method returns all next sibling
elements between two given arguments.
Example:
$(document).ready(function()
{
$("h2").nextUntil("h6");
});
JQuery prev(), prevAll() & prevUntil() Methods:
The prev(), prevAll() and prevUntil() methods work
just like the methods above but with reverse
functionality.
They return previous sibling elements (traverse
backwards along sibling elements in the DOM tree,
instead of forward).
JQUERY TRAVERSING -
FILTERING
Narrow Down The Search For Elements
The three most basic filtering methods are
first(), last() and eq(), which allow you to select
a specific element based on its position in a
group of elements.
Other filtering methods, like filter() and not()
allow you to select elements that match, or do
not match, a certain criteria.
JQUERY FIRST() METHOD
The first() method returns the first element of the
selected elements.
The following example selects the first <p> element
inside the first <div> element:
Example
$(document).ready(function(){
$("div p").first();
});
JQUERY LAST() METHOD
The last() method returns the last element of the selected
elements.
The following example selects the last <p> element
inside the last <div> element:
Example
$(document).ready(function(){
$("div p").last();
});
JQUERY EQ() METHOD
The eq() method returns an element with a
specific index number of the selected elements.
The index numbers start at 0, so the first
element will have the index number 0 and not
1. The following example selects the second
<p> element (index number 1):
Example
$(document).ready(function(){
$("p").eq(1);
});
JQUERY FILTER() METHOD
The filter() method lets you specify a criteria.
Elements that do not match the criteria are
removed from the selection, and those that
match will be returned.
The following example returns all <p>
elements with class name "intro":
Example
$(document).ready(function(){
$("p").filter(".intro");
});
FILTER
.filter(selector)
.filter('.some-class')
.filter(function)
.filter(function() {
return $(this).parents('li').length >= 2;
});
JQUERY NOT() METHOD
The not() method returns all elements that do not match
the criteria.
Tip: The not() method is the opposite of filter().
The following example returns all <p> elements that do
not have class name "intro":
Example
$(document).ready(function(){
$("p").not(".intro");
});
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)
TRAVERSAL METHODS
List of all traversal methods on the jQuery API site
http://api.jquery.com/category/traversing
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
CHAINING
JavaScript has chaining built in.
'swap this text'.replace(/w/, 'n').replace(/this/,'that');
'616-555-1212'.split('-').join('.');
$('a').parent('li').siblings().find('a')
CHAINING
Attach multiple behaviors.
$('a').removeClass('old').addClass('new');
CHAINING
DOM Traversal methods are different from other jQuery
chaining methods!
New jQuery instance is created with each one.
$('a').addClass('foo').parent('li').removeClass('foo')
CHAINING
JavaScript ignores white space, so use it to your advantage.
$('li').each(function() {
console.log( this ); // DOM element
console.log( $(this) );
});
TIPS
Store selectors used more than once in variables
Use length property to check existence
...but often no need for the check
if (numItems) {
// do something with other elements
}
TIPS
Concatenate to pass in a variable
$('#menu li').each(function(index) {
$(this).click(function() {
$('#footer li:eq(' + index + ')')
.addClass('active');
});
});
TIPS
Avoid jQuery's custom selectors when possible
// bad
$(':checkbox')
// better
$('input:checkbox')
// best
$('input[type="checkbox"]')
TIPS
Avoid jQuery's custom selectors when possible
// uncool
$('div:first')
// cool
$('div').first();
THE BASICS
In JavaScript, you can work with the following things:
Strings: textual content. wrapped in quotation marks
(single or double).
'hello, my name is Karl'
"hello, my name is Karl"
va r d ivs =
d o cu m en t.getElementsByTagName('div');
console.log( triple(5) ); // 15
console.log( quadruple(5) ); // 20
console.log( multiple(4)(5) ); // 20
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)
$(document).ready(function() {
});
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() {
// variables are defined within this scope
// avoid name collisions
})();
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
});
OBJECTS
In JavaScript, everything is an object. Well, almost everything.
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.
GLOBAL OBJECT
In the browser environment, the global object is window
It collects all functions and variables that are global in scope.
Usually implied.
console.log( then.toString() );
// Sat Aug 12 2000 14:00:00 GMT-0400 (EDT)
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';
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 =
console.log(str.replace(/[aeiou]/, '*'));
console.log(str.replace(/[aeiou]/g, '*'));
console.log(str.replace(/the/gi, 'a'));
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.';
Math.max(), Math.min()
JS:
var h3 = {
fontSize: '1.2em',
'line-height': 1
};
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;
}
};
OBJECT LITERALS
interests is a property and an object
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
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'
OBJECT LITERALS
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
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 );
}
OBJECT LITERALS
Great as function arguments
single argument allows flexibility when calling the function
doSomething({
speed: 'fast',
height: 500,
width: 200,
somethingElse: 'yes'
});
doSomething({width: 300});
REFERENCING SCRIPTS
IN THE HTML
browser slides
SELECTORS & TRAVERSAL
AT THE HEART OF JQUERY...
Find something
Do something
TIPS
Avoid jQuery's custom selectors when possible
// slower
$('li:eq(3)')
$('li:lt(3)')
// faster
$('li').eq(3)
$('li').slice(0, 3)
JSON
JAVASCRIPT OBJECT NOTATION