HowjQueryWorks
1.jQuery:TheBasics
Thisisabasictutorial,designedtohelpyougetstartedusingjQuery.
Ifyoudon'thaveatestpagesetupyet,startbycreatingthefollowingHTMLpage:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
// Your code goes here.
</script>
</body>
</html>Thesrcattributeinthe<script>elementmustpointtoacopyofjQuery.
DownloadacopyofjQueryfromtheDownloadingjQuerypageandstorethejquery.jsfileinthesamedirectoryasyourHTMLfile.
Note:WhenyoudownloadjQuery,thefilenamemaycontainaversionnumber,e.g.,jquery-x.y.z.js.
Makesuretoeitherrenamethisfiletojquery.jsorupdatethesrcattributeofthe<script>elementtomatchthefilename.
2.LaunchingCodeonDocumentReady
Toensurethattheircoderunsafterthebrowserfinishesloadingthedocument,
manyJavaScriptprogrammerswraptheircodeinanonloadfunction:
window.onload = function() {
alert( "welcome" );
};Unfortunately,thecodedoesn'trununtilallimagesarefinisheddownloading,includingbannerads.
Toruncodeassoonasthedocumentisreadytobemanipulated,jQueryhasastatementknownasthereadyevent:
$( document ).ready(function() {
// Your code here.
});Forexample,insidethereadyevent,youcanaddaclickhandlertothelink:
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "Thanks for visiting!" );
});
});CopytheabovejQuerycodeintoyourHTMLfilewhereitsays"//Yourcodegoeshere".
Then,saveyourHTMLfileandreloadthetestpageinyourbrowser.
Clickingthelinkshouldnowfirstdisplayanalertpop-up,
thencontinuewiththedefaultbehaviorofnavigatingtohttp://jquery.com.
Forclickandmostotherevents,youcanpreventthedefaultbehavior
bycallingevent.preventDefault()intheeventhandler:
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "As you can see, the link no longer took you to jquery.com" );
event.preventDefault();
});
});TryreplacingyourfirstsnippetofjQuerycode,
whichyoupreviouslycopiedintoyourHTMLfile,withtheoneabove.
SavetheHTMLfileagainandreloadtotryitout.
CompleteExample
Thefollowingexampleillustratestheclickhandlingcodediscussedabove,
embeddeddirectlyintheHTML<body>.Notethatinpractice,
itisusuallybettertoplaceyourcodeinaseparateJSfileandloadit
onthepagewitha<script>element'ssrcattribute.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<script src="jquery.js"></script>
<script>
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "The link will no longer take you to jquery.com" );
event.preventDefault();
});
});
</script>
</body>
</html>http://api.jquery.com/ready/
jQueryoffersseveralwaystoattachafunctionthatwillrunwhentheDOMisready.Allofthefollowingsyntaxesareequivalent:
// fn is a type of function.
// 1.
$(fn);
// 2.
$(document).ready(fn);
// 3.
$("document").ready(fn);
// 4.
$("img").ready(fn);
// 5.
$().ready(fn);// an implemention of onReady function.
// onReady function
var onReady = function(fn){
var old = window.onload;
if(typeof old != 'function'){
window.onload = fn;
}else{
window.onload = function(){
old();
fn();
}
}
}
// An usage of example:
onReady(function(){
console.log(1);
});
onReady(function(){
console.log(2);
});
onReady(function(){
console.log(3);
});3.AddingandRemovinganHTMLClass
Important:YoumustplacetheremainingjQueryexamplesinsidethereadyevent
sothatyourcodeexecuteswhenthedocumentisreadytobeworkedon.
Anothercommontaskisaddingorremovingaclass.
First,addsomestyleinformationintothe<head>ofthedocument,likethis:
<style>
a.test {
font-weight: bold;
}
</style>Next,addthe.addClass()calltothescript:
$( "a" ).addClass( "test" );
All<a>elementsarenowbold.
Toremoveanexistingclass,use.removeClass():
$( "a" ).removeClass( "test" );
SpecialEffects
jQueryalsoprovidessomehandyeffectstohelpyoumakeyourwebsitesstandout.Forexample,ifyoucreateaclickhandlerof:
$( "a" ).click(function( event ) {
event.preventDefault();
$( this ).hide( "slow" );
});Thenthelinkslowlydisappearswhenclicked.
4.CallbacksandFunctions
Unlikemanyotherprogramminglanguages,
JavaScriptenablesyoutofreelypassfunctionsaroundtobeexecutedatalatertime.
Acallbackisafunctionthatispassedasanargumenttoanotherfunctionandis
executedafteritsparentfunctionhascompleted.
Callbacksarespecialbecausetheypatientlywaittoexecuteuntiltheirparentfinishes.
Meanwhile,thebrowsercanbeexecutingotherfunctionsordoingallsortsofotherwork.
Tousecallbacks,itisimportanttoknowhowtopassthemintotheirparentfunction.
4.1CallbackwithoutArguments
Ifacallbackhasnoarguments,youcanpassitinlikethis:
$.get( "myhtmlpage.html", myCallBack );
When$.get()finishesgettingthepagemyhtmlpage.html,itexecutesthemyCallBack()function.
Note:Thesecondparameterhereissimplythefunctionname
(butnotasastring,andwithoutparentheses).
4.2CallbackwithArguments
Executingcallbackswithargumentscanbetricky.
4.2.1Wrong
Thiscodeexamplewillnotwork:
// call myCallback() function immediately. $.get( "myhtmlpage.html", myCallBack( param1, param2 ) );
ThereasonthisfailsisthatthecodeexecutesmyCallBack(param1,param2)immediately
andthenpassesmyCallBack()'sreturnvalueasthesecondparameterto$.get().
WeactuallywanttopassthefunctionmyCallBack(),notmyCallBack(param1,param2)'sreturn
value(whichmightormightnotbeafunction).
So,howtopassinmyCallBack()andincludeitsarguments?
4.2.2Right
TodeferexecutingmyCallBack()withitsparameters,youcanuseananonymousfunctionasawrapper.
Notetheuseoffunction(){}.Theanonymousfunctiondoesexactlyonething:callsmyCallBack(),
withthevaluesofparam1andparam2.
// define an anonymous function,
// which invoke myCallback() inside its function body.
$.get( "myhtmlpage.html", function() {
myCallBack( param1, param2 );
});When$.get()finishesgettingthepagemyhtmlpage.html,
itexecutestheanonymousfunction,whichexecutesmyCallBack(param1,param2).
<hr/>
WhatisthedifferencebetweenthesejQueryreadyfunctions?
// what is difference between
$(function(){
});
// and
$(document).ready(function() {
});Answer:
Link1.
Link2.
Thetwowaysareequivalent,Ipersonallypreferthesecond,$(function(){});it'sjustashortcutfordocumentready.
AboutthenewjQuery(document)...construct,youdon'treallyneedtousethenewoperator,jQuerywilluseitinternallyifyoudon't.
Theargumentthatthereadyhandlerfunctionreceives,isthejQueryobjectitself.
That'squiteusefulwhereyouhavetorunjQueryincompatibilitymodewithotherlibraries,forexample:
jQuery(function($){
//use$here
});
The$argumentinsidethecallbackwillrefertothejQueryobject,outsidethatfunctionitmightrefertoanotherlibrarylikePrototypeJS.
-