




jQuery est de plus en plus important que nous le pensons, m
Note: the version used in this article is jQuery 1.2.3
First you need to download a copy of jQuery and insert it in your html page (preferably within the <head>
tag). Then you need to write functions to tell jQuery what to do. The diagram below explains the detail how jQuery work:
Writing jQuery function is relatively easy (thanks to the wonderful documentation). The key point you have to learn is how to get the exact element that you want to apply the effects.
$("#header")
= get the element with id="header"$("h3")
= get all <h3> element$("div#content .photo")
= get all element with class="photo" nested in the <div id="content">$("ul li")
= get all <li> element nested in all <ul>$("ul li:first")
= get only the first <li> element of the <ul>Let's start by doing a simple slide panel. You've probably seen a lot of this, where you click on a link and a panel slide up/down. (view demo)
When an elment with class="btn-slide" is clicked, it will slideToggle (up/down) the <div id="panel"> element and then toggle a CSS class="active" to the <a class="btn-slide"> element. The .active class will toggle the background position of the arrow image (by CSS).
$(document).ready(function(){
$(".btn-slide").click(function(){
$("#panel").slideToggle("slow");
$(this).toggleClass("active");
});
});
This sample will show you how to make something disappear when an image button is clicked. (view demo)
When the <img class="delete"> is clicked, it will find its parent element <div class="pane"> and animate its opacity=hide with slow speed.
$(document).ready(function(){
$(".pane .delete").click(function(){
$(this).parents(".pane").animate({ opacity: "hide" }, "slow");
});
});
Now let's see the power of jQuery's chainability. With just several lines of code, I can make the box fly around with scaling and fading transition. (view demo)
Line 1: when the <a class="run"> is clicked
Line 2: animate the <div id="box"> opacity=0.1, left property until it reaches 400px, with speed 1200 (milliseconds)
Line 3: then opacity=0.4, top=160px, height=20, width=20, with speed "slow"
Line 4: then opacity=1, left=0, height=100, width=100, with speed "slow"
Line 5: then opacity=1, left=0, height=100, width=100, with speed "slow"
Line 6: then top=0, with speed "fast"
Line 7: then slideUp (default speed = "normal")
Line 8: then slideDown, with speed "slow"
Line 9: return false will prevent the browser jump to the link anchor
$(document).ready(function(){
$(".run").click(function(){
$("#box").animate({opacity: "0.1", left: "+=400"}, 1200)
.animate({opacity: "0.4", top: "+=160", height: "20", width: "20"}, "slow")
.animate({opacity: "1", left: "0", height: "100", width: "100"}, "slow")
.animate({top: "0"}, "fast")
.slideUp()
.slideDown("slow")
return false;
});
});