13.07.2015 Views

JavaScript Class 3: Element Manipulation - Live to Try

JavaScript Class 3: Element Manipulation - Live to Try

JavaScript Class 3: Element Manipulation - Live to Try

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Today's first code sample:bakery.html


Today's first code sample:bakery.htmlWe will review the code line by line:• To understand what each line is doing.• To learn about each new action we'reusing.• To explain basic conventions in jQuery.–Please download the sample codefrom: http://bit.ly/jsCode3


document.ready()


document.ready() – why do weuse it?• We use selec<strong>to</strong>rs in jQuery <strong>to</strong> select html elements,and then perform actions on them.• What do you think would happen if we tried <strong>to</strong>perform an action on an element, like a largeimage, that hadn't loaded yet?– We can try this ourselves.– Preview the two files, hideImageBeforeLoading.htmland hideImageAfterLoads.html


document.ready() – why do weuse it?• The document ready function prevents any jQuerycode from running before the html documentfinishes loading.• Other examples of actions that can fail if you donot wrap your code in document.ready( … );– <strong>Try</strong>ing <strong>to</strong> get the size of an image that hasn't loaded.– <strong>Try</strong>ing <strong>to</strong> hide an element that doesn't exist.


Selec<strong>to</strong>rs


Selec<strong>to</strong>rs: a refresher• Basic jQuery syntax is: $(selec<strong>to</strong>r).action()• jQuery selec<strong>to</strong>rs allow us <strong>to</strong> find htmlelements.• jQuery selec<strong>to</strong>rs are much like CSSselec<strong>to</strong>rs.– Instead of finding <strong>to</strong> an html element <strong>to</strong> apply styles,you can find an html element <strong>to</strong> modify, remove orreplace.• jQuery selec<strong>to</strong>rs allow you <strong>to</strong> select HTMLelements (or groups of elements) by elementname, attribute name


The “this” Selec<strong>to</strong>r


“this” selec<strong>to</strong>r• The “this” selec<strong>to</strong>r in our <strong>to</strong>ggle method is tellingus <strong>to</strong> select the element that just called thefunction that is currently executing.– We called the <strong>to</strong>ggle function after selecting alink (“a”).– So this in the <strong>to</strong>ggle function will give us thelink that we just interacted with.• Read more: this demystified


Mouseover & mouseout


Mouseover & mouseout actions• Mouseover is called when you place your mouseover an html element, like a link.• Mouseout is called when your mouse leaves theelement you had been on previously. i.e, you moveyour mouse off that link.• Read more:– http://api.jquery.com/mouseout/– http://api.jquery.com/mouseover/


The <strong>to</strong>ggle function & <strong>to</strong>ggle<strong>Class</strong>function <strong>to</strong>ggle() {$(this).<strong>to</strong>ggle<strong>Class</strong>("pink");}• Inside the <strong>to</strong>ggle function, we call jQuery's<strong>to</strong>ggle<strong>Class</strong>() function.• Toggle<strong>Class</strong>() takes the name of the class you passit, and:– If the element you've selected already has thatclass, it removes it.– It the element you've selected does NOT havethat class, it adds it.


The <strong>to</strong>ggle function & <strong>to</strong>ggle<strong>Class</strong>function <strong>to</strong>ggle() {$(this).<strong>to</strong>ggle<strong>Class</strong>("pink");}• If the the html was this before calling <strong>to</strong>ggle<strong>Class</strong>:Cupcakes• Then after <strong>to</strong>ggle<strong>Class</strong>, the html is:Cupcakes• Read more: http://api.jquery.com/<strong>to</strong>ggle<strong>Class</strong>/


Important Jargon: Callbacks• A callback is a function that is passed as anargument <strong>to</strong> another function.• A callback is executed after the parent function isfinished.• We used our <strong>to</strong>ggle function as a callback:$("a").mouseout(<strong>to</strong>ggle);


The click action


click action• click is called when you place your click an htmlelement, like a link or a but<strong>to</strong>n.• Read more: http://api.jquery.com/click/• In our code sample, we pass the uploadPicsfunction as a callback <strong>to</strong> the click action.


The uploadPicsfunction uploadPics() {var text = $("#enterText").val();var pho<strong>to</strong> = $("#enterPho<strong>to</strong>").val();$("#pho<strong>to</strong>List").append("");$("#textList").append("" + text +"");}• Inside the uploadPics function, we call thefollowing jQuery actions: val(), append().


