Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to jQuery. jQuery Quick facts Is a cross-compatible JavaScript library Released in 2006 by John Resig Simplifies HTML document traversing,

Similar presentations


Presentation on theme: "Introduction to jQuery. jQuery Quick facts Is a cross-compatible JavaScript library Released in 2006 by John Resig Simplifies HTML document traversing,"— Presentation transcript:

1 Introduction to jQuery

2 jQuery Quick facts Is a cross-compatible JavaScript library Released in 2006 by John Resig Simplifies HTML document traversing, event handling, animating, and AJAX. Write less, do more!

3 Disclaimer! No lecture, tutorial, or video will be able to give you all possible information about jQuery. You MUST visit the jQuery API website to find extensive documentation and some examples for learning all the ins/outs of jQuery.jQuery API CSE 33453

4 Getting jQuery You can download and locally host a copy which can be downloaded here.here Hotlink Google’s copy which is available here.here I prefer hot linking to Google’s copy. CSE 33454

5 Including jQuery in web pages To include jQuery in your website, all you need is a script tag with its src pointed to the hosted location. CSE 33455

6 Using jQuery To use the jQuery library in your javascript, you can either use the jQuery() function or more simply the $(). $() creates a jQuery object CSE 33456

7 window.onload Previously, we used the window.onload event as the place to start using javascript that manipulates the HTML document. We used the window.onload event because that gets fired when all the objects in the document have been loaded into the DOM and all the images have finished loading. CSE 33457

