Introduction to jQuery What is jQuery? • a lightweight, "write less, do more", JavaScript library. • The purpose is to make it much easier to use JavaScript. • takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that can be called with a single line of code. • simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. What is jQuery? • The jQuery library contains the following features: – HTML/DOM manipulation – CSS manipulation – HTML event methods – Effects and animations – AJAX – Utilities Using jQuery • several ways to start using jQuery on your web site: – Download the jQuery library from jQuery.com, use as external library, reference in HTML head (relative path) – Include jQuery from a CDN, like Google, also use as external library, reference (via HTTP) in HTML head Downloading jQuery • There are two versions of jQuery available for downloading: • Production version - this is for your live website because it has been minified and compressed • Development version - this is for testing and development (uncompressed and readable code) Downloading jQuery • Both versions can be downloaded from jQuery.com. • The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section): • <head> <script src="jquery-1.10.2.min.js"></script> </head> Alternatives to Downloading • If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network). • Both Google and Microsoft host jQuery. Google CDN • <head> <script src=" //ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> </head> Hello World • Activity 1 – hello1.html – local scripts – hello2.html – Google CDN jQuery Syntax • The jQuery syntax is tailor made for selecting HTML elements and performing some action on 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) jQuery Syntax • Examples: – $(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 • to prevent any jQuery code from running before the document is finished loading (is ready). • $(document).ready(function(){ // jQuery methods go here... }); The Document Ready Event • Good practice to wait for the document to be fully loaded and ready before working with it. • Some examples of actions that can fail if methods are run before the document is fully loaded: – Trying to hide an element that is not created yet – Trying to get the size of an image that is not loaded yet The Document Ready Event • Tip: The jQuery team has also created an even shorter method for the document ready event: • $(function(){ // jQuery methods go here... }); jQuery Selectors – activity 2 • jQuery selectors allow selection and manipulation of HTML element(s). • Enable to find elements based on their id, classes, types, attributes, values of attributes and much more. • It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. • All type of selectors in jQuery, start with the dollar sign and parentheses: $(). Example – element selector • select all <p> elements on a page like this: – $("p") • When a user clicks on a button, all <p> elements will be hidden: – $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); Example – #id selector • #id selector uses the id attribute of an HTML tag to find the specific element. • id should be unique within a page, so the #id selector is use to find a single, unique element – $(document).ready(function(){ $("button").click(function(){ $("#test").hide(); }); }); Example – .class Selector • finds elements with a specific class – by writing a period character, followed by the name of the class - $(".test") – $(document).ready(function(){ $("button").click(function(){ $(".test").hide(); }); }); More Examples of jQuery Selectors Syntax Description $("*") Selects all elements $(this) Selects the current HTML element $("p.intro") Selects all <p> elements with class="intro" $("p:first") Selects the first <p> element $("ul li:first") Selects the first <li> element of the first <ul> $("ul li:first-child") Selects the first <li> element of every <ul> $("[href]") Selects all elements with an href attribute $("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank" $("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank" $(":button") Selects all <button> elements and <input> elements of type="button" $("tr:even") Selects all even <tr> elements $("tr:odd") Selects all odd <tr> elements Important Functions • • • • • $().parseHTML('); //createElement $().html(); //get or set element $().val(); //get text value $().append(); //append text or html $().attr(); //get or set attribute jQuery Events Event Method Description $(selector).click(function) Invokes a function when the selected elements are clicked $(selector).dblclick(function) Invokes a function when the selected elements are double-clicked $(selector).focus(function) Invokes a function when the selected elements receive the focus $(selector).mouseover(function) Invokes a function when the mouse is over the selected elements $(selector).keypress(function) Invokes a function when a key is pressed inside the selected elements For a full jQuery event reference, please see jQuery Events Reference Append text to paragraph lemon on mouseover <script> $("#lemon").mouseover(function(){ $(this).append(" Cookie! "); }); </script> <p id='lemon'>Lemon drops biscuit chocolate…</p> Manipulating CSS CSS Properties Description $(selector).css(propertyName) Get the style property value of the first selected element $(selector).css(propertyName,value) Set the value of one style property for selected elements $(selector).css({properties}) Set multiple style properties for selected elements $(selector).addClass(class) Apply style class to the selected elements For a full jQuery CSS reference, please see jQuery CSS Methods Reference For more on the css function, see http://api.jquery.com/css/ Change color of paragraph lemon when btnColor is clicked <script> $("#btnColor").click(function(){ $("#lemon").addClass("blue"); }); </script> <style type="text/css"> .red{ color:red; } .blue{ color:blue; } </style> <script> $("#btnColorCheck").click(function(){ Whatalert($("#lemon").css("color")); color is the paragraph? }); </script> Display the color of the paragraph lemon when btnColorCheck is clicked. <p id='lemon'>Lemon drops biscuit chocolate…</p> Highlight (background-color = yellow) any paragraph that is double-clicked <script> $("p").dblclick(function(){ $(this).css("background-color", "yellow"); }); </script> jQuery Effects Function Description $(selector).hide() Hide selected elements $(selector).show() Show selected elements $(selector).toggle() Toggle (between hide and show) selected elements $(selector).slideDown() Slide-down (show) selected elements $(selector).slideUp() Slide-up (hide) selected elements $(selector).slideToggle() Toggle slide-up and slide-down of selected elements $(selector).fadeIn() Fade in selected elements $(selector).fadeOut() Fade out selected elements $(selector).fadeTo() Fade out selected elements to a given opacity $(selector).fadeToggle() Toggle between fade in and fade out Create a toggle button that shows/hides paragraph lemon. <script> $("#btnToggle").click(function(){ $("#lemon").slideToggle("slow"); }); </script> <p id='lemon'>Lemon drops biscuit chocolate…</p> <script> $("#btnFade").click(function(){ $("#lemon").fadeTo("slow", 0.5); }); </script> Fade paragraph lemon to 50% opacity when btnFade is clicked. <p id='lemon'>Lemon drops biscuit chocolate…</p> Manipulating HTML Function Description $(selector).html(content) Changes the (inner) HTML of selected elements $(selector).append(content) Appends content to the (inner) HTML of selected elements $(selector).after(content) Adds HTML after selected elements For a full jQuery HTML reference, please see jQuery HTML Methods Reference <script> $("#btnReplace").click(function(){ $("#lemon").html("Lollipop soufflé ice cream tootsie roll donut..."); }); </script> Replace text in paragraph lemon when btnReplace is clicked. <p id='lemon'>Lemon drops biscuit chocolate…</p> Ajax • The jQuery $.post() method loads data from the server using an HTTP POST request. • Syntax $.post(URL, {data}, function(data){…}); $.post("myScript.php", {name:txt}, function(result) { $("span").html(result); }); ajax.php Parameter Description URL Required. Specifies the url to send the request to. data Optional. Specifies data to send to the server along with the request. function(data) •Optional. Specifies a function to run if the request succeeds. data - contains the resulting data from the request http://www.w3schools.com/jquery/ajax_post.asp Ajax show_product.php <?php $id = $_POST['id']; Get this from the Ajax call mysql_connect("localhost", "omuser", "omuser") or die("Error connecting"); mysql_select_db("om") or die("Error selecting DB"); $query = "SELECT * FROM items WHERE item_id = $id"; $result = mysql_query($query); if (mysql_num_rows($result) == 0) { echo "Product ID $id not found."; return; } $row = mysql_fetch_array($result); echo "<strong>Item ID:</strong> {$row['item_id']}<br>"; echo "<strong>Title:</strong> {$row['title']}<br>"; echo "<strong>Artist:</strong> {$row['artist']}<br>"; echo "<strong>Price:</strong> {$row['unit_price']}<br>"; Ajax ajax.php $('#show').click(function(){ var prodId = $('#id').val(); $.post( "show_product.php", {id:prodId}, function(result) { $('#detail').html(result); } ); }); When the button is clicked Get the text box value Ajax POST Name of the PHP script The key/value to be passed Update the "detail" div With the output of the PHP script