420 likes | 610 Views
j Query. http:// www.w3schools.com/Jquery/ https:// jqueryui.com/ http://jquery.com /. What is jQuery ?.
E N D
jQuery http://www.w3schools.com/Jquery/ https://jqueryui.com/ http://jquery.com/
What is jQuery? • jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. (jQuery.com) • Write less, do more: • $("p.neat").addClass("ohmy").show("slow"); • Performance • Plugins • It’s standard • … and fun!
Adding jQuery to Your Web Pages • Download the jQuery library from jQuery.com then use it < script src="jquery-1.11.0.min.js"></script> or reference it. <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"> </script>
jQuery Syntax • The jQuery syntax is tailor made for selectingHTML elements and performing some actionon the element(s). • Basic syntax is: $(selector).action() • A $ sign to define/access jQuery • A (selector) to "query (or find)" HTML elements • A jQuery action() to be performed on the element(s) • Example • $(this).hide() - hides the current element. • $("p").hide() - hides all <p> elements. • $(".test").hide() - hides all elements with class="test". • $("#test").hide() - hides the element with id="test".
The Document Ready Event • We cannot use the DOM before the page has been constructed • The DOM way window.onload = function() { // do stuff with the DOM } • The direct jQuery translation $(document).ready(function() {//do stuff with the DOM}); • The jQuery way $(function() { // do stuff with the DOM });
Aspects of the DOM and jQuery • Identification:how do I obtain a referenceto the node that I want. • Traversal:how do I move around the DOM tree. • Node Manipulation:how do I get or set aspects of a DOM node. • Tree Manipulation:how do I change the structure of the page.
jQuery / DOM comparison $(document).ready(function(){ $("button").click(function(){ $("p").hide(); $("#test").hide(); $(".test").hide(); });}); • The element Selector • The #id Selector • The .class Selector • jQuery Selectors http://api.jquery.com/category/selectors/
jQuery terminology • the jQuery function • refers to the global jQuery object or the $ function depending on the context • a jQuery object • the object returned by the jQuery function that often represents a group of elements • selected elements • the DOM elements that you have selected for, most likely by some CSS selector passed to the jQuery function and possibly later filtered further
The jQuery object • The $ function always (even for ID selectors) returns an array-like object called a jQuery object. • The jQuery object wraps the originally selected DOM objects. • You can access the actual DOM object by accessing the elements of the jQuery object. // false document.getElementById("id") == $("#myid"); document.querySelectorAll("p") == $("p"); // true document.getElementById("id") == $("#myid")[0]; document.getElementById("id") == $("#myid").get(0); document.querySelectorAll("p")[0] == $("p")[0];
Using $ as a wrapper • $ adds extra functionality to DOM elements • passing an existing DOM object to $ will give it the jQuery upgrade // convert regular DOM objects to a jQuery object varelem = document.getElementById("myelem"); elem = $(elem); varelems = document.querySelectorAll(".special"); elems = $(elems);
Looping over the DOM • Using the DOM • Using jQuery varelems = document.querySelectorAll("li"); for (vari = 0; i < elems.length; i++) { var e = elems[i]; // do stuff with e } $("li").each(function(idx, e) { // do stuff with e }); • return false to exit the loop early • e is a plain old DOM object • We can upgrade it again using $ if we want $("li").each(function(idx, e) { e = $(e); // do stuff with e });
Getting/setting CSS classes in jQuery function highlightField() { // turn text yellow and make it bigger if (!$("#myid").hasClass("invalid")) { $("#myid").addClass("highlight"); } } • addClass, removeClass, hasClass, and other methods manipulate CSS classes • similar to existing className DOM property, but don't have to manually split by spaces
jQuery css() method parameters • getter syntax: • setter syntax: • multi-setter syntax: • modifier syntax: $("#myid").css(propertyName); $("#myid").css(propertyName, value); $("#myid").css({ 'propertyName1': value1, 'propertyName2': value2, ... }); $("#myid").css(propertyName, function(idx, oldValue) { return newValue; });
jQuery css() method behavior • Getterstypically operate only on the first of the jQuery object's selected elements. • Setterstypically operate on all of the selected DOM elements. <ul> <li style="font-size: 10px">10px font size</li> <li style="font-size: 20px">20px font size</li> <li style="font-size: 30px">30px font size</li> </ul> $("li").css("font-size"); // returns '10px' $("li").css("font-size", "15px"); // sets all selected elements to ‘15px' <ul> <li style="font-size: 15px">10px font size</li> <li style="font-size: 15px">20px font size</li> <li style="font-size: 15px">30px font size</li> </ul>
Changing and accessing styles in jQuery function biggerFont() { // turn text yellow and make it bigger var size = parseInt($("#clickme").css("font-size")); $("#clickme").css("font-size", size + 4 + "pt"); }
More about jQuery $ function signatures • Responding to the page readyevent • $(function); • Identifying elements • $("selector", [context]); • UpgradingDOM • elements=$(elements); • Creatingnew elements • $("<html>", [properties]);
Create and remove nodes in jQuery varnewElement = $("<div>"); $("#myid").append(newElement); • The $ function used to create a div element • Removing a node from the page: remove any LI that contains a “child” substring $("li:contains('child')").remove(); • Equivalent to the following native Javascript DOM: varbullets = document.getElementsByTagName("li"); for (vari = 0; i < bullets.length; i++) { if (bullets[i].innerHTML.indexOf("child") >= 0) { bullets[i].parentNode.removeChild(bullets[i]); } }
Creating complex nodes in jQuery $("<p>", { "id": "myid", "class": "special", "text": "My paragraph is awesome!" });
jQuery Event Methodshttp://www.w3schools.com/Jquery/jquery_ref_events.asp • some common DOM events • Commonly Used jQuery Event Methods: Click(), dblclick(), mouseenter(), mouseleave(), keypress();keydown(), keyup(), submit(), focus(),blur(), mouseup(), mousedown(), on(), hover() //attaches an event handler function to an HTML element $("p").click(function(){ $(this).hide(); //what to do});
jQuery Event Methods • on(): Attach an event handler function for one or more events to the selected elements. • Hover():Attaches two event handlers to the hover and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element: //Attach a click event handler to the <p> element: $("p").on("click",function(){ alert("The paragraph was clicked.");}); //Change background color of a <p> when the mouse pointer hovers over it: $("p").hover(function(){ $("p").css("background-color","yellow"); }, function(){ $("p").css("background-color","pink");});
jQueryVisual Effects • jQuery Effects - Hide and Show • hide() • show() • toggle() • jQuery Effects – Fading • fadeIn() • fadeOut() • fadeToggle() • fadeTo() • jQuery Effects – Sliding • slideDown() • slideUp() • slideToggle() • jQuery Effects – Animation • animate() • stop() • jQuery Method Chaining
jQuery Effects - Hide and Show • SYNTAX: $(selector).hide(speed,callback); • $(selector).show(speed,callback); • optionalspeed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", or milliseconds. • optionalcallback parameter is a function to be executed after the hide() or show() method completes • //Hide all <p> elements: • $("button").click(function(){ $("p").hide(); • $("p").hide(1000); // • $("p").hide("slow",function(){ alert("The paragraph is now hidden"); });}); • //Show all hidden <p> elements: • $("button").click(function(){ $("p").show();}); • //Shown elements are hidden and hidden elements are shown • $("button").click(function(){$("p").toggle();});
jQuery Effects - Fading • SYNTAX: $(selector).fadeIn(speed,callback); • //same for fadeOut and fadeToggle • optional speed parameter specifies the speed of the duration of the effect. • optional callback parameter is a function to be executed after the fading completes • SYNTAX: $(selector).fadeTo(speed,opacity,callback); • //Both speed and opacity are required • <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> • </script> • <script> • $(document).ready(function(){ • $(".btn1").click(function(){ • $("p").fadeOut(1000); • }); • $(".btn2").click(function(){ • $("p").fadeIn(1000); • }); • }); • </script> • </head> • <body> • <button class="btn1">Fade out</button> • <button class="btn2">Fade in</button> • <p>This is a paragraph.</p>
jQuery Effects - Sliding • SYNTAX: $(selector).slideDown(speed,callback); • //same for slideUp() and slideToggle() • optional speed parameter specifies the speed of the duration of the effect. • optional callback parameter is a function to be executed after the sliding completes • <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> • </script> • <script> • $(document).ready(function(){ • $(".btn1").click(function(){ • $("p").slideUp(1000); • }); • $(".btn2").click(function(){ • $("p").slideDown(1000); • }); • }); • </script> • </head> • <body> • <p>This is a paragraph.</p> • <button class="btn1">Slide up</button> • <button class="btn2">Slide down</button>
jQuery Effects - Animation • SYNTAX: $(selector).animate({params},speed,callback); • requiredparamsparameter defines the CSS properties to be animated. • optional speed parameter specifies the duration of the effect. • optional callback parameter is a function to be executed after the effect completes • <script> • $(document).ready(function(){ • $("button").click(function(){ • var div = $("div"); • startAnimation(); • function startAnimation(){ • div.animate({height:300},"slow"); • div.animate({width:300},"slow"); • div.css("background-color","blue"); • div.animate({height:100},"slow"); • div.animate({width:100},"slow",startAnimation); • } • }); • }); • </script> • </head> • <body> • <button>Start Animation</button> • <div ></div>
jQuery Stop Animations SYNTAX: $(selector).stop(stopAll,goToEnd); optional stopAllparameter specifies whether also the animation queue should be cleared or not. Default is false. optional goToEndparameter specifies whether or not to complete the current animation immediately. Default is false • <script> • $(document).ready(function(){ • $("#start").click(function(){ • $("div").animate({height:300},3000); • $("div").animate({width:300},3000); • }); • $("#stop").click(function(){ • $("div").stop(); • }); • }); • </script> • </head> • <body> • <p> • <button id="start">Start Animation</button> • <button id="stop">Stop Current Animation</button> • </p> • <div style="background:#98bf21;height:100px;width:100px"> • </div>
jQuery - Chaining • Chaining allows us to run multiple jQuery commands, one after the other, on the same element(s). browsers do not have to find the same element(s) more than once. • To chain an action, you simply append the action to the previous action. • <script> • $(document).ready(function() • { • $("button").click(function(){ • $("#p1").css("color","red").slideUp(2000).slideDown(2000); • }); • }); • </script> • </head> • <body> • <p id="p1">jQuery is fun!!</p> • <button>Click me</button> • </body> • </html>
jQuery DOM traversing http://api.jquery.com/category/traversing/ • jQuery Traversing – Ancestors • jQuery Traversing - Descendants • jQuery Traversing - Siblings • jQuery Traversing - Filtering
jQuery Traversing – Ancestors • Three useful jQuery methods for traversing up the DOM tree are: • parent(): returns the direct parent element of the selected element • parents(): returns all ancestor elements of the selected element and may used an optional parameter to filter the search for ancestors • parentsUntil() : returns all ancestor elements between two given arguments • $(document).ready(function(){ • //returns the direct parent element of each <span> elements • $("span").parent(); • //returns all ancestors of all < span> elements up to html element • $("span").parents(); • //returns all ancestors of all <span> elements that are <ul> elements • $("span").parents("ul"); • //returns all ancestor elements between a <span> and a <div> element • $("span").parentsUntil("div");});
jQuery Traversing – Ancestors (try it) CSS .ancestors *{ display: block; border: 2px solid lightgrey; color: lightgrey; padding: 5px; margin: 15px;} JQUERY $(document).ready(function(){ $("span").parents().css({"color":"red", "border":"2px solid red"}); }); HTML <body class="ancestors">body (great-great-grandparent) <div style="width:500px;">div (great-grandparent) <ul>ul (grandparent) <li>li (direct parent) <span>span</span> </li> </ul> </div> </body>
jQuery Traversing - Descendants • Two useful jQuery methods for traversing down the DOM tree are: • children():returns all direct children of the selected element and can use an optional parameter to filter the search for children • find():returns descendant elements of the selected element, all the way down to the last descendant • $(document).ready(function(){ • //returns all elements that are direct children of each <div> elements • $("div").children(); • //returns all <p> elements with the class name "1", that are direct • //children of <div> • $("div").children("p.1"); • //returns all <span> elements that are descendants of <div> • $("div").find("span"); • //returns all descendants of <div>: • $("div").find("*"); • });
jQuery Traversing - Siblings • There are many useful jQuery methods for traversing sideways in the DOM tree: • siblings(): returns all sibling elements of the selected element and can optionally filtered by a selector. • next(): returns the next sibling element of the selected element and can optionally filtered by a selector • nextAll(): returns all next sibling elements of the selected element and optionally filtered by a selector • nextUntil(): returns all next sibling elements between two given arguments. • prev(), prevAll(), prevUntil(): work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward) • $(document).ready(function(){ • $("h2").siblings(); • //returns all sibling elements of <h2> that are <p> elements • $("h2").siblings("p"); • //returns all <span> elements that are descendants of <div> • $("h2").next(); • });
jQuery Traversing - Filtering • Narrow Down The Search For Elements • The most basic filtering methods are: • first(), last() and eq(index)-which allow to select a specific element based on its position in a group of elements. • filter() and not()-allow to select elements that match, or not match, a certain criteria. • $(document).ready(function(){ • //selects the first <p> element inside the first <div> element • $("div p").first(); • //selects the second <p> element (index number 1): • $("p").eq(1); • //returns all <p> elements with class name "intro": • $("p").filter(".intro"); • //returns all <p> elements that do not have class name "intro":$("p").not(".intro"); • });
Drag and drop jQueryUI provides several methods for creating drag-and-drop functionality: • Sortable : a list of items that can be reordered • Draggable : an element that can be dragged • Dropable : elements on which a Draggable can be dropped
Sortable $('#myidul').sortable([options]); • specifies a list (ul, ol) as being able to be dragged into any order • with some stylings you can get rid of the list look and sort any grouping of elements • implemented internally using Draggables and Droppables • to make a list un-sortable again, call .sortable('destroy') on the sortable element
Sortable list events <script> $(function() { $("#simpsons").sortable({ 'update': listUpdate}); }); function listUpdate(event, ui) { // can do anything I want here; ui.item.css("font-size", "25px"); } </script> <body> <ol id="simpsons"> <li>Homer</li> <li>Marge</li> <li>Bart</li> <li>Lisa</li> <li>Maggie</li> </ol> </body>
Draggable $('#myid').draggable([options]); • specifies an element as being able to be dragged • <script> • $(function() { • $('#draggabledemo1').draggable(); $('#draggabledemo2').draggable({ • 'revert': true, • 'grid': [40, 40] • }); • }); • </script> • <body> • <div id="draggabledemo1">Draggable demo 1. Default options. • </div> • <div id="draggabledemo2">Draggable demo 2. • </div> • </body>
Droppable • $('#myid').droppable([options]); • specifies an element as being able to receive draggables • <style> #droptarget { width: 250px; height: 300px; • border: 2px solid black;} </style> • <script> • $(function() { • $('#shirt').draggable(); • $('#cup').draggable(); $('#droptarget').droppable({ • drop: function( event, ui ){ alert("you just dropped a " + • ui.draggable.attr('id')); • } • }); • }); • </script> • <body> • <img id="shirt" src="shirt.png" alt="shirt" /> • <img id="cup" src="cup.png" alt="cup" /> • <div id="droptarget"></div> </body>
Autocomplete • $('#myid').autocomplete([options]); • provides suggestions while you type into the field • datasourceis a JavaScript array, provided to the widget using the source-option • <link rel="stylesheet" href=“http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"> • <script src=“http://code.jquery.com/jquery-1.9.1.js"></script> • <script src=“http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> • <script> • $(function() { • varavailableTags = ["ActionScript", "AppleScript", • "Asp", "BASIC", "C", "C++", "Clojure", • "COBOL", "ColdFusion", "Erlang", "Fortran", • "Groovy", "Haskell", "Java", "JavaScript", • "Lisp", "Perl", "PHP", "Python", "Ruby", • "Scala", "Scheme" ]; • $( "#tags" ).autocomplete({source: availableTags }); • }); • </script> • <body> • <div > <label for="tags">Tags: </label> • <input id="tags"/> </div>