8 .ready() event jQuery provides a simple statement that checks the document and waits until it’s ready to be manipulated called the ready event. You’ll put most of your code in this method $(document).ready(function(){ // Your code here }); CSE 33458

9 Get some Elements jQuery provides two approaches to select elements: 1.jQuery Selectors 2.jQuery Filter Methods Both approaches return a jQuery object which contains an array of all elements found. CSE 33459

10 jQuery Selectors Supports CSS selectors versions 1-3 1.By element: $(“div”) 2.By id : $(“#id”) 3.By class: $(“.classname”) 4.By attribute: $(“a[href]”) 5.By attribute that contains value: $(“div[class*=‘warning’]”) 6.Any CSS selector will work CSE 334510

11 jQuery selectors See here for complete list.here CSE 334511

12 Your turn Quiz Google Bing You should be careful!! jQuery is super powerful and may be harmful to small babies -Select the google anchor element -Select the element with an id equal to nav -Select the element with the class equal to warning CSE 334512

13 jQuery Example Link http://jsfiddle.net/blinkmacalahan/UYANa/ CSE 334513

14 jQuery Filter Methods jQuery provides methods that will ‘filter’ sets return from a selector search..first() – reduces a set of matched elements to the first item.last() – reduces a set of matched elements to the last item.eq(index) – reduces a set of matched elements to the one at the specified index.slice( start [, end] ) - reduces a set of matched elements to the subset specified by the range of indices.find( selector|jQuery Object|element ) – search the descendants of the current set filtered by a selector, jQuery Object, or element. CSE 334514

15 jQuery Object $(‘div’) will return a jQuery Object that contains an array of matched elements for the specified selector. Using that jQuery object, we can perform any jQuery method on that object. CSE 334515

16 jQuery Method Examples $("div").find("a"); $("body *").first(); $("body *").last(); $("body > *").slice(0,2); //selects the first two children of the body element CSE 334516

17 CSS Methods.addClass() – Adds the specified class(es) to each element of the matched set..hasClass() - Determine whether any of the matched elements are assigned the given class..removeClass() - Remove a single class, multiple classes, or all classes from each element in the set of matched elements. CSE 334517

18 CSS Methods.addClass("warning"); //adds the warning class.addClass("warning critical"); //adds the warning & critical classes.hasClass("warning"); // returns true.hasClass("penguin"); // returns false.removeClass("warning"); //remove the warning class.removeClass("warning critical"); //remove the warning & critical classes.removeClass(); //removes all classes CSE 334518

19 CSS Method.height() Gets the current computed height for the first element’s content area of the matched set. Returns a unit-less numeric pixel value (No parseInt() required). Recommended for math calculations CSE 334519

20 CSS Method.height(value) Sets the CSS height of every element in the matched set value can be an integer representing a number value can be a String but it must include valid units CSE 334520

21 .height() example $(window).height(); //685 $('div').height(); // 50 $('div').eq(0).height(100); //sets the height of the first div element of the matched set to 100px $('div').eq(0).height("100px"); //same as previous statement CSE 334521

22 Other CSS height Methods.innerHeight() – get the height of the element including padding..outerHeight(includeMargin) – get the height of the element including padding, border, and optionally margin. CSE 334522

23 CSS Method.width() Exactly like.height(), but using width CSE 334523

24 CSS Element Coordinate Methods.offset() – returns the current coordinates of the first element in the matched set relative to the document..position() - returns the current coordinates of the first element in the matched set relative to the element’s containing block. CSE 334524

25 CSS Methods.css().css(propertyName) – Get the value of a style property for the first element in the set of matched elements..css(propertyName, value) – set one or more CSS properties for the matched set. Get/set any CSS 1 & 2 property. Some of CSS3 isn’t supported by vanilla jQuery, but plugins can be used to support them. CSE 334525

26 .css() examples $('p').css('height'); // "50px" $('p').css('color'); // "rgb(255, 255, 255)" $('p').css('width', '100px'); //sets the matched elements' width to 100px $('p:last').css('color', 'red'); //sets the last item of the matched elements color to red CSE 334526

27 Mixing jQuery and DOM API Using the jQuery object of matched elements, we can access a particular element using array index notation. Doing this will return a DOM node. // returns a DOM node for the first matched element $('div')[0]; CSE 334527

28 Mixing jQuery and DOM API You CAN’T use jQuery methods directly on a DOM node. $('div')[0].css('color', 'red'); //this WON'T work $('div')[2].height(); //this WON'T work CSE 334528

29 Mixing jQuery and DOM API You CAN use DOM API properties and methods on DOM nodes directly. //The following uses DOM API properties on DOM nodes $('div')[0].style.color; // "red" $('div')[0].style.display; // "block" //The following uses DOM API methods on DOM nodes $('div')[0].addEventListener('click', function(e) { alert(e.target); }, false); CSE 334529

30 Mixing jQuery and DOM API If you have a DOM node and want to use jQuery on it, use the node as the selector. //This example is a little wasteful var node = $('div')[0]; $(node).css('color'); // "black" //This example is useful $(document.body).css('display'); // "block" CSE 334530

31 jQuery Events CSE 334531

32 Subset of jQuery Events.click().dblclick().focus(),.focusin(),.focusout().hover().keydown(),.keyup(),.keypress().mousedown(),.mouseup().mousemove().ready() CSE 334532

33 .hover() Binds two event handlers to the set of matched elements. One handler is executed when the mouse pointer enters an element. A second handler is executed when the point leaves the element. CSE 334533

34 .hover() example http://jsfiddle.net/blinkmacalahan/M5Ccz/ CSE 334534

35 Ways to use.hover() Fade in/out objects Make elements grow/shrink Change element’s class and take advantage of CSS CSE 334535

36 .ready() Unlike the window.onload event, jQuery’s ready() is handled once the DOM hierarchy has been fully constructed. In most cases, this is the best place to attach jQuery event handlers or run other jQuery code. However if you need to perform operations on images, you’ll need to use jQuery’s load() event. CSE 334536

37 .css() revisited Using.css() as a setter method only modifies the element’s inline style. You can unset applied inline styles by supplying an empty string as the property value. Note this does NOT remove a style that has been applied with a CSS rule in a stylesheet or element. CSE 334537

38 Unsetting inline CSS property //this removes any inline color style applied $('div:first').css('color', ''); CSE 334538

39 .css() revisited jQuery can equally interpret CSS and DOM style properties. So the following sets are equivalent: $('div').css('background-color', 'red'); $('div').css('backgroundColor', 'red'); $('div').css('margin-top'); // 100px $('div').css('marginTop'); //100px CSE 334539

40 .css() revisited If you dislike having to set CSS properties one at a time, then you’re in luck. You can pass a JSON string which consists of property-value pairs to set multiple CSS properties. CSE 334540

41 .css() with JSON //sets the bg color to black and the color to red all in one //method call $('div').css( { 'background-color' : 'black', 'color' : 'red' }); $('span').css( { 'position' : 'absolute', 'top' : '10px', 'left' : '200px' }); CSE 334541

42 jQuery Effects CSE 334542

43 jQuery Effects The jQuery library provides several techniques for adding animations to a webpage. You can create custom animations You can use standard pre-made animations CSE 334543

44 Premade Fade Animations.fadeIn() - display matched elements by fading them to opaque..fadeOut() – display matched elements by fading them to transparent..fadeTo() – adjust the opacity of matched elements. CSE 334544

45 .fadeIn().fadeIn() – animates matched elements to opaque over 400ms..fadeIn([duration]) – animates matched elements to opaque over duration ms. You can use the string fast and slow to indicate durations of 200 and 600ms. CSE 334545

46 .fadeIn().fadeIn([callback]) – you can provide a function to call once the animation is complete. Using the.fadeIn() method on an element with display: none will change the element’s display value to inline or block. CSE 334546

47 .fadeIn() Example //fades matched img element to opaque after 400ms $('img').fadeIn(); //fades matched img elements to opaque after 200ms; $('img').fadeIn('fast'); $('img').fadeIn(100, function() { alert('~100ms have elapsed since click'); }); CSE 334547

48 .fadeOut() Very similar to fadeIn() except for the following: 1.Matched elements fade to transparent 2.At the end of the animation, the element’s display property is set to none. CSE 334548

49 .fadeOut() Example $('img').fadeOut(100, function() { alert("The element's display property value is now none"); }); CSE 334549

50 Premade hiding/showing animations.hide() – Hide the matched elements.show() – Display the matched elements CSE 334550

51 .hide().hide() will immediately hide an element and is equivalent to.css(‘display’, ‘none’). The element display value is saved in cache..hide([duration]) will animate the width, height, and opacity of matched elements. After the animation completes, the elements display values are set to none. CSE 334551

52 fadeOut() versus hide() CSE 334552 hide fadeOut

53 .show().show() will immediately reveal matched elements and is equivalent to.css(‘display’, ‘block’). The elements display property is restored to its previous value..show([duration])will animate the width, height, and opacity simultaneously for duration ms. CSE 334553

54 Premade slide animations.slideDown() – Display the matched elements with a sliding motion..slideUp() – Hide the matched elements with a sliding motion. CSE 334554

55 .slideDown() Animates the height of matched elements. This will cause elements beneath the selected elements to slide down as well..slideDown() – with no specified duration the animation will complete in 400ms..slideDown([duration]) – performs slide animation for duration ms. You can also specify fast and slow. CSE 334555

56 .slideDown().slideDown([callback]) – If supplied, the callback function will be called with the animation completes. $('img').slideDown(); //performs animation for default 400ms $('img').slideDown('slow'); //performs slide animation for 600ms $('img').slideDown(300, function() { $(this).css('height'); }); CSE 334556

57 .slideUp() Opposite of slideDown() Supports same parameters CSE 334557

58 .slideToggle() Slides up or down depending on the current state of the element Supports same parameters as other slide functions http://jsfiddle.net/jmmurphy09/2y56z74v/ CSE 334558

59 Custom Animation If you need more power than the premade animations, then you can make your own. CSE 334559

60 .animation() This method allows developers to create animations effects on any numeric CSS value. By default you can’t animate colors. You can‘t animate font-family, position, display, etc. You can however set these properties once the animation completes. CSE 334560

61 Specifying properties to.animate() The animate() method accepts a property map similar to.css(). Use any numeric valued properties to animate. Provide a duration and callback function for when the animation completes. CSE 334561

62 .animate() Example //Use JSON string to specify CSS property map $('img').animate({ height : '10px', width : '200px', opacity : '.2' }); $('img').animate({ height : '10px', width : '200px', opacity : '.2' }, 400); $('img').animate({ left : '500px', top : '200px'}, 200, function() { $(this).css('display', 'none'); } ); CSE 334562 http://jsfiddle.net/jmmurphy09/kdn36wyw/

63 this in jQuery In callback functions, the this variable is a DOM node. That means you can’t use jQuery methods directly on it. How do we fix that? CSE 334563

64 this example $('a').click( function(e) { console.log('this: ' + this); //this is a DOM node //e.target is the target of the click event. console.log('e.target: ' + e.target); if ( this === e.target ) { console.log('e.target === target'); } //stop the default action of the browser opening the link. e.preventDefault(); $(this).css('backgroundColor', 'green'); }); CSE 334564

65 .each() function Iterates over a jQuery object executing a function for each matched element. Each time the function runs, it is passed the current loop iteration. The function is fired in the current context of the DOM element, so this refers to the element. CSE 334565

66 .each() example $('div').each( function(i) { console.log( i + ': ' + this.tagName + ' ' + $(this).text();); }); CSE 334566

67 jQuery Extras CSE 334567

68 Store data with jQuery.data() Store arbitrary data associated with the specified element. Data is cleared when page reloads jQuery.data(element, key, value)

69 Get data with jQuery.data() Returns a value for the named data store on the element. jQuery.data(element, key); CSE 334569

70 jQuery.data() example jQuery.data(document.body, 'foo', 'bar'); // 'bar' jQuery.data(document.body, 'foo'); // 'bar' //In chrome $0 is shorthand for document.body jQuery.data($0, 'json', "{ 'name' : 'fred' }"); // "{ 'name' : // 'fred'}" jQuery.data($0, 'json'); // "{ 'name' : 'fred'}" jQuery.data($0, 'id', 52); // 52 jQuery.data($0, 'id'); // 52 jQuery.data($0, 'isAwesome', true); // true jQuery.data($0, 'isAwesome'); // true CSE 334570

71 You can also do AJAX with jQuery // Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.ajax( "example.php" ).done(function() { alert("success"); }).fail(function() { alert("error"); }).always(function() { alert("complete"); }); // perform other work here... // Set another completion function for the request above jqxhr.always(function() { alert("second complete"); }); CSE 334571

72 jQuery UI http://jqueryui.com/ Provides abstractions for low-level interaction and animation, advanced effects and high- level, themeable widgets, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications. CSE 334572


Download ppt "Introduction to jQuery. jQuery Quick facts Is a cross-compatible JavaScript library Released in 2006 by John Resig Simplifies HTML document traversing,"

Similar presentations


Ads by Google