JQuery: JQuery in 8 Hours, JQuery for Beginners, Learn ... · Show Content (1) Show Content (2) Set...

Post on 17-Aug-2020

32 views 2 download

Transcript of JQuery: JQuery in 8 Hours, JQuery for Beginners, Learn ... · Show Content (1) Show Content (2) Set...

JQueryIn8Hours

ByRayYao

ForBeginners

LearnJQueryFast!

Copyright©2015byRayYao

AllRightsReserved

Neitherpartofthisbooknorwholeofthisbookmaybereproducedortransmittedinanyformorbyanymeanselectronic,photographicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromtheauthor.RayYao

AbouttheAuthor

RayYao:

CertifiedPHPengineerbyZend,USA

CertifiedJAVAprogrammerbySun,USA

CertifiedSCWCDdeveloperbyOracle,USA

CertifiedA+professionalbyCompTIA,USA

CertifiedASP.NETexpertbyMicrosoft,USA

CertifiedMCPprofessionalbyMicrosoft,USA

CertifiedTECHNOLOGYspecialistbyMicrosoft,USA

CertifiedNETWORK+professionalbyCompTIA,USA

ToknowmoreRayYao’sbooksinAmazon:

www.websprogram.com/books.php

www.amazon.com/author/rayyao

PrefaceThisbookisausefulbookaboutJQueryprogramming.YoucanlearncompleteprimaryknowledgeofJQueryfastandeasily.Thestraightforwarddefinitions,theplainandsimpleexamples,theelaborateexplanationsandtheneatandbeautifullayoutfeaturethishelpfulandeducativebook.Youwillbeimpressedbythenewdistinctivecomposingstyle.Readingthisbookisagreatenjoyment!YoucanmasterallessentialJQueryskillquickly.

SourceCodeforDownloadThisbookprovidessourcecodefordownload;youcandownloadthesourcecodeforbetterstudy,orcopythesourcecodetoyourfavoriteeditortotesttheprograms.Thedownloadlinkofthesourcecodeisatthelastpageofthisbook.

StartCodingToday!

TableofContentsHour1JQueryBasic

WhatisjQuery?

InstalljQuery

FirstjQueryscript

RunWhenPageLoaded

Whatis$(“”)meaning?

ShowContent(1)

ShowContent(2)

SetCSSStyle

SetCSSbyID

SetCSSbyTag

SetCSSbyClass

SetCSSbySpecifiedTag

SetCSSbyIndex

SetCSSbyFirstTag

SetCSSbyLastTag

SetCSSbyEmbedTag

Exercises

Hour2jQueryFunctionAddaClass

Add&RemoveClass

TheSizeofElement

ShowHiddenElements

HideSelectedElements

Hide&ShowElements

SlideElementUp

SlideElementDown

InsertBeforeElement

InsertAfterElement

CheckElementCondition

HowManyElements?

Exercises

Hour3ElementsSelection$(document).ready()

$(function(){})

$(“divtag”)

$(“div>tag”)

$(“divtag”)&$(“div>tag”)

$(“tag:contains(text)”)

$(“tag[attribute]”)

$(“tag[attribute=value]”)

