Vous êtes sur la page 1sur 61

S

0
P
I
N
F
0

0
p
e
n

C
a
m
p
u
s

!"#$%&'(')*+,+-.(/0,12345
Ce uocument mis votie uisposition piovient l'oiigine ue S0PINF0 Inteinational 0niveisity.
Il a pu tie sujet mouification uepuis sa publication initiale.
!""#$%&'()*+()'%,'-.+-'/'0112'$3'"45,%53'6#$78489:3%'$%';<=>?@A'>5,%B57C457D'<59E%BF9,G'
7E%"'$%F'H9DD9%BF'$%'E9$#4FI'D9EB%FI'"43BFI'%5,B7J5%H%5,FI'D489"9%DFI'I'%,"K'
'
!"#$%&'(')*+(,-.)/0'
LLLKF3695M4K"4H+46%5"7H63F''
S0PINF0 vous peimet ue paitagei ce uocument


Vous tes libre de :
Partager reproduire, distribuer et communiquer ce document
Remixer modifier ce document
A condition de respecter les rgles suivantes :
Indication obligatoire de la paternit Vous devez obligatoirement prciser lorigine SUPINFO du document au dbut de celui-ci de la mme manire quindiqu par SUPINFO
International University Notamment en laissant obligatoirement la premire et la dernire page du document, mais pas d'une manire qui suggrerait que SUPINFO International
University vous soutienne ou approuve votre utilisation du document, surtout si vous le modifiez. Dans ce dernier cas, il vous faudra obligatoirement supprimer le texte SUPINFO
Official Document en tte de page et prciser la page indiquant votre identit et les modifications principales apportes. En dehors de ces dispositions, aucune autre modification de
la premire et de la dernire page du document nest autorise.
NOTE IMPORTANTE!
!
Ce document est mis disposition selon le contrat CC-BY-NC-SA Creative Commons disponible en ligne http://creativecommons.org/licenses ou par courrier postal Creative Commons, 171
Second Street, Suite 300, San Francisco, California 94105, USA modi en ce sens que la premire et la dernire page du document ne peuvent tre supprimes en cas de reproduction, distribution,
communication ou modication. Vous pouvez donc reproduire, remixer, arranger et adapter ce document des ns non commerciales tant que vous respectez les rgles de paternit et que les
nouveaux documents sont protgs selon des termes identiques. Les autorisations au-del du champ de cette licence peuvent tre obtenues support@supinfo.com.!
!
SUPINFO International University EDUCINVEST!
IT Tower - Avenue Louise 480 1050 Brussels Belgium . www.supinfo.com !
jQuery
www.supinfo.com
Copyright SUPINFO. All rights reserved
The JavaScript Library
Course Objectives
Discover jQuery principles and
advantages.
Be able to use it to manipulate
CSS properties.
Be able to design simple
By following this course, you will:
jQuery
Be able to design simple
JavaScript animations.
Be able to do event
programming.
Be able to manipulate content.
Course Scheme
Discovery of jQuery
Selectors
CSS Manipulation
Event
Here are the parts that we will approach:
jQuery
Content Manipulation
Discovery of jQuery
jQuery
Preview
Presentation
Hello World
Advantages
Installation
These are the chapters that we will approach:
Discovery
Presentation
Discovery
Library designed to simplify the use of JavaScript.
First release in 2006 by John Resig.
The most popular JavaScript library !
Used by over 31% of the 10 000 most visited websites.
Free and Open Source. Free and Open Source.
Has many Plugins
Image sliders.
Form validators.
File upload tools.
Dynamic Data Tables.
Etc
Hello World
Discovery
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" >
<head>
<title>Hello World avec jQuery</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="jquery.js></script>
</head>
<body>
Hi !
<script type="text/javascript> <script type="text/javascript>
$('body').html('Hello World');
</script>
</body>
</html>
Advantages
Discovery
Syntax designed to make it easier to navigate into a
document.
Simple JavaScript version :
function getTextboxValue() {
var obj = document.getElementById("champ_input");
alert('Le champ a pour valeur : "' + obj.value + '"');
jQuery version :
alert('Le champ a pour valeur : "' + obj.value + '"');
}
function getTextboxValue() {
alert('Le champ a pour valeur : + $(#champ_input").val());
}
Advantages
Discovery
Guarantee code compatibility across a wide number of
browser.
Simple JavaScript version :
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset; scrOfX = window.pageXOffset;
} else if( document.body && } else if( document.body &&
(document.body.scrollLeft || document.body.scrollTop))
{
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement &&
(document.documentElement.scrollLeft ||
document.documentElement.scrollTop))
{
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
Advantages
Discovery
Guarantee code compatibility across a wide number of
browser.
jQuery version :
function getScrollXY() {
return [$(document).scrollTop(),
$(document).scrollLeft()];
}
So What do you prefer to use ?
Installation
Discovery
To use jQuery library, you have to download and
include it in your page :
If you dont want to host the jQuery files, you can use
<script type="text/javascript" src="jquery.js>
</script>
If you dont want to host the jQuery files, you can use
those hosted by Google :
<script type="text/javascript
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jqu
ery.min.js>
</script>
Questions
Do you have any questions?
Discovery
Selectors
jQuery
Preview
Presentation
CSS Selectors
Specific jQuery Selectors
These are the chapters that we will approach:
Selectors
Presentation
Selectors
Selectors are used to select elements on your page and
interact with them.
Two types of selector can be used :
CSS Selectors CSS Selectors
Specific jQuery Selectors
CSS Selectors
Selectors
Expression Return
* All elements.
element All element elements.
#id Element with "id" as id.
.class All elements with "class" as class value.
elem[attr] All elements "elem with "attr" attribute specified.
elem[attr="val"] All elements "elem with "attr" attribute specified
with the value val".
elem1 elem2 All "elem2" elements contained in "elem1" elements.
elem1 > elem2 All "elem2" elements directly inside "elem1"
elements.
elem1 + elem2 All "elem2" elements immediately preceded by
"elem1" elements.
elem1 ~ elem2 All "elem2" elements preceded by "elem1"
elements.
CSS Selectors
Selectors
$('p');
$('div');
$('#header');
<p> Hey, Dude ! </p>
<div> ... </div>
<div id="header"> ... </div>
$('#header');
$('#menu');
$('.notice');
$('.error');
<span id="menu"> ... </span>
<div id="header"> ... </div>
<span class=notice"> ... </span>
<span class=error"> ... </span>
Specific jQuery Selectors
Selectors
Expression Return
:hidden Hidden/invisible elements.
:visible Visible elements.
:parent Elements with child elements.
:header Title elements (h1, h2, h3, ).
:not(s) Elements not selected by the selector "s".
:has(s) Elements containing elements selected by the selector "s". :has(s) Elements containing elements selected by the selector "s".
:contains(t) Elements containing the text t".
:empty Elements with empty content.
:eq(n) et :nth(n) The nth element (zero-based).
:gt(n) Elements with index greater than n.
:lt(n) Elements with index lower than n.
:first Same as eq(0).
:last The last element.
:even Elements with even index.
:odd Elements with odd index.
Specific jQuery Selectors
Selectors
$('img:hidden');
$('img[src$=.png]');
<img src="1.png style=display: none; />
$('img[src$=.png]');
$("p:contains('Hi'):has(span)");
<img src="1.png style=display: none; />
<p> Hi ! <span class="smth"> Buddy </span> </p>
Questions
Do you have any questions?
Events
CSS Manipulation
jQuery
Preview
CSS Functions
Animations
These are the chapters that we will approach:
CSS Manipulation
CSS Functions
CSS Manipulation
You can manipulate CSS easily thanks to functions below :
.css( propertyName )
Get the CSS property value.
var color = $("div").css("background-color");
alert(color);
CSS Functions
CSS Manipulation
You can manipulate CSS easily thanks to functions below :
.css( propertyName, value )
Set the CSS property value.
$("div").css("background-color, "cyan"); $("div").css("background-color, "cyan");
var color = $("div").css("background-color");
alert(color);
CSS Functions
CSS Manipulation
You can manipulate CSS easily thanks to functions below :
.css( map )
Set all the CSS properties contained in the map.
$("p").css({
"background-color : "cyan",
"font-weight : "bolder"
});
Animations
CSS Manipulation
You can create animation effects on any numeric CSS
property
.animate( properties, [ duration ])
All animated properties should be a single numeric
value.
Properties like width, height, or left can be Properties like width, height, or left can be
animated but background-color cant be.
In addition to numeric values , each property
can take the strings "show", "hide" and
"toggle".
Animated properties can also be relative thanks
to leading += and -= sequence of characters.
Duration value is in milliseconds or a following
string: "slow", "normal", "fast".
Animations
CSS Manipulation
You can create animation effects on any numeric CSS
property
.animate( properties, [ duration ])
$("#test").animate({
left: '+=50',
opacity: 'show'
}, 500);
Animations
CSS Manipulation
jQuery provide many other functions to animate elements :
$("#test").fadeIn(500);
$("#test").fadeOut("slow");
$("#test").fadeTo("slow",0.5);
$("#test").slideDown(800);
$("#test").slideUp("fast");
$("#test").slideToggle(1200);
$("#test").hide("normal");
$("#test").show(666);
Questions
Do you have any questions?
CSS Manipulation
Exercises
CSS Manipulation
Were going to play with jQuery and add some CSS
properties to our Resume page.
Firstly, install jQuery in your page.
Secondly, use jQuery to add a background color to
your link to Google.
Third, your More about me title have to blink.
Fourth, use the animate function to add a grow effect
to your main title.
Events
jQuery
Preview
Presentation
Example
this keyword
Callbacks
These are the chapters that we will approach:
Events
Presentation
Events
jQuery provide methods to keep clean separation of
structure (HTML) and behaviours (JavaScript).
No more need to use HTML event attributes
onclick
onblur
onload

Just use selectors and jQuery methods on it !
$("a").click( function(){ alert("Hello World"); });
Anonymous Function
Presentation
Events
Function Description
.blur(handler) The blur event is sent to an element when it loses
focus.
.change(handler) The change event is sent to an element when its
value changes.
.click(handler) The click event is sent to an element when the mouse
pointer is over the element, and the mouse button is
pressed and released. pressed and released.
.focus(handler) The focus event is sent to an element when it gains
focus.
.keydown(handler) The keydown event is sent to an element when the
user first presses a key on the keyboard.
.keyup(handler) The keyup event is sent to an element when the user
releases a key on the keyboard.
.submit(handler) The submit event is sent to an element when the user
is attempting to submit a form.

Example
Events
What does this snippet do ?
$("form").submit( function() {
if ($("input:first").val() == admin") {
$("span").text(Welcome Mr Admin.").show();
return true;
}}
$("input:first").css("background-color", "red");
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
What is "this" ?
Events
jQuery provide the this keyword.
Represent the selected element inside nested functions.
Example :
<div id="test">Rock Paper Scissors Lezard Spock</div>
<script type="text/javascript">
$("#test").hover( function() {
$(this).css("color", "pink");
}, function() {
$(this).css("color", "black");
});
</script>
Go to the next slide to
learn what it is
Callbacks
Events
Some jQuery functions allow two anonymous functions in
parameter.
The second one is called callback function
Executed when the event is finished.
Most functions that accept callbacks are animation ones
.fadeIn()
.fadeOut()
.slideUp()
.slideDown()

Callbacks
Events
Example :
<div id="test">Rock Paper Scissors Lezard Spock</div>
<script type="text/javascript">
$("#test").slideUp(1234, function() {
alert("You have closed the div.");
});
</script>
Questions
Do you have any questions?
Events
Exercises (1/2)
Events
Create a new webpage named solar_system.html.
The HTML must just be an unordered list of image.
Use CSS to make the
page look like this :
The pictures you need
are on
courses.supinfo.com
Exercises (2/2)
Events
When your mouse passes over an image :
It has to become darker and display the planet
name.
Content Manipulation
jQuery
Preview
Presentation
Textual Content
HTML Content
Insert Inside an Element
These are the chapters that we will approach:
Content Manipulation
Insert Outside
Wrappers
Clone
Remove
Presentation
Content Manipulation
jQuery provide methods to add, retrieve, modify and
remove HTML content.
Were going to discover and explain them.
Textual Content
Content Manipulation
.text()
Get the combined text contents of each element in the
set of matched elements, including their descendants
<p id=test">
<span class=text">Hello you ;-)</span>
</p>
<script type="text/javascript">
var text = $("#test").text();
alert(text);
</script>
Textual Content
Content Manipulation
.text( textString )
Set the content of each element in the set of matched
elements to the specified text.
<p id=test">
<span class=text">Hello you ;-)</span>
</p>
<script type="text/javascript">
$("#test").text("<span>Hello by jQuery!</span>");
</script>
<p id=test">
&lt;span&gt;Hello by jQuery!&lt;/span&gt;
</p>
HTML Content
Content Manipulation
.html()
Get the HTML contents of the first element in the set of
matched elements.
<p id=test">
<span class=text">Hello you ;-)</span>
</p>
<script type="text/javascript">
var text = $("#test").html();
alert(text);
</script>
HTML Content
Content Manipulation
.html( textString )
Set the HTML contents of each element in the set of
matched elements.
<p id=test">
<span class=text">Hello you ;-)</span>
</p>
<script type="text/javascript">
$("#test").html("<span>Hello by jQuery!</span>");
</script>
<p id=test">
<span>Hello by jQuery!</span>
</p>
HTML Content
Content Manipulation
.replaceWith( textString )
Replace each element in the set of matched elements
with the provided new content.
<p id=test">
<span class=text">Hello you ;-)</span>
</p>
<script type="text/javascript">
$("#test").replaceWith("<p>Hello by jQuery!</p>");
</script>
<p> Hello by jQuery! </p>
Insert Inside an Element
Content Manipulation
.prepend( textString )
Insert content, specified by the parameter, to the
beginning of each element in the set of matched
elements.
.append( textString )
Insert content, specified by the parameter, to the end of Insert content, specified by the parameter, to the end of
each element in the set of matched elements.
<p id="test"> Hello you ;-)</p>
<script type="text/javascript">
$("#test").prepend("<em>Before</em>");
$("#test").append("<em>After</em>");
</script>
<p><em>Before</em>Hello by jQuery!<em>After</em></p>
Insert Outside
Content Manipulation
.insertBefore( selector )
Insert every element in the set of matched elements
before the target.
.insertAfter( selector )
Insert every element in the set of matched elements
after the target. after the target.
<p id="test"> Hello you ;-)</p>
<script type="text/javascript">
$("<em>Before</em>").insertBefore("#test");
$("<em>After</em>").insertAfter("#test");
</script>
<em>Before</em><p>Hello by jQuery!</p><em>After</em>
Wrappers
Content Manipulation
.wrap( wrappingElement)
Wrap an HTML structure around each element in the
set of matched elements.
<p class="test"> Its gonna be legen...</p>
<p> wait for it </p>
<p class="test"> ...dary ! </p>
<script type="text/javascript">
$(".test").wrap("<div id='barney' />");
</script>
<div id="barney">
<p class="test"> Its gonna be legen...</p>
</div>
<p> wait for it </p>
<div id="barney">
<p class="test"> ...dary ! </p>
</div>
Copy
Content Manipulation
.clone()
Create a deep copy of the set of matched elements.
<p class="test"> Kage bunshin no jutsu ! </p>
<script type="text/javascript">
$(".test").clone().appendTo("body"); $(".test").clone().appendTo("body");
$(".test").clone().appendTo("body");
</script>
<p class="test"> Kage bunshin no jutsu ! </p>
<p class="test"> Kage bunshin no jutsu ! </p>
<p class="test"> Kage bunshin no jutsu ! </p>
<p class="test"> Kage bunshin no jutsu ! </p>
Remove
Content Manipulation
.remove()
Remove the set of matched elements from the DOM.
<p class="test"> Its gonna be legen...</p>
<p> wait for it </p>
<p class="test"> ...dary ! </p>
<p class="test"> Its gonna be legen...</p>
<p class="test"> ...dary ! </p>
<script type="text/javascript">
$("p:not(.test)").remove();
</script>
Questions
Do you have any questions?
Content Manipulation
Exercises
Content Manipulation
Modify your solar_system.html page
When you click on an image, it has to be displayed
bigger in the center of the screen and all in
background have to become darker.
The bigger image The bigger image
have to be displayed
with a toggle effect.
To close it and return
to the same screen
than at beginning, you
have to just click in the
dark area.
Demonstration
Events
jQuery
advantages
jQuery
advantages
Course summary
jQuery
Content
manipulation
Content
manipulation
Events Events
Animation Animation
For more
Publications
If you want to go into these subjects more deeply,
jQuery
jQuery
Le framework JavaScript du Web 2.0
Web sites
http://jquery.com/ http://api.jquery.com/
http://webdesignledger.com/resources/best-jquery-plugins-of-2010
http://www.siteduzero.com/tutoriel-3-160876-decouvrir-jquery.html
Luc VAN LANCKER
Available on http://librairies.supinfo.com
ENI editions
S
0
P
I
N
F
0

0
p
e
n

C
a
m
p
u
s

!"#$%&'(')*+,+-.(/0,12345
Ce uocument mis votie uisposition piovient l'oiigine ue S0PINF0 Inteinational 0niveisity.
Il a pu tie sujet mouification uepuis sa publication initiale.
!""#$%&'()*+()'%,'-.+-'/'0112'$3'"45,%53'6#$78489:3%'$%';<=>?@A'>5,%B57C457D'<59E%BF9,G'
7E%"'$%F'H9DD9%BF'$%'E9$#4FI'D9EB%FI'"43BFI'%5,B7J5%H%5,FI'D489"9%DFI'I'%,"K'
'
!"#$%&'(')*+(,-.)/0'
LLLKF3695M4K"4H+46%5"7H63F''
S0PINF0 vous peimet ue paitagei ce uocument


Vous tes libre de :
Partager reproduire, distribuer et communiquer ce document
Remixer modifier ce document
A condition de respecter les rgles suivantes :
Indication obligatoire de la paternit Vous devez obligatoirement prciser lorigine SUPINFO du document au dbut de celui-ci de la mme manire quindiqu par SUPINFO
International University Notamment en laissant obligatoirement la premire et la dernire page du document, mais pas d'une manire qui suggrerait que SUPINFO International
University vous soutienne ou approuve votre utilisation du document, surtout si vous le modifiez. Dans ce dernier cas, il vous faudra obligatoirement supprimer le texte SUPINFO
Official Document en tte de page et prciser la page indiquant votre identit et les modifications principales apportes. En dehors de ces dispositions, aucune autre modification de
la premire et de la dernire page du document nest autorise.
NOTE IMPORTANTE!
!
Ce document est mis disposition selon le contrat CC-BY-NC-SA Creative Commons disponible en ligne http://creativecommons.org/licenses ou par courrier postal Creative Commons, 171
Second Street, Suite 300, San Francisco, California 94105, USA modi en ce sens que la premire et la dernire page du document ne peuvent tre supprimes en cas de reproduction, distribution,
communication ou modication. Vous pouvez donc reproduire, remixer, arranger et adapter ce document des ns non commerciales tant que vous respectez les rgles de paternit et que les
nouveaux documents sont protgs selon des termes identiques. Les autorisations au-del du champ de cette licence peuvent tre obtenues support@supinfo.com.!
!
SUPINFO International University EDUCINVEST!
IT Tower - Avenue Louise 480 1050 Brussels Belgium . www.supinfo.com !

Vous aimerez peut-être aussi