The val action


The val() action• Val() will get you the current value of the first elementyour selec<strong>to</strong>r matches.– If you selec<strong>to</strong>r matches more than one element, val()will only pass you back the current value of the firstmatch.• Val() is often used <strong>to</strong> grab the text out of a form element,like a text box.In our example, we grab the text entered in<strong>to</strong> the textbox with this line:var text = $("#enterText").val();• Read more: http://api.jquery.com/val/


The append action


append action• Append will insert the content you pass <strong>to</strong> it on<strong>to</strong>the end of the element you selected (but beforethat element's closing tag).$("#textList").append("" + text + "");First it finds the id=”textList” element ()Then, it inserts the_text_you_entered right before the tag• Read more: http://api.jquery.com/append/


The uploadPics functionIn summary, the uploadPics function:– Grabs the html element with id=”enterText”(this is the first textbox), and requests the valueof the text in the textbox.– Does the same thing <strong>to</strong> the element withid=”enterPho<strong>to</strong>” (the second textbox).– Appends new html code, containing a newimage nested inside a list item. The imagecontains the URL typed in<strong>to</strong> the second textbox.– Appends the text entered in the first textboxnext <strong>to</strong> the new image.


There's more than one way <strong>to</strong> doit...• There is another way we could have written thesame code, in a slightly more condensed way, thanthe way we just reviewed.• This other way leverages something called anAnonymous Function.


There's more than one way <strong>to</strong> doit...


Anonymous Functions


Anonymous Functions—what arethey?• An anonymous function is all those function() {/*some code */ }); blocks you see passed <strong>to</strong>events.– Example: $(“p”).hide(function(){alert(“the paragraph is now hidden!”);});• Anonymous functions don't have names.• This is NOT an anonymous function: functionpassTheSalt() { … }


Anonymous Functions—placement matters• When you see an anonymous function inside anevent, you are binding the anonymous function <strong>to</strong>that event.– $(“p”).hide(function(){alert(“the paragraph is now hidden!”);});– In the above example, we are binding the anonymousfunction whose code displays an alert <strong>to</strong> the hideevent.


Anonymous Functions—whenthey are required• If a function takes a parameter, and you want <strong>to</strong>call that function from within an event, you mustuse Anonymous Functions.• Let's review this in the sample code file,anonFxnExample.html– This file is contained within the zip file at:http://bit.ly/jsCode3


Anonymous Functions—whenthey are required• Let's say we have a function that takes oneparameter:function fadeLinkAway(aLink) {$(aLink).fadeOut();}• The function accepts a link, and then fades thatlink out.• If you try and call it like this, it will NOT work:$("a").mouseover(fadeLinkAway2(this));


Anonymous Functions—whenthey are requiredfunction fadeLinkAway(aLink) {$(aLink).fadeOut();}• Because you are passing a parameter, you mustuse an anonymous function:$("a").mouseover(function(){});fadeLinkAway(this);


Anonymous Functions—whenthey are required• To read more, see the “Callback with arguments”section of “How jQuery Works” by John Resig(crea<strong>to</strong>r of jQuery).


Extra Topics: Validation pluginsand Regular Expressions• Time permitting, we will discuss the jQueryvalidation plugin, which allows us <strong>to</strong> validate formdata: http://docs.jquery.com/Plugins/validation– See the example here:http://docs.jquery.com/Plugins/validation#Example• The plugin uses Regular Expresions <strong>to</strong> do thevalidation. To read more about regularexpressions:http://en.wikipedia.org/wiki/Regular_expression


Lab Time!• Next up, we're going <strong>to</strong> do a new example that issimilar <strong>to</strong> the bakery example, and re-uses manyof the same jQuery actions.• We are going <strong>to</strong> use this a base file:– LINK <strong>to</strong> be given in class• We are going <strong>to</strong> modify this file <strong>to</strong> create aLOLCAT genera<strong>to</strong>r!


Homework• Reading:– http://api.jquery.com/append/– http://docs.jquery.com/Val– http://api.jquery.com/<strong>to</strong>ggle<strong>Class</strong>/– http://docs.jquery.com/Tu<strong>to</strong>rials:Getting_Started_with_jQuer– http://docs.jquery.com/Plugins/validation• Lab:– To be announced in class

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!