$(“#id”).is(‘tag’)

$(“tag:eq(3)”)

$(“input:checked”)

$(“selectoption:selected”)

Exercises

Hour4MoreFunctionattr()

html()

text()

append()

width()

height()

before()

after()

val()

Exercises

Hour5Eventbind(event,function(event){})

one(event,function(event){})

event(function(){})

event.screenX&event.screenY

event.pageX&event.pageY

event.keyCode

hover(over,out)

Exercises

Hour6Effects&Animationshow(duration,callback)

hide(duration,callback)

toggle(duration,callback)

fadeOut(duration,callback)

fadeIn(duration,callback)

slideUp(duration,callback)

slideDown(duration,callback)

slideToggle(duration,callback)

fadeTo(duration,opacity)

animate()

Exercises

Hour7UtilityFunctions$.each()

$.makeArray()

$.isArray()

$.inArray()

$.grep()

$.unique()

$.trim()

Exercises

Hour8AjaxbyjQueryWhatisAjax?

SetupServer

load()

$.post()

$.get()

$.ajax()withpostmethod

$.ajax()withgetmethod

AjaxError

AjaxSuccess

Exercises

SourceCodeforDownload

Hour1JQueryBasic

WhatisjQuery?JQueryisaclientside-scriptinglibraryofJavaScript.Youcanaccessanyelement,makeanimation,andvalidateinputbyusingthelibrary.Noextracodecanachievetheresultbywritingoneorfewlinesofcodeinsteadofwritingdozenlinesofcodes.Youcanhandletheeventseasilyinthehtmldocument;getfastresultsfromserverusingAjax,andsoon……

Advantages:

Ithelpstorunwithallkindofbrowsersandiscompatiblevariousbrowsers.

Ithelpstoimplementcriticalfunctionalitywithoutwritinghundredsoflineofcodes.

Itisfasttoimplementcustomizedaction.

KnowmoreJQuery:

http://learn.jquery.com/

http://api.jquery.com/

http://forum.jquery.com/

http://www.websprogram.com/

DownloadJQuery:

http://jquery.com/download/

InstalljQueryWecanusejQueryintwoways:

(1)IfyouwanttousejQueryfilelocally,thendownloadit.DownloadjQueryfromhttp://jquery.com/download/,putthedownloadedfileinthesamefolderwithyourjQueryfiles,andreferenceitin<head>sectionofhtmldocumentasfollowing:

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

</head>

(2)IfyoudonotwanttodownloadjQuery,thenyoucanincludeitinhtmldocumentasfollowing:

<head>

<scriptsrc=“http://code.jquery.com/jquery-latest.js”></script>

</head>

FirstjQueryscriptNowwewritethefirstjQueryscript.Createanewhtmldocumentnamed“Test.html”.

Example1.1

<html>

<head>

<title>jQueryHelloWorld</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(document).ready(function(){

$(“#divID”).html(“HelloWorld!”);

});

</script>

</head>

<body>

<divid=“divID”>

</div>

</body>

</html>

SavefilewithnamedTest.htmlandrunitbyanybrowser,youwillseetheresult:

Output:

HelloWorld!

Explanation:

“<scriptsrc=“jquery-1.11.3.js”</script>”meanstousejQuerycodeincurrentdocument.

“$(document).ready(function(){})”meanstorunthefunctionautomaticallywhenthewebpageiscompletelyloaded.

“$(“#divID”)”accessesthetagwhoseidis“divID”.

“html()”displaysthecontents.

“$(“#divID”).html(“HelloWorld!”)”displays“HelloWorld!”inatagwhoseidis“divID”.

“<divid=“divID”>”definesatagnamed“divID”wheresomecontentswillbeshown.

Congratulation!Youhaveachievedyourfirsttarget.

RunWhenPageLoaded“$(document).ready(function(){})”meanstoexecutethefunctionwhenthewebpageisloadedcompletely.

Example1.2

<html>

<head>

<title>JQuerypathTesting</title>

<scriptsrc=“jquery-1.11.3.js”></script>

</head>

<body>

<scripttype=“text/javascript”>

$(document).ready(function(){

alert(“TestjQuerypath”);

});

</script>

</body>

</html>

Savefilewithtestjquery.htmlandrunitanybrowser,youwillseethealertboxwithmessage“TestJQuerypath”.

Output:

Explanation:

“<scriptsrc=“jquery-1.11.3.js”></script>”usesjQuerycodeincurrentdocument.

“$(document).ready(function(){})”executesthefunctionwhenthewebpageisloadedcompletely.

Whatis$(“”)meaning?“$”isasymbolofjQuery.

“$()”accessesanelementincurrenthtmldocument.

Forexample:

$(“span”)accessesatag,itstagnameis“span”.

$(“#3”)accessesatag,itsidis“3”.

$(“.clss5”)accessesatag,itsclassnameis“clss5”.

ShowContent(1)$(“tag”).html()

$(“tag”)accessesthe“tag”.

.html()showsthecontentswithouthtmlsymbol.

Example1.3

<html>

<head>

<title>Howtousehtml()</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<script>

$(document).ready(function(){

$(“div”).html(“<h1>Halloworld!</h1>”);

});

</script>

</head>

<body>

<div></div>

</body>

</html>

Pleaserunthebrowse,youwillseetheresult.

Output:

HelloWorld!

Explanation:

“<scriptsrc=“jquery-1.11.3.js”></script>”usesjQuerycodeincurrentdocument.

“$(document).ready(function(){}”executesthefunctionwhenthewebpageisloadedcompletely.

“$(“div”).html(“<h1>Halloworld!</h1>”)”displays“Halloworld!”intag“div”.

Note:Youcannotsee<h1>…</h1>,because.html()showscontentswithouthtmlsymbol.

ShowContent(2)$(“tag”).text()

“$(“tag”)”accessesthe“tag”

.text()showscontentswithhtmlsymbol.

Example1.4

<html>

<head>

<title>Howtousetext()</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<script>

$(document).ready(function(){

$(“div”).text(“<h1>Halloworld!</h1>”);

});

</script>

</head>

<body>

<div></div>

</body>

</html>

Pleaserunthebrowse,youwillseetheresult.

Output:

<h1>Halloworld!</h1>

Explanation:

“<scriptsrc=“jquery-1.11.3.js”></script>”usesjQuerycodeincurrentdocument.

“$(document).ready(function(){}”executesthefunctionwhenthewebpageisloadedcompletely.

“$(“div”).text(“<h1>Halloworld!</h1>”)”displays“Halloworld!”intag“div”.

Note:Youcansee<h1>…</h1>,because.text()showscontentswithhtmlsymbol.

SetCSSStyle$(“selector”).css(“style”)

Whatisselector?

AllHTMLelementsbasedontheirid,classes,types(text,radioetc.),attributes(id,title,srcetc),tagname(div,p,form,table,tr,th,tdetc.)etcarejQueryselectors.

$(“selector”)meanstoaccessonespecifiedelement.

Whatiscss()?

Thecss()methodsetsorreturnsoneormorestylepropertiesfortheselectedelements.

css(“style”)meanstosetastyleforaspecifiedelement.

“$(“selector”).css(“style”)”accessesaspecifiedelement,andsetsacssstyleforit.

SetCSSbyID“$(“#id”).css()”accessesatagbyitsid,andsetsacssstyle.

Ifwewanttoaccessanyelementbyits“id”,thenwehavetouse“#”toselectthatelement.css()methodcansetorchangeanyproperty.

Example1.5

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionchangeColor(){

$(“#divTest”).css(“background-color”,“red”);

}

</script>

</head>

<body>

<divid=“divTest”onclick=“changeColor()”style=“cursor:pointer;width:300px;Height:20px;background-color:#cccccc;”>

Clickheretochangebackgroundcolor.

</div>

</body>

</html>

Original:

Clickontext“Clickheretochangebackgroundcolor”,andthenyouwillseethedivbackgroundcolorchanged.

Output:

Explanation:

“$(“#divTest”).css(“background-color”,“red”)”accessesatagwhoseidis“divTest”,andsetsitsbackgroundcoloras“red”.

“<divid=”divTest”onclick=”changeColor()”executesthefunction“changeColor()”whenclickingatagwhoseidis“divTest”.

Inaboveexample,youcanseeIamchanging“div”backgroundcolorbyaccessingitsid‘#divTest”.

SetCSSbyTag“$(“tag”).css()”accessesatagbyitsname,andsetsacssstyle.

Ifwewanttoaccessanyelementbyits“tag”name,thenwehavetouse“tag”nametoselectthatelement,css()methodcansetorchangeanyproperty.

Example1.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionchangeColor(){

$(“div”).css(“background-color”,“red”);

}

</script>

</head>

<body>

<divonclick=“changeColor()”width:300px;style=“cursor:pointer;width:300px;Height:20px;background-color:#cccccc;”>

Clickheretochangebackgroundcolor.

</div>

</body>

</html>

Original:

Clickontext“Clickheretochangebackgroundcolor”,andthenyouwillseethedivbackgroundcolorwillbechanged.

Output:

Explanation:

“$(“div”).css(“background-color”,“red”)”accessesatagwhosetagnameis“divTest”,andsetsitsbackgroundcoloras“red”.

“<divonclick=”changeColor()””executesthefunction“changeColor()”whenclickingatagwhosetagnameis“div”.

Inaboveexample,youcanseeIamchanging“div”backgroundcolorbyusingtag“div”.

SetCSSbyClass“$(“.class”).css()”accessesanelementbyitsclassname,andsetsacssstyle.

Ifwewanttoaccessanyelementby“class”namethenwehavetouse“classname”toselectthatelement,css()methodcansetorchangeanyproperty.

Example1.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionchangeColor(){

$(“.divClick”).css(“background-color”,“red”);

}

</script>

</head>

<body>

<divclass=“divClick”onclick=“changeColor()”style=“cursor:pointer;width:300px;Height:20px;background-color:#cccccc;”>

Clickheretochangebackgroundcolor.

</div>

</body>

</html>

Original:

Clickontext“Clickheretochangebackgroundcolor”,andthenyouwillseethedivbackgroundcolorwillbechanged.

Output:

Explanation:

“$(“.divClick”).css(“background-color”,“red”)”accessesatagwhoseclassnameis“divClick”,andsetsitsbackgroundcoloras“red”.

“<divclass=”divClick”onclick=”changeColor()””executesthefunction“changeColor()”whenclickingatagwhoseclassnameis“divClick”.

Inaboveexample,youcanseeIamchanging“div”backgroundcolorbyusingclass“.divClick”.

SetCSSbySpecifiedTag“$(“‘p:nth-child(n)”).css()”accessesthe“n”tag,andsetsacssstyle.

“$(“‘p:nth-child(1)”).css()”accessesthefirsttag,andsetsacssstyle.

“$(“‘p:nth-child(4)”).css()”accessesthefourthtag,andsetsacssstyle.

Example1.8

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionsetCSS(){

$(‘p:nth-child(1)’).css(“font-style”,“italic”);

$(‘p:nth-child(4)’).css(“font-style”,“italic”);

}

</script>

</head>

<body>

<h1>Selectingthefirstandlasttag</h1>

<div>

<p>IlovejQuery1time</p>

<p>IlovejQuery2time</p>

<p>IlovejQuery3time</p>

<p>IlovejQuery4time</p>

</div>

<inputtype=“button”value=“ClickMe”

onclick=“setCSS()”></input>

</body>

</html>

Original:

IlovejQuery1time

IlovejQuery2time

IlovejQuery3time

IlovejQuery4time

Afterclickingthebutton“Clickme”,youwillseetheresult.

Output:

IlovejQuery1time

IlovejQuery2time

IlovejQuery3time

IlovejQuery4time

Explanation:

“onclick=“setCSS()””executesthefunctionwhenclickingthebutton.

“$(“‘p:nth-child(1)”).css()”accessesthefirsttag,andsetsacssstyle.

“$(“‘p:nth-child(4)”).css()”accessesthefourthtag,andsetsacssstyle.

“onclick=“setCSS()””runsthesetCSS()whenclickingthebutton.

SetCSSbyIndex$(“div”).eq(n).css()accessesanelementwhoseindexnumberis“n”,andsetsacssstyle.

The.eq()selectorisusedtoselectanelementwithaspecificindexnumber.

Note:Theindexnumbersstartsfrom0,sothefirstelementwillhavetheindexnumber0.

Example1.9

<html>

<head>

<title>JQuerytag.3rd</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionchangeColor(){

$(“div”).eq(2).css(“background-color”,“black”);

}

</script>

</head>

<body>

<divstyle=“float:left;background-color:aqua;width:150px;height:120px;”></div>

<divstyle=“float:left;background-color:maroon;width:150px;height:120px;”></div>

<divstyle=“float:left;background-color:green;width:150px;height:120px;”></div>

<br><br><br><br><br><br><br>

<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>

</body>

</html>

Original:

Clickontext“ClickMe”,andthenyouwillseethethirddivbackgroundcolorwillbechanged.

Output:

Explanation:

“$(“div”).eq(2).css(“background-color”,“black”)”accessesthe3thtag“div”,andsetsitsbackgroundcolorasblack.

“<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>”runs“changeColor()”whenclickingthebutton.

Thecolorof3stlocationdivhasbeenchangedfromgreentoblack.

SetCSSbyFirstTag$(“tag:first”).css()accessesthefirstelement,andsetsacssstyle.

“:first”selectorisusedtoselectthefirstelementfrommatchedelements.

Example1.10

<html>

<head>

<title>JQuerytag:first</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionchangeColor(){

$(“div:first”).css(“background-color”,“black”);

}

</script>

</head>

<body>

<divstyle=“float:left;background-color:aqua;width:150px;height:120px;”></div>

<divstyle=“float:left;background-color:maroon;width:150px;height:120px;”></div>

<divstyle=“float:left;background-color:green;width:150px;height:120px;”></div>

<br><br><br><br><br><br><br>

<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>

</body>

</html>

Original:

Clickthebutton“ClickMe”,andthenyouwillseethefirstdivbackgroundcolorwillbechanged.

Output:

Explanation:

“$(“div:first”).css(“background-color”,“black”)”accessesthefirsttag“div”,andsetsitsbackgroundcolorasblack.

“<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>”runs“changeColor()”whenclickingthebutton.

Thecolorof1stlocationdivhasbeenchangedfromaquatoblack.

SetCSSbyLastTag$(“tag:last”).css()accessesthelastelement,andsetsacssstyle.

“:last”selectorisusedtoselectthelasttagfrommatchedelements.

Example1.11

<html>

<head>

<title>JQuerytag:last</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionchangeColor(){

$(“div:last”).css(“background-color”,“black”);

}

</script>

</head>

<body>

<divstyle=“float:left;background-color:aqua;width:150px;height:120px;”></div>

<divstyle=“float:left;background-color:maroon;width:150px;height:120px;”></div>

<divstyle=“float:left;background-color:green;width:150px;height:120px;”></div>

<br><br><br><br><br><br><br>

<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>

</body>

</html>

Original:

Clickonbutton“ClickMe”,andthenyouwillseethelastdivbackgroundcolorwillbechanged.

Output:

Explanation:

“$(“div:last”).css(“background-color”,“black”)”accessesthelasttag“div”,andsetsitsbackgroundcolorasblack.

“<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>”runs“changeColor()”whenclickingthebutton.

Thecoloroflastlocationdivhasbeenchangedfromgreentoblack.

SetCSSbyEmbedTag$(“body”)selectorwillgetthecontentinsidethe“body”tag.$(“bodydiv”)willgetthealldivelementsinsidethe“body”tag.

$(“bodydivtag”).css()accessesa“tag”underthe“div”insidethe“body”,andsetsacssstyle.

Example1.12

<html>

<head>

<title>JQuerytag.3rd</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionchangeColor(){

$(“bodydivp”).css(“background-color”,“gray”);

}

</script>

</head>

<body>

<div>

<palign=“center”style=“float:left;background-color:aqua;width:150px;height:120px;”></p>

<palign=“center”style=“float:left;background-color:maroon;width:150px;height:120px;”></p>

<pstyle=“float:left;background-color:green;width:150px;height:120px;”></p>

</div>

<br><br><br><br><br><br>

<div><br><br><br>

<inputname=“button”type=“button”onClick=“changeColor()”value=“ClickMe”/>

</div>

</html>

Original:

Clickontext“ClickMe”andthenyouwillseethattextcolorofall“p”tagof“div”taginside“body”tagwillbechangedto“Gray”.

Output:

Explanation:

“$(“bodydivp”).css(“background-color”,“gray”)”accessesall“p”tapsinsidethe“div”tagwhichlocatesinsidethe“body”tag,andsetsthebackgroundcolorasgray.

“<inputtype=“button”value=“ClickMe”onclick=“changeColor()”/>”runs“changeColor()”whenclickingthebutton.

Exercises

Accesstag,id,class

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>Accesstag,id,class</title>

</head>

<body>

<divid=“idName”>ThisidisidName,sobecomered</div><br>

<div>Herehasnodefinition,sonochangeincolor</div><br>

<divclass=“className”>ThisclassisclassName,sobecomered</div>

<p>Thistagisp,sobecomered</p>

</body>

<scriptsrc=“jquery-1.11.3.js”type=“text/javascript”></script>

<scripttype=“text/javascript”>

$(function(){

$(“p,#idName,.className”).css(“color”,“red”);

});

</script>

</html>

(Figure1)

Pleasesavethefilewithname“Access.html”inthefolderwithjquey-1.11.3.js.Note:makesuretouse“.html”extensionname.Doubleclick“Access.html”file,the“Access.html”willberunbyabrowser,andseetheoutput.(Figure2)

Output:(Figure2asfollowing)

Hour2jQueryFunction

AddaClassTheaddClass()methodisusedtoaddsclasstoeverymatchingelement.

Example2.1

<html>

<head>

<scripttype=“text/javascript”

src=“jquery-1.11.3.js”>

</script>

<scripttype=“text/javascript”>

functionmyFunction(){

$(‘p’).addClass(“redClass”);

}

</script>

<style>

.redClass{

color:red;font-style:italic;

}

</style>

</head>

<body>

<p>PHPin8Hours</p>

<p>JQueryin8Hours</p>

<p>JavaScriptin8Hours</p>

</div>

<form>

<inputtype=“button”value=“Add”

onclick=“myFunction()”></input>

</form>

</body>

</html>

Original:

PHPin8Hours

JQueryin8Hours

JavaScriptin8Hours

Clickonbutton“Add”andseetheresult

Output:

PHPin8Hours

JQueryin8Hours

JavaScriptin8Hours

Explanation

$(‘p’).addClass(“redClass”);accesses“p”tag,addsaclass“redClass”styletospecifiedtext.

“onclick=“myFunction()””executesthe“myFunction()”whenclickingthebutton.

Beforeclickingthelinkthereisnocolorinthetext,butwhenyouclick“Add”,thetextwillappearred.

Add&RemoveClassThetoggleClass()methodisusedtoaddorremoveclassforeveryelementinthematchingselectedelements.

Ifthespecifiedclassismissing,theclasswillbeaddedandifclassisadded,theclasswillberemoved.

Example2.2

<html>

<head>

<scripttype=“text/javascript”

src=“jquery-1.11.3.js”>

</script>

<scripttype=“text/javascript”>

functionmyFunction(){

$(‘p’).toggleClass(“redClass”);

}

</script>

<style>

.redClass{

color:red;font-style:italic;

}

</style>

</head>

<body>

<p>PHPin8Hours</p>

<p>JQueryin8Hours</p>

<p>JavaScriptin8Hours</p>

</div>

<form>

<inputtype=“button”value=“Toggle”

onclick=“myFunction()”></input>

</form>

</body>

</html>

Original:

PHPin8Hours

JQueryin8Hours

JavaScriptin8Hours

Clickonbutton“Toggle”andseetheresult

Output:

PHPin8Hours

JQueryin8Hours

JavaScriptin8Hours

Explanation:

$(‘p’).toggleClass(“redClass”);accesses“p”tag,addsaclass“redClass”whentheclass“redClass”ismissing,orremovestheclass“redClass”whentheclass“redClass”isexisting.

“onclick=“myFunction()””executesthe“myFunction()”whenclickingthebutton.

Beforeclickingthelinkthereisnocolorinthetext,butwhenyouclick“Toggle”,thetextwillappearred.Ifyouclickagain,thecoloroftextwilldisappearagain.

TheSizeofElementThesize()methodreturnsthenumberofelementsmatched.

Example2.3

<html>

<head>

<title>jQuerySizeMethod</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetSize(){

alert(“thesizeofliis:“+$(“li”).size());

}

</script>

</head>

<body>

<inputtype=“button”onclick=“getSize()”value=“Clickheretocheckli”/>

<ul>

<li>Home</li>

<li>Product</li>

<li>AboutUs</li>

</ul>

</body>

</html>

Original:

Clickon“Clickheretocheckli”buttonandseetheresult.

Output:

Explanation:

“$(“li”).size());”accessesthetag“li”,andcountshowmanytags“li”.

onclick=“getSize()”executesthe“getSize()”whenclickingthe“Clickheretocheckli”.

ShowHiddenElementsTheshow()methodisusedtoshowthehiddenelementswhichareselected.

Example2.4

<html>

<head>

<title>jQueryShowMethod</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionshowText(){

$(“#divMsg”).show();

}

</script>

</head>

<body>

<divonclick=“showText()”style=“cursor:pointer;”>

Clickhere.</div>

<divid=“divMsg”style=“background-color:green;display:none;color:white;”>

ThisisTesting……</div>

</body>

</html>

Original:

Clickhere

Clickon“Clickhere”linkandseetheresult.

Output:

Clickhere

ThisisTesting……

Explanation:

$(“#divMsg”).show()accessesthetagwhoseidis“divMsg”,andshowsitshiddencontents.

onclick=“showText()”executesthe“showtext()”whenclicking“Clickhere”.

HideSelectedElements

Thehide()isusedtohidetheelementswhichareselected.

Example2.5

<html>

<head>

<title>jQueryHideMethod</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionhideText(){

$(“#divMsg”).hide();

}

</script>

</head>

<body>

<divonclick=“hideText()”style=“cursor:pointer;”>

Clickhere</div>

<divid=“divMsg”style=“background-color:green;color:white;”>

ThisisTesting…</div>

</body>

</html>

Original:

Clickhere

ThisisTesting……

Clickon“Clickhere”linkandseetheresult.

Output:

Clickhere

Explanation:

“$(“#divMsg”).hide()”accessesthetagwhoseidis“divMsg”andhidesitsselectedtext.

“onclick=“hideText()””executesthe“hideText”whenclicking“Clickhere”.

Afterclicking“Clickhere”,thedivhasbeendisappeared.

Hide&ShowElements“toggle()”switchesbetweenhide()andshow()forthematchingelements.

Example2.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiontoggleEffect(){

$(“#divMsg”).toggle();

}

</script>

</head>

<body>

<divonclick=“toggleEffect()”style=“cursor:pointer;”>Clickhere</div>

<divid=“divMsg”style=“background-color:green;color:white;”>

ThisisTesting…</div>

</body>

</html>

Original:

Clickhere

ThisisTesting……

Clickon“Clickhere”linkandseetheresult.Ifselectedelementisvisiblethenitwillbehidden,andifitishiddenthenitwillbeshown.

Output:

Clickhere

Note:Ifyouclick“Clickhere”again,itwillshowThisisTestingagain.

Explanation:

“$(“#divMsg”).toggle()”accessesthetagwhoseidis“divMsg”,showsthehiddentextorhidestheshowntext.

“onclick=“toggleEffect()””executesthe“toggleEffect()”whenclicking“Clickhere”.

SlideElementUpTheslideUp()methodisusedtoslidethematchedelementupandhideit.

Example2.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionslideUp(){

$(“#divMsg”).slideUp();

}

</script>

</head>

<body>

<divonclick=“slideUp()”style=“cursor:pointer;”>

Clickhere</div>

<divid=“divMsg”style=“background-color:green;color:white;margin-top:10px;

width:120px;height:150px”>

ThisisTesing…</div>

</body>

</html>

Original:

Clickhere

ThisisTesting……

Clickon“Clickhere”linkandseetheresult.

Output:

Clickhere

Note:whenyouclickon“Clickhere”,theThisisTesting……smoothlywillslidefromdowntoupandbehidden.

Explanation:

“$(“#divMsg”).slideUp()”accessesthetagwhoseidis“divMsg”,andslowlyhidesthetextfromdowntoup.

“onclick=“slideUp()””executesthe“slideUp()”whenclicking“Clickhere”.

SlideElementDown

TheslideDown()methodisusedtoslidethematchedelementdownandshowit.

Example2.8

<html>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionslideDown(){

$(“#divMsg”).slideDown();

}

</script>

</head>

<body>

<divonclick=“slideDown()”style=“cursor:pointer;color:red”>

Clickhere</div>

<divid=“divMsg”style=“background-color:green;color:white;margin-top:10px;display:none;width:120px;height:150px”>

ThisisTesing…</div>

</body>

</html>

Original:

Clickhere

Clickon“Clickhere”linkandseetheresult.

Output:

Note:whenyouclickon“Clickhere”,thedivsmoothlywillslidefromuptodownandbeshown.

Explanation:

“$(“#divMsg”).slideDown()”accessesthetagwhoseidis“divMsg”,andslowlyshowsthetextfromuptodown.

“onclick=“slideDown()””executesthe“slideDown()”whenclicking“Clickhere”.

InsertBeforeElementinsertBefore()andbefore()methodsareusedforsametask,insertatextorhtmlcontentbeforethematchingelements.Theirmaindifferenceisonlyinthesyntax.

Example2.9

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioninsertBeforeHtml(){

$(“<divstyle=‘color:green;’>ThistextisinsertedbyinsertBefore()method.</div>”).insertBefore($(“#divInsertBefore”));

$(“#divInsertBefore”).before(“<divstyle=‘color:gray;’>Thistextisinsertedbybefore()method.</div>”);

}

</script>

</head>

<body>

<divid=“divInsertBefore”onclick=“insertBeforeHtml()”style=“cursor:pointer;color:red;”>

Clickhere</div>

</body>

</html>

Original:

Clickhere

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“.insertBefore($(“#divInsertBefore”))”insertsatextbeforethetagwhoseidis“divInsertBefore”.

“$(“#divInsertBefore”).before”insertsatextbeforethetagwhoseidis“divInsertBefore”.

Theirmaindifferenceisonlyinthesyntax.

InsertAfterElementTheinsertAfter()andafter()methodsisusedforthesametask,insertatextorhtmlcontentafterthematchingelements.Theirmajordifferenceisinthesyntax.

Example2.10

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioninsertAfterHtml(){

$(“<divstyle=‘color:green;’>ThistextisinsertedbyinsertAfter()method.</div>”).insertAfter($(“#divInsertAfter”));

$(“#divInsertAfter”).after(“<divstyle=‘color:gray;’>Thistextisinsertedbyafter()method.</div>”);

}

</script>

</head>

<body>

<divid=“divInsertAfter”onclick=“insertAfterHtml()”style=“cursor:pointer;color:red;”>

Clickhere</div>

</body>

</html>

Original:

Clickhere

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“.insertAfter($(“#divInsertAfter”));”insertsatextafterthetagwhoseidis“divInsertAfter”.

“$(“#divInsertAfter”).after”insertsatextafterthetagwhoseidis“divInsertAfter”.

Theirmaindifferenceisonlyinthesyntax.

CheckElementCondition“is()”testsanelementstoseewhetheritmatchesgivencondition.Itreturnstrueorfalse.

Example2.11

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioncheckGender(){

if($(“#chkMale”).is(“:checked”)){

alert(“Maleisselected”);

}

elseif(

$(“#chkFemale”).is(“:checked”)){

alert(“Femaleisselected”);

}}

</script>

</head>

<body>

<divid=“chkGender”onclick=“checkGender()”style=“cursor:pointer;color:red;”>

Clickhere</div>

<inputtype=“radio”id=“chkMale”name=“sex”value=“male”>Male<br>

<inputtype=“radio”id=“chkFemale”name=“sex”value=“female”>Female

</body>

</html>

Original:

Clickhere

○Male

○Female

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

$(“#chkMale”).is(“:checked”)tests“#chkMale”tagtoseeifitischecked.

$(“#chkFemale”).is(“:checked”)tests“#chkFemale”tagtoseeifitischecked.

“onclick=“checkGender()”executes“checkGender”functionwhenclicking“Clickhere”.

HowManyElements?$(“”).lengthcountsthenumberofspecifiedelements.

ThelengthpropertycontainsthenumberofelementsinthejQueryobject.

Example2.12

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioncheckLength(){

alert(“TheNumberofdivsare:”+$(“div”).length);

}

</script>

</head>

<body>

<ponclick=“checkLength()”style=“cursor:pointer;color:red;”>Clickhere</p>

<divstyle=“color:green;”>

Thisisfirstdiv</div>

<divstyle=“color:blue;”>

Thisis2nddiv</div>

<divstyle=“color:green;”>

Thisis3rddiv</div>

<divstyle=“color:blue;”>

Thisis4thdiv</div>

</body>

</html>

Original:

Clickhere

Thisisfirstdiv

Thisis2nddiv

Thisis3rddiv

Thisis4thdiv

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$(“div”).length”accessesthe“div”tag,andcountshowmanyelementsinsidethe“div”.

Exercises

replaceWith()

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>replaceWith</title>

</head>

<scriptsrc=“jquery-1.11.3.js”type=“text/javascript”></script>

<scripttype=“text/javascript”>

functionreplaceWith(){

$(“#replaceWith”).replaceWith(“Hello,thisisanewtext!”);

};

</script>

<body>

<pid=“replaceWith”>

Thistextwillbereplacedwithanewtext</p>

<p>

<inputtype=“button”value=“Relace”onclick=“replaceWith()”>

</p>

</body>

</html>

(Figure1)

Pleasesavethefilewithname“ReplaceWith.html”.

Note:makesuretouse“.html”extensionname.

Doubleclick“ReplaceWith.html”file,the“ReplaceWith.html”willberunbyabrowser,clickthebutton,andseetheoutput.(Figure2)

Original:

Output:

(Figure2)

Explanation:

replaceWith()isusedtoreplaceanexistingtextwithanewtext.

Hour3ElementsSelection

$(document).ready()“$(document).ready()”isusedtospecifyafunctiontoexecuteafterloadingwebpage.

Theeventoccursafterwebpageisloaded.

Example3.1

<html>

<head>

<title>ThisisTestPage</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(document).ready(function(){

alert(“readyfunctioncalled”);

});

</script>

</head>

<body>

<p>Example:</p>

<p>$(document).ready(function(){</p>

<p>……

});

</p>

</body>

</html>

Output:

Explanation:

“$(document).ready(function())”executesthefunctionautomaticallywhenthewebpageisloaded.

$(function(){})$(function(){})doesthesametaskas$(document).ready()functiondoes.

Example3.2

<html>

<head>

<title>ThisisTestPage</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

alert(“readyfunctioncalled”);

});

</script>

</head>

<body>

……

</body>

</html>

Output:

Explanation:

“$(function(){}”runslike“$(document).ready()”.Afterthewebpageisloaded,the“$(function(){}”willrunautomatically.

$(“divtag”)“$(‘divtag’)canaccessalltoplevelchildelementsandallsublevelchildelementsinsidedivtagbytagname.

Example3.3

<Html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetchild(){

alert($(“pspan”).length);

}

</script>

</head>

<body>

<divonclick=“getchild()”style=“cursor:pointer;width:300px;height:20px;color:red;”>

Clickhere

</div>

<p>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild

<spanstyle=“float:left;width:100%;padding:5px;”>Thisissublevelchild</span>

</span>

</p>

</body>

</html>

Original:Clickhere

Thisistoplevelchild

Thisistoplevelchild

Thisistoplevelchild

Thisissublevelchild

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“($(“pspan”).length”accessesalltoplevelchildelements“span”andsublevelchildelements“span”insidethe“p”tag,andcountsthenumberofall“span”elements.

$(“element”).lengthcountsthenumberofelements.

Inaboveexample,youcanseetheresultis4.(lengthofallspanelements).

$(“div>tag”)“$(‘div>tag’)canaccessalltoplevelchildelementsinsidedivtag.Butnotincludingthesublevelchildelements.

Example3.4

<Html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetchild(){

alert($(“p>span”).length);

}

</script>

</head>

<body>

<divonclick=“getchild()”style=“cursor:pointer;width:300px;height:20px;color:red;”>

Clickhere

</div>

<p>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild

<spanstyle=“float:left;width:100%;padding:5px;”>Thisissublevelchild</span>

</span>

</p>

</body>

</html>

Original:Clickhere

Thisistoplevelchild

Thisistoplevelchild

Thisistoplevelchild

Thisissublevelchild

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$(“p>span”).length”accessesalltoplevelchildelements“span”insidethe“p”tag,butnotincludingallsublevelchildelements“span”,andcountsthenumberofalltoplevelchildelements.

$(“element”).lengthcountsthenumberofelements.

Inaboveexample,youcanseetheresultis3(lengthofalltoplevelchild“span”element).

$(“divtag”)&$(“div>tag”)$(“divtag”)willgetthealltop&sub-levelchildelementsinsidethe“div”tag,while$(“div>tag”)willonlygetthealltop-levelelements,notincludingthesub-levelelements.Let’sseethiswithexample.

Example3.5

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetchild(){

alert($(“pspan”).length);

alert($(“p>span”).length);

}

</script>

</head>

<body>

<divonclick=“getchild()”style=“cursor:pointer;width:300px;height:20px;color:red;”>

Clickhere

</div>

<p>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisistoplevelchild

<spanstyle=“float:left;width:100%;padding:5px;”>Thisissublevelchild</span>

</span>

</p>

</body>

</html>

Original:

ClickhereThisistoplevelchild

Thisistoplevelchild

Thisistoplevelchild

Thisissublevelchild

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$(“divtag”)”accessesbothtoplevelandsublevelchildelements.

“$(“div>tag”)”accessesonlytoplevelchildelements,notincludesthesublevelchildelements.

Intheaboveexample,youcanseethefirstcountis4foralltopandsublevelchildelements,andsecondcountis3foralltop-levelchildelementsonly.

$(“tag:contains(text)”)“$(“tag:contains(text)”)”accessesatagthatcontainsaspecified“text”.

Example3.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioncheckContains(){

alert($(“span:contains(‘second’)”).html());

}

</script>

</head>

<body>

<divonclick=“checkContains()”style=“cursor:pointer;width:300px;height:20px;color:red;”>

Clickhere

</div>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisisfirstspan</span>

<spanstyle=“float:left;width:100%;padding:5px;”>Thisissecondspan</span>

</body>

</html>

Original:

Clickhere

Thisisfirstspan

Thisissecondspan

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

$(“span:contains(‘second’)”)accessesthe“span”thatcontainsatext“second”.

“onclick=“checkContains()””runsthecheckContains()whenclickingthe“Clickhere”.

$(“tag[attribute]”)$(“tag[attribute]”)canaccessatagwithaspecifiedattribute.

Example3.7

<html>

<head>

<title>jQuerytagattribute</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetTitle(){

alert($(“div[title]”).html());

}

</script>

</head>

<body>

<inputonclick=“getTitle()”type=“button”value=“ClickHere”style=”color:red;”/>

<divtitle=“Thisistitle”style=“float:left;width:100%”>HelloWorld.Iamdiv</div>

</body>

</html>

Original:

ClickHere

HelloWorld.Iamdiv

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$(“div[title]”).html()”accessesthetag“div”withanattribute“title”,anddisplaysitscontents.

“onclick=“getTitle()”callsthefunction“getTitle()”whenclickingthebutton.

$(“tag[attribute=value]”)“$(“tag[attribute=value]”)”accessesatagby“attribute=value”.

ClickHere

Example3.8

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetHtmlByTitle(){

alert($(“div[title=‘2nd’]”).html());

}

</script>

</head>

<body>

<inputonclick=“getHtmlByTitle()”type=“button”value=“ClickHere”style=“color:red;”/>

<divtitle=“first”style=“float:left;width:100%”>

Thisisfirstdiv</div>

<divtitle=“2nd”style=“float:left;width:100%”>

Thisis2nddiv</div>

</body>

</html>

Original:

Thisisfirstdiv

Thisis2nddiv

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$(“div[title=‘2nd’]”).html()”accessesthetag“div”by“title=2nd”anddisplaysitscontents.

“onclick=“getHtmlByTitle()””callsthefunction“getHtmlByTitle()”whenclickingthebutton.

$(“#id”).is(‘tag’)$(“#id”).is(‘tag’)testsanelementwithaspecifiedidtoseeifitisa“tag”element.Itwillreturntrueiftheelementisa“tag”element.Otherwise,itwillreturnfalse.

Example3.9

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioncheckElementByTag(){

alert($(“#divHello”).is(“div”));

}

</script>

</head>

<body>

<inputonclick=“checkElementByTag()”type=“button”value=“ClickHere”style=“color:red;”/>

<divid=“divHello”style=“float:left;width:100%”>

Helloworld</div>

</body>

</html>

Original:

ClickHere

Helloworld

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$(“#divHello”).is(“div”);”returnstrueiftheelementwithID“#divHello”isa<div>element.

“onclick=“checkElementByTag()”callsthefunction“checkElementByTag()”whenclickingthebutton.

$(“tag:eq(3)”)$(“tag:eq(3)”)accessesatagwithanindexnumber“3”.

:eq()isusedtoselectanelementwithaspecificindexnumber.

Note:indexnumberbeginsfrom0.

Example3.10

<html>

<head>

<title>Jquerytag:eq(3)</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetElementByIndex(){

alert($(“div:eq(3)”).html());

}

</script>

</head>

<body>

<inputonclick=“getElementByIndex()”type=“button”value=“ClickHere”style=“color:red;”/>

<divstyle=“float:left;width:100%”>

Thisisfirstdiv</div>

<divstyle=“float:left;width:100%”>

Thisis2nddiv</div>

<divstyle=“float:left;width:100%”>

Thisis3rddiv</div>

<divstyle=“float:left;width:100%”>

Thisis4thdiv</div>

<divstyle=“float:left;width:100%”>

Thisis5thdiv</div>

</body>

</html>

Original:

ClickHere

Thisisfirstdiv

Thisis2nddiv

Thisis3rddiv

Thisis4thdiv

Thisis5thdiv

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“$”(div:eq(3)”).html()”accessesatag“div”atthepositionofindexnumber“3”,andshowsitscontents.

Note:indexnumberbeginsfrom0.

$(“input:checked”)“$(“input:checked”)”accessesan“input”tagthathasbeenchecked.

The“:checked”selectorusuallyworksforradiobuttons,checkboxes,andselectelements.

Example3.11

<html>

<head>

<title>ThisisTestPage</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functiongetCheckedCount(){

alert($(“input:checked”).length);

}

</script>

</head>

<body>

<inputonclick=“getCheckedCount()”type=“button”value=“ClickHere”style=“color:red;”/>

<inputtype=“checkbox”value=“Apple”checked=“checked”/>Apple

<inputtype=“checkbox”value=“Banana”/>Banana

<inputtype=“checkbox”value=“Peach”checked=“checked”/>Peach

<inputtype=“checkbox”value=“Mango”/>Mango

</body>

</html>

Original:

Clickon“Clickhere”linkandseetheresult.

Output:

Explanation:

“($(“input:checked”).length)”accessesaninputtagwhichhasbeenchecked,andcounthowmanyinputtaghasbeenchecked.

“onclick=“getCheckedCount()””callsthefunction“getCheckedCount()”whenclickingthebutton.

$(“selectoption:selected”)“$(“selectoption:selected”)”accessesa“select”tagwithaselectedoption.

Example3.12

<html>

<head>

<title>Jqueryselectedoption</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetSelectedValue(){

alert($(“selectoption:selected”).text());

}

</script>

</head>

<body>

<inputonclick=“getSelectedValue()”type=“button”value=“ClickHere”style=“color:red;”/>

<select>

<option>First</option>

<optionselected>second</option>

<option>third</option>

</select>

</body>

</html>

Original:

ClickonClickHereandseetheresult.text()showsthecontents.

Output:

Explanation:

“$(“selectoption:selected”).text()”accessesa“select”tagwhoseoptionhasbeenselected,anddisplaysitscontents.

onclick=“getSelectedValue()”callsthefunction“getSelectedValue()”whenclickingthebutton.

Exercises

filter()

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>filter</title>

</head>

<body>

<h3><center>

<p>0</p>

<pid=“study”>1</p>

<pclass=“study”>2</p>

<pclass=“study”>3</p>

<pclass=“study”>4</p>

<pid=“study”>5</p>

</h3></center>

</body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$(“p”).filter(“.study”).css(“color”,“red”);

});

</script>

</html>

(Figure1)

Pleasesavethefilewithname“Filter.html”.

Note:makesuretouse“.html”extensionname.

Doubleclick“Filter.html”file,the“Filter.html”willberunbyabrowser,andseetheoutput.(Figure2)

Original: Output:

(Figure2)

Explanation:

filter()isusedtogetspecifiedelement.

Hour4MoreFunction

attr()Theattr()methodisusedtosettheattributes.Forexample:

Ifyouwanttosetanattributesvaluebyusingtheattr()function,youcanwritethecodelikethis:

$(“img”).attr(“alt”,”Thisisanimage.”).

Ifyouwanttodisabledanelement,thenyoucanwritethecodelikethis:

$(“#elementID”).attr(“disabled”,”disabled”).

Example4.1

<html>

<head>

<title>Jqueryselectedoption</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionsetAttr(){

$(“input:eq(1)”).attr(“disabled”,“disabled”);

}

</script>

</head>

<body>

<inputtype=“button”onclick=“setAttr()”value=“ClickHere”style=“color:red;”/>

<inputtype=“text”value=“HelloWorld”/>

</body>

</html>

Original:

Clickon“Clickhere”linkandseetheresult.

Output:

Intheaboveexample,theHelloWorldtexthasbeendisabled.

Explanation:

“$(“input:eq(1)”)accessesthe“input”tagwhoseindexnumberis1.

“.attr(“disabled”,“disabled”);”setsthe“disabled”property’svalueisdisable.

“onclick=“setAttr()””callsthefunction“setAttr()”whenclickingthebutton.

Note:Theindexnumberbeginsfromzero.

html()Thehtml()methodisusedtogettheHTMLcontentsoftheelementorsettheHTMLcontentsofeverymatchedelement.

Example4.2

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionsetGetHtml(){

alert(“BeforeChangingcontentis:”+$(“#divContent”).html());

$(“#divContent”).html(“Htmlischanged”);

alert(“AfterChangingcontentis:”+$(“#divContent”).html());

}

</script>

</head>

<body>

<inputonclick=“setGetHtml()”type=“button”value=“ClickHere”style=“color:red;”/>

<divid=“divContent”>HelloWorld</div>

</body>

</html>

Original:

ClickHere

HelloWorld

Clickon“Clickhere”buttonandseetheresult.

Output:

Explanation:

Whencallingthefunction“setGetHtml()”,threefollowingcommandswillbeexecuted.

(1)“$(“#divContent”).html());”getsthecontentsfrom“#divContent”.

(2)“$(“#divContent”).html(“Htmlischanged”);”setsthecontents“Htmlischanged”to“divContent”.

(3)“$(“#divContent”).html());”getsthecontentsfrom“#divContent”.

Intheaboveexample,youcanseethe“HelloWorld”textatfirst,butwhenyouclick“ClickHere”,thetext“HelloWorld”hasbeenchangedinto“Htmlischanged”,andtwoalertmessagesareshownrespectively.

text()Thetext()methodisusedtogetthetextoftheelementorsetthetextofeverymatchedelement.

Example4.3

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionsetGetText(){

alert(“BeforeChangingtextis:”+$(“#divContent”).text());

$(“#divContent”).text(“HelloWorldtextischanged”);

alert(“AfterChangingtextis:”+$(“#divContent”).text());

}

</script>

</head>

<body>

<inputonclick=“setGetText()”type=“button”value=“ClickHere”style=“color:red;”/>

<divid=“divContent”>HelloWorldIamtext</div>

</body>

</html>

Original:

ClickHere

HelloWorldIamtext

Clickon“Clickhere”linkandseetheresult

Output:

.

Explanation:

Whencallingthefunction“setGetText()”,threefollowingcommandswillbeexecuted.

(1)“$(“#divContent”).text());”getsthecontentsfrom“#divContent”.

(2)“$(“#divContent”).text(“HelloWorldtextischanged“);”setsthecontents“HelloWorldtextischanged”to“divContent”.

(3)“$(“#divContent”).text());”getsthecontentsfrom“#divContent”.

Intheaboveexampleyoucanseethe“HelloWorldIamtext”atfirst,butwhenyouclick“ClickHere”,thetext“HelloWorldIamtext”hasbeenchangedinto“HelloWorldtextischanged”,andtwoalertmessagesareshownrespectively.

append()append()methodisusedtoaddthevalueattheendofthespecifiedelement.

Example4.4

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functionappendHtml(){

$(“#divContent”).append(“</br>Thisisnewcontent”);

}

</script>

</head>

<body>

<inputonclick=“appendHtml()”type=“button”value=“ClickHere”style=“color:red;”/>

<divid=“divContent”>HelloWorld</div>

</body>

</html>

Original:

Clickon“Clickhere”buttonandseetheresult

Output:

Explanation:

“$(“#divContent”).append(“</br>Thisisnewcontent”);”accessesthetag“#divContent”,andappends“Thisisnewcontent”texttotheendoftheoriginaltext.

Intheaboveexample,youcanseethe“HelloWorld”textatfirst,butwhenyouclick“ClickHere”,the“Thisisnewcontent”texthasbeenappendedattheendoftheoriginaltext“HelloWorld”.

width()Thewidth()methodisusedtogetthewidthofanelement.

Example4.5

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functiongetWidth(){

alert(“Thewidthforthedivis”+$(“#divContent”).width()+“px.”);

}

</script>

<body>

<inputonclick=“getWidth()”type=“button”value=“GetWidth”style=“color:red;”/>

<divid=“divContent”style=“width:200px;”>

HelloWorld

</div>

</body>

</html>

Original:

GetWidth

HelloWorld

Clickon“GetWidth”linkandseetheresult.

Output:

Explanation:

“$(“#divContent”).width()”accessesthe“#divContent”tag,andgetitswidth().

height()Theheight()functionisusedtogettheheightofanelement.

Example4.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functiongetHeight(){

alert(“Theheightforthedivis”+$(“#divContent”).height()+“px.”);

}

</script>

</head>

<body>

<inputonclick=“getHeight()”type=“button”value=“GetHeight”style=“color:red;”/>

<divid=“divContent”style=“width:200px;height:60px;“>

HelloWorld

</div>

</body>

</html>

Original:

GetHeight

HelloWorld

Clickon“GetHeight”linkandseetheresult.

Output:

Explanation:

“$(“#divContent”).height()”accessesthetag“#divContent”,andreturnstheheightoftheelement.

before()Thebefore()methodinsertsspecifiedcontentbeforetheselectedelements.

Example4.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functioninsertContentBefore(){

$(“#divContent”).before(”<div>Thisisnewtext</div>”);

}

</script>

</head>

<body>

<inputonclick=“insertContentBefore()”type=“button”value=“InsertBefore”style=“color:red;”/>

<divid=“divContent”style=“width:200px;height:20px;color:Green;”>

HelloWorld

</div>

</body>

</html>

Original:

Output:

Explanation:

$(“#divContent”).before(”<div>Thisisnewtext</div>”)accessesthetag“#divConent”,andinsertsthetext“Thisisnewtext”beforetheelement.

after()Theafter()methodinsertsspecifiedcontentaftertheselectedelements.

Example4.8

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functioninsertContentAfter(){

$(“#divContent”).after(”<div>Thisisnewtext</div>”);

}

</script>

</head>

<body>

<inputonclick=“insertContentAfter()”type=“button”value=“InsertAfter”style=“color:red;”/>

<divid=“divContent”style=“width:200px;height:20px;color:Green;”>

HelloWorld

</div>

</body>

</html>

Original:

Output:

Explanation:

“$(“#divContent”).after(”<div>Thisisnewtext</div>”);”accessesthetag“#divContent”,andinsertsthetext“Thisisnewtext”aftertheelement.

val()Theval()methodgetsorsetstheattributevalueoftheselectedelements.

Example4.9

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functiongetVal(){

alert($(“#ddlGender”).val());

}

</script>

</head>

<body>

<inputonclick=“getVal()”type=“button”value=“GetVal”style=“color:red;”/>

<selectid=“ddlGender”>

<optionvalue=“Male”>Male</option>

<optionvalue=“Female”>Female</option>

</select>

</body>

</html>

Original:

GetVal Malev

Select“Malev”,andclickon“GetVal”button.

Output:

Explanation:

Select“Malev”,andclickon“GetVal”button.

“$(“#ddlGender”).val();”accessestheelement“#ddlGender”,andreturnitsoptionvalue.

Exercises

slice(start,end-1)

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>Slice()</title>

</head>

<body><h3><center>

<p>0</p>

<p>1</p>

<p>2</p>

<p>3</p>

<p>4</p>

<p>5</p>

</center></h3>

</body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$(“p”).slice(2,5).css(“color”,“red”);

});

</script>

</html>

(Figure1)

Pleasesavethefilewithname“Slice.html”.

Note:makesuretouse“.html”extensionname.

Doubleclick“Slice.html”file,the“Slice.html”willberunbyabrowser,andseetheoutput.(Figure2)

Original: Output:

(Figure2)

Explanation:

slice(start,end-1)isusedtogetspecifiedelementfromstartindextoend-1index.

Note:indexstartswithzero.

Hour5Event

bind(event,function(event){})Thebind()methodisusedtobindtheeventandrunsthefunction.

Aneventrepresentsthepreciseactionwhensomethinghappens.E.g.click,keyup,mouseoverrepresentthreeevents.Movingamouseoveranelement,selectingaradiobuttonandclickingonanelementareexampleofevent.

Example5.1

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

$(document).ready(function(){

$(“#btn”).bind(“click”,function(){

alert(“Userclickedonbutton.”);

});

});

</script>

<body>

<inputid=“btn”type=“button”value=“ClickHere”style=“color:red;”/>

</body>

</html>

Original:

ClickHere

Clickon“GetHere”buttonandseetheresult.

Output:

Explanation:

“$(“#btn”).bind(“click”,function(){}”runsthefunctionwhenclickingthebutton“#btn”.

one(event,function(event){})Theone()methodisusedtobindaneventandrunsthefunctiononlyonce.

Example5.2

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

$(document).ready(function(){

$(“#btnBind”).one(“click”,function(){

alert(“Thiswillbedisplayedonlyonce.”);

});

});

</script>

</head>

<body>

<inputid=“btnBind”type=“button”value=“OneTimeBindEvent”style=“color:red;”/>

</body>

</html>

Original:

OneTimeBindEvent

Clickon“OneTimeBindEvent”buttonandseetheresult.

Output:

Explanation:

“$(“#btnBind”).one(“click”,function(){}”runsthefunctiononlyoncewhenclickingthebutton“#btnBind”.

event(function(){})“event(function(){})”executesthefunctionwhenaneventoccurs.“event”meansclick,mouseOver,keyDown……

Example5.3

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

$(document).ready(function(){

$(“#btnClick”).click(function(){

alert(“IamClickEvent”);

});

$(“#btnMouseOver”).mouseover(function(){

alert(“IamMouseOverEvent”);

});

$(“#btnMouseLeave”).mouseleave(function(){

alert(“IamMouseLeaveEvent”);

});

});

</script>

</head>

<body>

<inputid=“btnClick”type=“button”value=“ClickEvent”style=“color:gray;”/>

<inputid=“btnMouseOver”type=“button”value=“MouseOverEvent”style=“color:gray;”/>

<inputid=“btnMouseLeave”type=“button”value=“MouseLeaveEvent”style=“color:gray;”/>

</body>

</html>

Original:

Takeactionon“ClickEvent”,“MouseOverEvent”and“MouseLeaveEvent”buttonsrespectivelyandseetheresult.

Output:

Explanation:

“$(“#btnClick”).click(function()”runsthefunctionwhenclickingthebutton“#btnClick”.

“$(“#btnMouseOver”).mouseover(function()”runsthefunctionwhenmouseoverthebutton.

“$(“#btnMouseLeave”).mouseleave(function()”runsthefunctionwhenmouseleavethebutton.

event.screenX&event.screenYWecanuse“event.screenX”and“event.screenY”togetthecoordinatesofthemousepointer,relativetothescreen,whenthemouseisclickedonanelement.

Example5.4

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functiongetCordinates(){

varx=event.screenX;vary=event.screenY;

alert(“Xcoords:”+x+“,Ycoords:”+y);

}

</script>

</head>

<bodyonmousedown=“getCordinates()”><br><br>

<center><h3>Pleaseclickanywhereinwebpage.</h3></center>

</body>

</html>

Original:

Pleaseclickanywhereinwebpage.

Output:

Explanation:

“event.screenX;”returnsthexcoordinaterelativetothescreen.

“event.screenY;”returnstheycoordinaterelativetothescreen.

event.pageX&event.pageYThe“event.pageX”and“event.pageY”propertiesusedtogetthepositionofthemousepointer,relativetotheleftandtopedgeofthedocumentrespectively.

Example5.5

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

$(document).ready(function(){

$(document).mousemove(function(event){

varx=event.pageX;vary=event.pageY;

$(“span”).text(“pageX:”+x+“,pageY:”+y);

});

});

</script>

</head>

<body>

<br><br><center>

<p>ThePositionofMouseisat:<span></span></p>

</center>

</body>

</html>

Original:ThePositionofMouseisat:

Pleasemovemouseonthepageyouwillseethemagic.

Output:

Explanation:

“event.pageX;”returnsthexcoordinaterelativetothedocument.

“event.pageY;”returnstheycoordinaterelativetothedocument.

event.keyCode“event.keyCode”returnstheUnicodevalueofanon-characterkeyinakeyPressevent.

Example5.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

functiongetChar(event){

alert(“keycodeis:”+event.keyCode);

}

</script>

</head>

<body>

<br><br>

<center>

Pleasetypealetterintextbox:<br><br>

<inputtype=”text”onkeydown=“getChar(event);”/>

</center>

</body>

</html>

Original:

Inputaletter“j”inthetextfieldandseetheresult.

Output:

Explanation:

Wheninputaletter“j”intotextfield,aneventoccurs,andreturnsamessage“keycodeis:74”

“event.keyCode”returnstheUnicodevalueofanon-characterkeyinakeyPressevent.

hover(over,out)The“hover(over,out)”bindshandlersforbothmouseEnterandmouseLeaveevents.

Example5.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/JavaScript”>

$(document).ready(function(){

$(‘div’).hover(

function(){

$(this).css({“background-color”:“red”});

}

);

});

</script>

</head>

<body>

<divclass=“div”style=“background-color:green;margin:10px;padding:12px;border:2pxsolid#666;width:200px;“>

MouseMoveHere

</div>

</body>

</html>

Original:

MovetheMouseon“MouserMoveHere”DivYouwillseethecolorofdivwouldbechangedfromgreentored.

Output:

Explanation:

“$(‘div’).hover(function()”runsthefunctionwhenmousehoversabovethetag“div”.

“$(this).css({“background-color”:“red”}”accessesthe“div”,andsetsacssstyle.“this”represents“div”.

Exercises

toggle(function());

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>Toggle</title>

</head>

<body><br>

<inputtype=“button”value=“Toggle”

onclick=“myFunction()”/>

Pleaseclickthebutton.

<pid=“content”>

Thistextwillbeshownandhidden.</p>

</body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionmyFunction(){

$(“#content”).toggle(function(){

});

};

</script>

</html>

(Figure1)

Pleasesavethefilewithname“Toggle.html”.

Note:makesuretouse“.html”extensionname.

Doubleclick“Toggle.html”file,the“Toggle.html”willberunbyabrowser,clickthebutton,andseetheoutput.(Figure2)

Output:

(Figure2)

Explanation:

toggle()functionisusedtoswitchdifferentactions.

Hour6Effects&Animation

show(duration,callback)The“show(duration,callback)”showselementwithduration.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedaftertheshow()methodiscompleted.

slow 600milliseconds

normal 400milliseconds

fast 200milliseconds

Example6.1

<html>

<head>

<title>jQueryshowMethodwithdurationandcallbackparameters</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(document).ready(function(){

$(“#btnShow”).click(function(){

$(“p”).show(“slow”,function(){

alert(“Iamcallafterparagraphfullyshown”);

});

});

});

</script>

</head>

<body>

<inputtype=“button”id=“btnShow”value=“ShowMe”/>

<pstyle=“display:none”>

Thisisaparagraph</p>

</body>

</html>

Original:

Clickon“ShowMe”buttonsandseetheresult.“Thisisaparagraph”willbeshown.

Output:

Explanation:

“$(“#btnShow”).click(function()”runsthefunctionwhenclickingthebuttonwhoseidis“#btnShow”.

“$(“p”).show(“slow”,function()”accessesthetag“p”,showsitscontents“Thisisaparagraph”slowly,andrunsthefunction,returnsanalertmessage“Iamcallafterparagraphfullyshown”.

hide(duration,callback)The“hide(duration,callback)”hideselementwithduration.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunctionwhichisexecutedaftercompletingthehide()method.

slow 600milliseconds

normal 400milliseconds

fast 200milliseconds

Example6.2

<html>

<head>

<title>jQueryhideMethodwithdurationandcallbackparameters</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(document).ready(function(){

$(“#btnHide”).click(function(){

$(“p”).hide(“slow”,function(){

alert(“Iamcallafterparagraphfullyhidden”);

});

});

});

</script>

</head>

<body>

<inputtype=“button”id=“btnHide”value=“HideMe”/>

<p>Thisisaparagraph</p>

</body>

</html>

Original:

Clickon“HideMe”buttonandseetheresult.“Thisisaparagraph”willbehidden.

Output:

HideMe

Youcannotsee“Thisisaparagraph”now.

Explanation:

“$(“#btnHide”).click(function()”runsthefunctionwhenclickingthebuttonwhoseidis“#btnHide”.

“$(“p”).hide(“slow”,function()”accessesthetag“p”,hidesitscontents“Thisisaparagraph”slowly,andrunsthefunction,returnsanalertmessage“Iamcallafterparagraphfullyhidden”.

toggle(duration,callback)The“toggle(duration,callback)”togglesbetweenhide()andshow()elements.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedafterthetoggle()methodiscompleted.

Example6.3

<html>

<head>

<title>jQueryhideMethodwithdurationandcallbackparameters</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiontoggleEffect(){

$(“#divMsg”).toggle(“fast”,function(){

alert(“Thetogglemethodiscompleted!”);});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“toggleEffect();”value=“Togglebetweenhideandshow”/></div>

<divid=“divMsg”style=“background-color:green;color:white;width:200px;height:200px;”>

Iamdiv</div>

</body>

</html>

Original:

Clickon“Togglebetweenhideandshow”buttonandseetheresult.

Output:

Whenyoukeepclickingthebutton,message“Iamdiv”willshowandhidealternately.

Explanation:

“$(“#divMsg”).toggle(“fast”,function()”accessesthetag“#divMsg”,showsandhidesitscontents“Iamdiv”fast,andrunsthefunction,returnsanalertmessage“Thetogglemethod()iscompleted!”.

fadeOut(duration,callback)ThefadeOut(duration,callback)changestheopacityforselectedelements,fromvisibletohidden.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedafterthefadeOut()methodiscompleted.

Example6.4

<html>

<head>

<title>jQueryhideMethodwithdurationandcallbackparameters</title>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionfadeOutDiv(){

$(“#divMsg”).fadeOut(500,function(){

alert(“ThefadeOutmethodiscompleted!”);});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“fadeOutDiv();”value=“FadeOutDiv”/></div>

<divid=“divMsg”style=“background-color:maroon;color:white;width:200px;height:200px;”>

Iamdiv</div>

</body>

</html>

Original:

Note:fadeOut(500,callback),500millisecondsisaduration.

Clickon“FadeOutDiv”buttonandseetheresult.“Iamdiv”willfadeout.

Output:

Explanation:

“$(“#divMsg”).fadeOut(500,function()”accessesthetag“#divMsg”,fadesoutitscontents“Iamdiv”in500milliseconds,andrunsthefunction,returnsanalertmessage“Thefadeoutmethodiscompleted!”.

fadeIn(duration,callback)ThefadeIn(duration,callback)changestheopacityforselectingelements,fromhiddentovisible.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedafterthefadeIn()methodiscompleted.

Example6.5

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionfadeInDiv(){

$(“#divMsg”).fadeIn(500,function(){

alert(“ThefadeInmethodiscompleted!”);});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“fadeInDiv();”value=“FadeInDiv”/></div>

<divid=“divMsg”style=“background-color:maroon;color:white;width:200px;height:200px;

display:none;”>

Iamdiv</div>

</body>

</html>

Note:fadeIn(500,callback),500millisecondsisaduration.

Original:

Clickon“FadeInDiv”buttonandseetheresult.“Iamdiv”willfadein.

Output:

Explanation:

“$(“#divMsg”).fadeIn(500,function()”accessesthetag“#divMsg”,fadesinitscontents“Iamdiv”in500milliseconds,andrunsthefunction,returnsanalertmessage“ThefadeInmethodiscompleted!”.

slideUp(duration,callback)TheslideUp(duration,callback)isusedtoslidethematchedelementupbyhiding.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedaftertheslideUp()methodiscompleted.

SlideUpDiv

Example6.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionslideUpDiv(){

$(“#divMsg”).slideUp(500,function(){

alert(“TheslideUpmethodiscompleted!”);});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“slideUpDiv();”value=“slideUpDiv”/></div>

<divid=“divMsg”style=“background-color:maroon;color:white;width:200px;height:200px;”>

Iamdiv</div>

</body>

</html>

Original:

Clickon“slideUpDiv”buttonandseetheresult.“Iamdiv”willslideup.

SlideUpDiv

Output:

Explanation:

“$(“#divMsg”).slideUp(500,function()”accessesthetag“#divMsg”,slidesupitscontents“Iamdiv”in500milliseconds,andrunsthefunction,returnsanalertmessage“TheslideUpmethodiscompleted!”.

slideDown(duration,callback)TheslideDown(duration,callback)isusedtoslidethematchedelementdownbyshowing.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isfunction,whichisexecutedaftertheslideDown()methodiscompleted.

Example6.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionslideDownDiv(){

$(“#divMsg”).slideDown(500,function(){

alert(“TheslideDownmethodiscompleted!”);});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“slideDownDiv();”value=“slideDownDiv”/></div>

<divid=“divMsg”style=“background-color:maroon;color:white;width:200px;height:200px;

display:none;”>

Iamdiv</div>

</body>

</html>

Original:

Clickon“slideDownDiv”buttonandseetheresult.

Output:

Explanation:

“$(“#divMsg”).slideDown(500,function()”accessesthetag“#divMsg”,slidesdownitscontents“Iamdiv”in500milliseconds,andrunsthefunction,returnsanalertmessage“TheslideDownmethodiscompleted!”.

slideToggle(duration,callback)TheslideToggle(duration,callback)worksbetweenslideUp()andslideDown()fortheselectedelements.Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansettimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedaftertheslideToggle()methodiscompleted.

Example6.8

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionslideToggleDiv(){

$(“#divMsg”).slideToggle(500,function(){

alert(“TheslideTogglemethodiscompleted!”);});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“slideToggleDiv();”value=“slideToggleDiv”/></div>

<divid=“divMsg”style=“background-color:green;color:white;width:200px;height:200px;”>

Iamdiv</div>

</body>

</html>

Original:

Clickon“slideToggle Div”buttonandseetheresult.

Output:

Clickon“slideToggle Div”buttonandseetheresult.

Explanation:

“$(“#divMsg”).slideToggle(500,function()”accessesthetag“#divMsg”,slidesupandslidesdownitscontents“Iamdiv”in500milliseconds,andrunsthefunction,returnsanalertmessage“TheslideTogglemethodiscompleted!”

Intheaboveexample,whenyoukeepclickingthebutton“slideToggleDiv”,thetext“IamDiv”willslideupandslidedownalternately.

fadeTo(duration,opacity)

ThefadeTo(duration,opacity)methodgraduallychangestheopacityforselectedelementstoaspecifiedopacity(fadingeffect).Ithastwooptionalparameters(duration,callback).Thefirstparameter“duration”isaspeed(slow,normal,fast)oryoucansetatimeinmilliseconds.Thesecondparameter“callback”isafunction,whichisexecutedafterthefadeTo()methodiscompleted.

Opacityvalue:from1(opaque)to0(transparent).

Example6.9

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionfadeToDiv(){

$(“#divMsg”).fadeTo(2000,0.3);

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“fadeToDiv();”value=“fadeToDiv”/></div><br/>

<divid=“divMsg”style=“background-color:green;color:white;width:200px;height:200px;”>

Iamdiv</div>

</body>

</html>

Original:

Clickon“fadeTo Div”buttonandseetheresult.

Output:

fadeToDiv

Explanation:

“$(“#divMsg”).fadeTo(2000,0.3)”accessesthetag“divMsg”,fadesitscontents“Iamdiv”totheopacityvalue0.3in2000milliseconds.

Opacityvalue:from1(opaque)to0(transparent).

animate()

animate(“width,height,opacity,fontSize,opposition”,duration,callback)

Theanimate(arguments)methodisusedtocreatecustomizedanimations.The“width,height,opacity,fontSize,opposition”parametersdefinetheCSSpropertiestobeanimated.Theparameter“duration”hasthreepossiblevalues:Slow,Normal,Fast,oryoucansetthetimeinmilliseconds.Theparameter“callback”isafunction,whichisexecutedaftertheanimationcompletes.

Example6.10

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionanimateDiv(){

$(“#divMsg”).animate({

width:‘350px’,height:‘350px’,opacity:‘0.5’,fontSize:‘3em’,left:‘450px’},‘slow’,function(){

alert(“Theanimatemethodiscompleted!”)}

);}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“animateDiv();”value=“animatetoDiv”/></div>

<br/>

<divid=“divMsg”style=“background:green;height:200px;width:200px;position:absolute;”>

Iamdivwithsomecustomanimation

</div>

</body>

</html>

Original:

Clickon“animatetoDiv”buttonandseetheresult.

Output:

animatetoDiv

Explanation:

“$(“#divMsg”).animate({width:‘350px’,height:‘350px’,opacity:‘0.5’,fontSize:‘3em’,left:‘450px’},‘slow’,function()”accessesthetag“#divMsg”,showsacustomizedanimationwithspecifiedsize,opacity,font,oppositionandduration.Atlast,runsthefunctionanddisplaysanalertmessage“Theanimationmethodiscompleted!”.

Exercises

animate();

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>Animation</title>

<styletype=“text/css”>

#panel{position:relative;width:100px;height:100px;border:1pxsolid#000000;background:yellow;cursor:pointer}

</style>

<scriptsrc=“jquery-1.11.3.js”type=“text/javascript”></script>

<scripttype=“text/javascript”>

$(function(){

$(“#panel”).css(“opacity”,“0.8”);

$(“#panel”).click(function(){

$(this).animate({left:“400px”,height:“200px”,opacity:“1”},3000)

.animate({top:“200px”,width:“200px”},3000)

.animate({left:“1px”,top:“1px”,width:“200”,height:“200”},3000)

.fadeOut(“slow”);

});

});

</script>

</head>

<body>

<divid=“panel”><br><br><center>ClickMe!</center></div>

</body>

</html>

(Figure1)

Pleasesavethefilewithname“Animate.html”.

Note:makesuretouse“.html”extensionname.

Doubleclick“Animate.html”file,the“Animate.html”willberunbyabrowser,clickthepanel,andseetheoutput.

(Figure2)

Output:

(Figure2)

Explanation:

animate()functionisusedtocreateacustomizedanimationwithjQuery.

Hour7UtilityFunctions

$.each()$(“tag”).each(function())accessesaspecifiedtag,andrepeatedlyexecutesthefunction.

Example7.1

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionloopWithEach(){

$(“ulli”).each(function(){

$(this).css(“color”,“red”);

});

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“loopWithEach();”value=“ClickHere”/>

</div>

<ul>

<li>First</li>

<li>Second</li>

<li>Third</li>

</ul>

</body>

</html>

Original:

Clickon“ClickHere”buttonandseetheresult.

Output:

Explanation:

“$(“ulli”).each(function()”accessesthetag“li”insidethe“ul”,andexecutesthefunctionrepeatedly.

“$(this).css(“color”,“red”)”accessesthe“this”objectwhichrepresentstag“li”,andsetsacssstyle.

Whenyouclickon“ClickHere”button,thecolorofallthreeelementsarechangedtoredbecauseeach()methodaccessesallelementsonebyone.each()methodworkslikealoop.

$.makeArray()$.makeArray(object)createsanarray.

$.makeArray(object)isjQueryutilitymethodwhichreturnsJavaScriptarraycreatedbyanarray-likeobject.

Example7.2

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functionmakeArray(){

varobj=$(“li”);

varmyArray=$.makeArray(obj);

myArray.reverse();

$(“ul”).html(myArray);

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“makeArray();”value=“ClickHere”/>

</div>

<ulstyle=“color:black;font-weight:bold;”>

<li>One</li>

<li>Two</li>

<li>Three</li>

<li>Four</li>

<li>Five</li>

</ul>

</body>

</html>

Original:

Clickon“ClickHere”buttonandseetheresult.reverse()willmakeitsobjectreversed.Outputwillshow5,4,3,2,1.

Output:

Explanation:

“varobj=$(“li”);”createsanobjectfortag“li”.

“varmyArray=$.makeArray(obj)”createsanarrayfortheelementsof“li”.

“$(“ul”).html(myArray);”accessesthetag“ul”,anddisplayselementof“myArray”.

“myArray.reverse();”reversesallelementsin“myArray”.

Whenyouclickedon“ClickHere”buttonthe“li”elementsvalueswillbereversed.

$.isArray()$.isArray(array)usedtocheckwhethertheargumentisanarrayornot.ItreturnsBooleanvalue“True”or“False”.Let`stakeanexampleforclarification.

Example7.3

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioncheckArray(){

vara=[];

varb=[1,2,3];

varc=“Iamstring”;

alert(‘aisanarray?‘+$.isArray(a));

alert(‘bisanarray?‘+$.isArray(b));

alert(‘cisanarray?‘+$.isArray(c));

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“checkArray();”value=“CheckArray”/>

</div>

</body>

</html>

Original:

Clickon“CheckArray”buttonandseetheresult.

Output:

Explanation:

“$.isArray(a)”checksthearray“a”toseeifitisanarray.

Whenyouclickon“CheckArray”button,thefirstandsecondalertboxreturnstruevalueswhilethirdalertboxreturnsfalsevalue.

$.inArray()$.inArray()searchesforaspecifiedvaluewithinanarrayandreturnsitsindexnumber.Ifthespecifiedvaluedoesnotexistinthearray,itreturns-1.

Example7.4

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functioncheckArray(){

varmyArray=[“Pete”,“John”,“Andy”];

$(“#spnPosition”).html($.inArray(“John”,myArray));

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“checkArray();”value=“checkArrayPosition”/>

</div>

<span>Johnisatposition:</span>

<br/>

<spanid=“spnPosition”></span>

</body>

</html>

Original:

Clickon“CheckArrayPosition”buttonandseetheresult.

Output:

Explanation:

Youcanseetheresultis“1”.

“$(“#spnPosition”)”accessestheelement“#spnPosition”.

“.html(text);”displaysthetextatspecifiedpositon.

“$.inArray(“John”,myArray)”returnstheindexnumberof“John”inmyArray.

$.grep()$.grep(array,function(values,index))

$.grep(…)methodcreatesanewarraybyfilteringexistingarray.

Parameter“array”:existingarrayname.

Parameter“values”:theelements’valueinexistingarray.

Parameter“index”:theindexnumberinexistingarray

Note:Theexistingarrayisnotaffected.

Example7.5

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongrepFunc(){

varoldArray=[1,5,3,8,6,7,9,11,15,13];

newArray=$.grep(oldArray,function(n,i){

return(n!==15&&i>3);

//oldArrayrepresentstheexistingarrayname

//nrepresentstheelements’valueofoldArray

//irepresentstheindexnumberofoldArray

});

$(“#grepValues”).html(newArray.join(“,“));

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“grepFunc();”value=“ClickHere”/>

</div>

<divstyle=“padding:5px;”>

Valuesbeforegrep:<spanstyle=“color:green;”>1,5,3,8,6,7,9,11,15,13</span>

</div>

<divstyle=“padding:5px;”>

Valuesaftergrep:<spanid=“grepValues”style=“color:red;”></span>

</div>

</body>

</html>

Original:

Clickon“ClickHere”buttonandseetheresult.

Output:

Explanation:

“newArray=$.grep(…)”createsanewarraybyfilteringanexistingarray.

“n!==15&&i>3”filtersanexistingarraybyalogicalexpression:elements’valuecannotbe15andindexnumbermustbegreaterthan3.

“$(“#grepValues”).html()”accessesthetag“#grepValues”,andshowstheelements’valueofnewarrayinhere.

“newArray.join(“,“)”joinstheelements’valuewith“,”.

$.unique()The$.unique()functionremovesduplicatevaluesinanarray.Itreturnsuniqueelementvaluesinthearray.

Example7.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

functiongetUniqueValues(){

varmyArr=[2,5,5,7,7,8];

alert(“BeforeusinguniqueMethod:“+myArr);

myArr=$.unique(myArr);//removeduplicatevalues

varval=””;

for(vari=0;i<myArr.length;i++){

val+=myArr[i]+“,”;//getalluniquevalues

}

val=val.slice(0,-1)//removelastcomma

alert(“AfterusinguniqueMethod:“+val);

}

</script>

</head>

<body>

<div>

<inputtype=“button”onclick=“getUniqueValues();”value=“ClickHere”/>

</div>

</body>

</html>

Original:

Clickon“ClickHere”buttonandseetheresult.

Output:

Explanation:

“myArr=$.unique(myArr);”removesduplicateelementvaluesinmyArr.

“array.slice(m,n)”returnselementsvaluefrommton-1.Butif“n”is-1,removesthelastelementvalue.

$.trim()Thetrim()methodremoveswhitespaceatthebeginningandattheendofastring.

Example7.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(document).ready(function(){

varstr=“HelloWorld!“;

$(“#afterTrim”).html(“Aftertrim:”+$.trim(str));

});

</script>

</head>

<body>

<div>

OriginalString:&nbsp;&nbsp;&nbsp;Hello&nbsp;&nbsp;&nbsp;World!</div>

<divid=“afterTrim”>

</div>

</body>

</html>

Original:

OriginalString:HelloWorld!

Runthebrowser,youwillseetheresult.

Output:

Explanation:

“$.trim(str)”trimsthewhitespaceatthebeginningandattheendofthestring“str”.

Exercises

replaceAll();

OpenNotepad,writejQuerycodes(Figure1):

<html>

<head>

<title>test</title>

</head>

<body>

<br>

<inputtype=“button”value=“ReplaceAll”

onclick=“myFunction()”/><br>

<pid=“replaceAll”>

Thisisanoriginaltext,</p>

<pid=“replaceAll”>whichwillbereplacedbyanewtext.</p>

</body>

<scriptsrc=“jquery-1.11.3.js”type=“text/javascript”></script>

<scripttype=“text/javascript”>

functionmyFunction(){

$(“<br><div><strong>Thisisnewtext.Updated!</strong></div>”)

.replaceAll(“#replaceAll”);

};

</script>

</html>

(Figure1)

Pleasesavethefilewithname“ReplaceAll.html”.

Note:makesuretouse“.html”extensionname.

Doubleclick“ReplaceAll.html”file,the“ReplaceAll.html”willberunbyabrowser,clickthebuttonfortwotimes,andseetheoutput.(Figure2)

Original:

Output:

(Figure2)

Explanation:

replaceAll()functionisusedtoreplaceanexistingwholetextwithanewtext.

Hour8AjaxbyjQuery

WhatisAjax?AJAXstandsfor“AsynchronousJavaScriptAndXML”.AJAXisanewtechniqueforcreatingbetter,faster,andmoreinteractivewebscriptswithXML,HTML,CSS,PHP,ASPandJavaScriptbytheserver.

AJAXisusedtoupdatepartsofawebpage,withoutreloadingthewholepage.

ThatmeanswithAjax,youcancommunicatewiththeservertorenewtheinformation,withoutrefreshingthewebpage.

ByjQuery,youcaneasilyimplementAjaxinyourwebpages.

TorunAjax,youneedaserver.

SetupServer

IfyouwanttorunAjax,youneedtosetupaserverinyourowncomputer.

“AppServ”isfreesoftwaretosetupaserver;itcanrunApache,PHP,MySQL,PhpMyAdmin,Ajax,JavaScript,JQuery……

Step1:

Download“AppServ”formlink:(Figure1)

http://www.appservnetwork.com/

(Figure1)

Step2:

InstallAppServtolocalcomputer.

C:\AppServ

(Figure2)

(Figure2)

Step3:

Pleasecheckallboxtoinstallanything.(Figure3)

(Figure3)

Step4:

ServerName:localhost

EmailAddress:xxxxxxxx@xxxxx.xxx

ApacheHTTPPort:80(Figure4)

(Figure4)

Step5:

Enterrootpassword:12345(Figure5)

(Defaultusername:root)

(Figure5)

Step6:

Checkthebox,StartApache,StartMySQL

ClickFinishbutton.(Figure6)

(Figure6)

Step7:

TesttoseeifAppServinstallationissuccessful,pleaserunabrowser,entertheaddress:

http://localhost

Ifyoucanseethepagelikethis:(Figure7)

(Figure7)

Congratulation!Yourownserverrunssuccessfully.

Step8:

Howtouseserver?

OpenfolderC:\AppServ\www,pleasecreateafoldernamed“myServer”,whichcanworkasaworkplace.Youcanputallyouprogramfilesto“myServer”folder.Fromnowon,youareabletorunAjaxfiles,PHPfilesandHTMLfilesonC:\AppServ\www\myServer.(Figure8)

(Figure8)

Note:

Pleaseuse“http://localhost/……“torunanyfilesontheserver,forexample:

IfyouwanttorunAjaxEvent.html,enteraddress:

http://localhost/myServer/AjaxEven.html

IfyouwanttorunResponse.php,enteraddress:

http://localhost/myServer/Response.php

load()

load()canremotelyloadtheresourcefilefromtheserver,anddisplaysthedownloadeddata.

load(url,data,function)

Argument“url”isaresourcefileontheserver.

Argument“data”sendsdata{key:value}toserver.(optional)

Argument“function”willrunwhentheAjaxoperationiscomplete.(optional)

Example8.1

(1)Aresourcefileisontheserver:(myFile.txt)

(C:\AppServ\www\myServer\myFile.txt)

Hello!Ajaxistesting!

(2)jQueryfileisontheserver:(loadText.html)

(C:\AppServ\www\myServer\loadText.html)

<html>

<head>

<body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$(“div”).load(“myFile.txt”);

});

</script>

</head>

<br>Respond:<br><br><div></div>

</body>

</html>

(3)jquery-1.11.3.jsisontheserver.

(C:\AppServ\www\myServer\jquery-1.11.3.js)

RuntheloadText.htmlbyaddress:

http://localhost/myServer/loadText.html

Output:

Respond:

Hello!Ajaxistesting!

Explanation:

“$(function(){}”executesthefunctionwhenloadTest.htmlisloaded.

“$(“div”).load(“myFile.txt”);”loadsthe“myFile.txt”anddisplayitscontentsintag“div”ofloadTest.html.

Note:

“jquery-1.11.3.js”,“myFirst.txt”and“loadText.html”shouldbeputinthesamefolder.

IfyouwanttoknowmoreaboutAjax,you‘dbetterlearnoneofthelanguagessuchasPHP,ASPandJSPfirst.

$.post()

$.post()cansenddatatotheserver.

$.post(url,data,function)

Argument“url”isaresourcefileontheserver.

Argument“data”sendsdata{key:value}toserver.

Argument“function”willrunwhentheAjaxoperationiscomplete.

Example8.2

(1)Aresourcefileontheserver:(postFile.php)

(C:\AppServ\www\myServer\postFile.php)

<html>

<body>

<?php

if($_POST[“data”]==“100”){echo(“100”);}

?>

</body>

</html>

(2)jQueryfile:(postTest.html)

(C:\AppServ\www\myServer\postTest.html)

<html>

<body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$.post(“postFile.php”,{data:100},function(data){

$(“div”).html(data);

});});

</script>

Respond:

<div></div>

</body>

</html>

(3)jquery-1.11.3.jsisontheserver.

(C:\AppServ\www\myServer\jquery-1.11.3.js)

RunthepostTest.htmlbyaddress:

http://localhost/myServer/postTest.html

Output:

Respond:

100

Explanation:

“if($_POST[“data”]==“100”)teststhereceiveddatatoseeifitequals100.

“echo“100”;”displays100.

“{data:100}”sendsthe“data:100”totheserver.

“function(data)”isacallbackfunctionwhichwillrunwhentheajaxoperationiscomplete.

“$(“div”).html(data);”displaysthe“data”inthetag“div”ofpostTest.html.

Note:

postFile.phpandpostTest.htmlshouldbeputinthesamefolder.

$.get()

$.get()cansenddatatotheserver.

$.get(url,data,function)

Argument“url”isaresourcefileontheserver.

Argument“data”sendsdata{key:value}toserver.

Argument“function”willrunwhentheAjaxoperationiscomplete.

Example8.3

(1)Aresourcefileontheserver:(getFile.php)

(C:\AppServ\www\myServer\getFile.php)

<html>

<body>

<?php

if($_GET[“data”]==“100”){echo(“100”);}

?>

</body>

</html>

(2)jQueryfile:(getTest.html)

(C:\AppServ\www\myServer\getTest.html)

<html>

<body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$.get(“getFile.php”,{data:100},function(data){

$(“div”).html(data);

});});

</script>

Respond:

<div></div>

</body>

</html>

(3)jquery-1.11.3.jsisontheserver.

(C:\AppServ\www\myServer\jquery-1.11.3.js)

RunthegetTest.htmlbyaddress:

http://localhost/myServer/getTest.html

Output:

Respond:

100

Explanation:

“if($_GET[“data”]==“100”)teststhereceiveddatatoseeifitequals100.

“echo“100”;”displays100.

“{data:100}”sendsthe“data:100”totheserver.

“function(data)”isacallbackfunctionwhichwillrunwhentheajaxoperationiscomplete.

“$(“div”).html(data);”displaysthe“data”inthetag“div”ofgetTest.html.

$.ajax()withpostmethod

$.ajax()cancommunicateswiththeserver,andreplacestheload(),$.post(),$.get().

$.ajax({

type:“GET”or“POST”,

url:“sourcefile”,

data:{key:value}

success:function(data){}

});

Argument“GET/POST”isthehttprequesttype.

Argument“url”isaresourcefileontheserver.

Argument“data”sendsdata{key:value}toserver.

Argument“function”willrunwhentheAjaxoperationissuccessful.

Example8.4

(1)Aresourcefileontheserver:(postFile.php)

(C:\AppServ\www\myServer\postFile.php)

<html>

<body>

<?php

if($_POST[“data”]==“100”){echo(“100”);}

?>

</body>

</html>

(2)jQueryfile:(postAjax.html)

(C:\AppServ\www\myServer\postAjax.html)

<html>

<body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$.ajax({

type:“POST”,

url:“postFile.php”,//loadpostFile.php

data:{data:100},

success:function(data){

$(“div”).html(data);//showdatain“div”

}

});});

</script>

Respond:

<div></div>

</body>

</html>

(3)jquery-1.11.3.jsisontheserver.

(C:\AppServ\www\myServer\jquery-1.11.3.js)

RunthepostAjax.htmlbyaddress:

http://localhost/myServer/postAjax.html

Output:

Respond:

100

Explanation:

$.ajax()communicateswiththeserverusingPOSTmethod.

$.ajax()withgetmethod

$.ajax()cancommunicateswiththeserver,andreplacestheload(),$.post(),$.get().

$.ajax({

type:“GET”or“POST”,

url:“sourcefile”,

data:{key:value}

success:function(data){}

});

Argument“GET/POST”isthehttprequesttype.

Argument“url”isaresourcefileontheserver.

Argument“data”sendsdata{key:value}toserver.

Argument“function”willrunwhentheAjaxoperationissuccessful.

Example8.5

(1)Aresourcefileontheserver:(getFile.php)\

(C:\AppServ\www\myServer\getFile.php)

<html>

<body>

<?php

if($_GET[“data”]==“100”){echo(“100”);}

?>

</body>

</html>

(2)jQueryfile:(getAjax.html)

(C:\AppServ\www\myServer\getAjax.html)

<html>

<body>

<scriptsrc=“jquery-1.11.3.js”></script>

<scripttype=“text/javascript”>

$(function(){

$.ajax({

type:“get”,

url:“getFile.php”,//loadgetFile.php

data:{data:100},

success:function(data){

$(“div”).html(data);//showdatain“div”

}

});});

</script>

Respond:

<div></div>

</body>

</html>

(3)jquery-1.11.3.jsisontheserver.

(C:\AppServ\www\myServer\jquery-1.11.3.js)

RunthegetAjax.htmlbyaddress:

http://localhost/myServer/getAjax.html

Output:

Respond:

100

Explanation:

$.ajax()communicateswiththeserverusingGETmethod.

AjaxError

$.ajax()canhandleerrorswithacallbackfunction.

$.ajax({

type:“GET”or“POST”,

url:“sourcefile”,

data:{key:value}

error:function(xhr,message,e){}

});

“xhr”representsaXMLHttpRequestObject.

“message”representsaerrormessage.

“e”isanexceptionobject.

Example8.6

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<script>

$(document).ready(function(){

$.ajax({

type:“GET”,

url:“noFile.txt”,//wrongfile

success:suss,

error:err

});

});

functionsuss(data)

{

$(“div”).text(data);

}

functionerr(xhr,message,e)

{

$(“div”).text(message);

}

</script>

</head>

<body>

<h3>HandlingAjaxerrors</h3>

Successorerrormessage:<div></div>

</body>

</html>

Output:

Sussessorerrormessage:

error

Explanation:

“url:“noFile.txt”,”specifiesafilethatisnotexisting,soanerroroccurred.

“error:err”catchestheerrorandcallthefunctionerr(){}.

“$(“div”).text(message);”showstheerrormessage.

AjaxSuccess$.ajax()willexecutethecallbackfunctionifAjaxrunssuccessfully.

$.ajax({

type:“GET”or“POST”,

url:“sourcefile”,

data:{key:value}

success:function(data){}

});

“success:function(data){}”willexecutethefunctionifAjaxrunssuccessfully.

Example8.7

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<script>

$(document).ready(function(){

$.ajax({

type:“GET”,

url:“myFile.txt”,//rightfile

success:suss,

error:err

});

});

functionsuss(data)

{

$(“div”).text(data);

}

functionerr(xhr,message,e)

{

$(“div”).text(message);

}

</script>

</head>

<body>

<h3>Ifrunsuccessfully</h3>

Successorerrormessage:<div></div>

</body>

</html>

Output:

Successorerrormessage:

Hello!Ajaxistesting!

Explanation:

“url:“myFile.txt”,”specifiesafilethatisexisting,andthereisnoanyincorrectcodesinthewholeprogram,therefore,theAjaxrunssuccessfully.

“success:suss,”willcallthefunctionsuss(){}iftheAjaxprogramrunssuccessfully.

“$(“div”).text(data);”willshow“myFile.txt”scontent:”Hello!Ajaxistesting!”

Exercises

AjaxEvent

OpenNotepad,writetwofilesasfollowing,andputthemtothesamefolder“myServer”withjquery-1.11.3.jsintheserver.

(1)Response.php

(C:\AppServ\www\myServer\Response.php)

<?php

if($_POST[“data”]==“1”){

echo‘AjaxRunsSuccessfully!’;

}

if($_POST[“data”]==“2”){

echo‘AjaxErrorOccurs!’;

}

?>

(2)AjaxEvent.html

(C:\AppServ\www\myServer\AjaxEvent.html)

<html>

<head>

<scriptsrc=“jquery-1.11.3.js”></script>

<script>

functionmyFun(){

$.ajax({

type:“POST”,

url:“Response.php”,

data:{data:1},//set“data”as1

success:callback,

});

};

functioncallback(data){

$(“#results”).text(data);

}

</script>

</head>

<body><br>

<inputtype=“button”value=“RunAjax”

onclick=“myFun()”>

<br><br>HandlingAjaxevents<br><br>

Clickthebutton,Ajaxresponses:

<br><br><h3><divid=“results”></div></h3>

</body>

</html>

(3)jquery-1.11.3.jsisontheserver.

(C:\AppServ\www\myServer\jquery-1.11.3.js)

RuntheAjaxEvent.htmlbyaddress:

http://localhost/myServer/AjaxEven.html

Andclickthebutton.(Figure)

Original:

Output:

(Figure)

Howtimeflies!Itistimetosaygood-bye.

www.websprogram.com/books.php

www.amazon.com/author/rayyao

SourceCodeforDownloadPleasedownloadthesourcecodeofthisbook.

SourceCodeofJQueryforDownload

DearMyFriend,

IfyouarenotsatisfiedwiththiseBook,couldyoupleasereturntheeBookforarefundwithinsevendaysofthedateofpurchase?

Ifyoufoundanyerrorsinthisbook,couldyoupleasesendanemailtome?

yaowining@yahoo.com

Iwillappreciateyouremail.Thankyouverymuch!

Sincerely

RayYao

Myfriend,Seeyou!