Faculty.cse.tamu.edu



JQuery Advanced TopicsThe ‘on’ MethodThe ‘on’ method is an easy way to add multiple event handlers to the same elementE.g. A table cell that turns blue while the mouse cursor is hovering over it with text that turns red when the cell is clickedUsing the ‘on’ method for a single events$("p").on("click",?function(){??? alert("The paragraph was clicked.");});Using the ‘on’ method for multiple events<head><script?src=""></script><script>$(document).ready(function(){ $("td").on({??? mouseenter:?function(){??????? $(this).css("background-color",?"blue");??? },???? mouseleave:?function(){??????? $(this).css("background-color",?"white");??? },???? click:?function(){??????? $(this).css("color",?"red");??? }? });});</script></head><body> <table> <tr> <td>Element One</td><td>Element Two</td> </tr> </table></body> Uses slightly different syntax than the rest of jQuerylist of other mouse-events DOM TraversalJQuery provides a simple way to traverse an element’s ancestors, descendants, and siblings.This is especially useful for tables and chartsTraversal DOM of HTML DocHTML CodeOverall Traversal Traversing within a Smaller Bulleted set are three methods for traversing an element’s ancestorsparent() – Returns the immediate parent of the elementparents() – Returns all ancestors of the element. This method can take a parameter which only selects elements that match that parameterE.g. $(“#row11”).parents(“ul”); fetches all <ul> elements of the element with id ‘row11’parentsUntil() – Returns all ancestors between the selected element and the element provided as a parameterE.g. $(“#row11”).parents(“ul”); fetches all elements between the element with id ‘row11’ and its first <ul> parentDescendantsThere are two methods for traversing an element’s descendantschildren() – Returns all children of the selected element, equivalent to ‘parents()’ for ancestorsLike ‘parents()’ this can take a parameter to filter the resultsfind() – Returns only the descendants matching the provided parameterE.g. $(“#table1”).find(“td”); fetches all <td> elements within the element with id ‘table1’SiblingsThere are seven methods for traversing an element’s siblingssiblings() – Like ‘children()’, returns all siblings of the selected elementnext() – Fetches the next immediate sibling of the elementnextAll() – Fetches all subsequent siblings of the elementnextUntil() – Fetches all subsequent siblings of the element between the selected element and the element provided as a parameterE.g. $(“#list1”).parents(“ul”); fetches all elements between the element with id ‘list1’ and its next <ul> siblingprev() – Equivalent to ‘next()’ in the reverse directionprevAll() – Equivalent to ‘nextAll()’ in the reverse directionprevUntil() – Equivalent to ‘nextUntil()’ in the reverse directionUsing traversal to affect children<head><script?src=""></script><script>$(document).ready(function(){ $("#addRow").click(function(){??? // ... Code to add table row here ... // Code to color the text of all <td> children of <table> elements red $("table").find("td").css("color",?"red"); });});</script></head><body><table><tr><td>Element One</td><td>Element Two</td></tr></table><button id="addRow">Add Row</button></body>AJAXJQuery greatly simplifies AJAX callsMuch of the tedious AJAX setup can be performed in one lineThere are three methods used to send and request data with AJAX in JQuery$(selector).load(URL, data, callback) – Load can send or simply request data; it returns received data directly into the HTML of the selected element. Data and callback are optional parametersdata – This parameter determines whether the .load() call uses GET or POST. It can be either:String with data to send – Causes the .load() to use GETKey/data pairs with data to send, e.g. { valueOne: "Data 1", valueTwo: "Data 2" } – Causes the .load() to use POSTcallback – The callback function for when the request is received$.get(URL, callback) – Performs a GET request independently of any specific element. Callback is an optional parametercallback – The callback function for when the request is received$.post(URL, data, callback) – Performs a POST request independently of any specific element. Data and callback are optional parametersdata – Key/data pairs with data to send, e.g. { valueOne: "Data 1", valueTwo: "Data 2" }callback – The callback function for when the request is receivedAny data sent using AJAX and JQuery can be received like a normal requests. GET or POST depends on the methods used and the parameters passed in.The callback method works just like an AJAX callback method and has the following parametersresponseTxt - contains the resulting content if the call succeedsstatusTxt - contains the status of the callxhr - contains the XMLHttpRequest objectThe below examples compare AJAX calls with and without JQueryAJAX with callback method (No JQuery)function?loadDoc() { // set up request OBJECT??var?xhttp =?new?XMLHttpRequest(); // set up hander to handle the various stages of the request? xhttp.onreadystatechange?=?function() {????if?(this.readyState?==?4?&&?this.status?==?200) {???? document.getElementById("demo").innerHTML?=?this.responseText;????}? }; // Open() establishes the connection with the server // This will succeed (and changes the state)? xhttp.open("GET",?"ajax_info.txt",?true); // request data? xhttp.send();}AJAX with callback method (Using JQuery)$(document).ready(function(){??? // request data $("#demo").load("ajax_info.txt",?function(responseTxt, statusTxt, xhr){ // Occurs if the request succeeds and is ready????????if(statusTxt ==?"success")??????????? alert("External content loaded successfully!"); // Occurs if an error occurs at any point????????if(statusTxt ==?"error")??????????? alert("Error: "?+ xhr.status?+?": "?+ xhr.statusText);??? });});AJAX POST (Using JQuery)$("#submit").click(function(){??? // Get data var fname = $("#fname").text(); var lname = $("#lname").text();? // POST data $.post("confirm.php", { first_name:?fname, last_name:?lname });});AnimationsJQuery can be used to animate elementsThere are several specific methods that can be used to perform built-in animations such as:fadeIn() – Fades an element to full opacityfadeOut() – Fades an element to full transparencyfadeToggle() – Fades an element to either full opacity or transparency depending on its current statefadeTo(opacity) – Fades an element to a specified degree of opacityslideDown() – Slides an element to its full dimensionsslideUp() – Slides an element to its minimum dimensionsslideToggle() – Slides an element to either its full or minimum dimensions depending on its current stateAll animation methods can take the parameters speed and callbackSpeed – The speed to perform the animation, this can be default values such as ‘slow’ or ‘fast’ or specific number of milliseconds as an integerCallback – A generic JQuery callback methodThe ‘stop()’ method can be called in the middle of any animation method to instantly halt the animationUseful if called from a button’s click handlerThe true power of JQuery animations lie in the ‘animate()’ methodThis method allows you to specify specific attributes to modify during the animationThe first parameter of the ‘animate()’ method is a list of CSS attributes that will be the result of the animation.These are final values, not current valuesE.g. $(“#animateDiv”).animate({height: 250px, width: 250px}); will cause the element with id ‘animateDiv’ to become 250px by 250px with a moderate speed animationSimple animation example$(document).ready(function(){??? $("#zoom").click(function(){ $("#animate").animate( { opacity: ‘0.5’, // Will concurrently adjust height: ‘250px’, // each value given here width: ‘250px’; // at the same time });??? });});</script></head><body><div id="animate" style="height:100px; width:100px;"></div><button id="zoom">Zoom</button></body>Relative values can be used instead of absolute values when animatingA relative value has an ‘<operator>=<value>’ formatE.g. ‘+=100px’, ‘-=10px’, ‘*=50px’As opposed to absolute values, these values will be updated every time the animate method is calledSequential animations can be triggered by calling the animate function repeatedly in the same eventMultiple animations example$(document).ready(function(){??? $("#doAnimate").click(function(){ $("#animate").animate({opacity: ‘0.5’}, “slow”}); // Will change this value $("#animate").animate({height: ‘250px’}, “slow”}); // *then* this value $("#animate").animate({width: ‘250px’}, “slow”}); // *then* this value??? });}); Resources (Tutorial with worked examples) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download