jQuery

898 views

Published on

Presents:
Introduction and Using jQuery
Selectors and Attributes
Events
Height and Width
DOM Manipulation and Modification
Effects and Animation
Store arbitrary data and add your functions.
Ajax

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
898
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds funcionality to the elements in the page doesn't have to wait for all content to load.
  • $(this).hide() - hides current element$("p").hide() - hides all paragraphs$("p.test").hide() - hides all paragraphs with class="test"$("#test").hide() - hides the element with id="test“$("p").last().addClass("selected")– changes class of last paragraph to “selected”
  • http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/
  • MultipleAttributeSelector [name="value"][name2="value2"]
  • There are more selectors for all form elements
  • There are more selectors for all form elements
  • $("p").addClass("myClassyourClass");
  • <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />$('#greatphoto').attr('alt', 'Beijing Brush Seller');  change alt attribute of element$('#greatphoto').attr({ alt: 'Beijing Brush Seller', title: 'photo by Kelly Clark' });  To change the alt attribute and add the title attribute at the same time.When setting multiple attributes, the quotes around attribute names are optional.WARNING: When setting the 'class' attribute, you must always use quotes!jQuery prohibits changing the type attribute on an <input> or <button> element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.$('#greatphoto').attr('title', function(i, val) { return val + ' - photo by Kelly Clark' });  using a function to set attributes, you can compute the value based on other properties of the element. Here, to concatenate a new value with anexisting value:
  • <div id="mydiv" class="foo bar"></div>$('#mydiv').hasClass('bar’)  true$('#mydiv').hasClass('foo')  true$('#mydiv').hasClass(’red') false
  • <div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div>$('div.demo-container').html();  <div class="demo-box">Demonstration Box</div>$('div.demo-container’) .html('<p>All new content. <em>You bet!</em></p>');  <div class="demo-container”> <p>All new content. <em>You bet!</em></p></div>
  • By using a function to set properties, you can compute the value based on other properties of the element. For example, to toggle all checkboxes based off their individual values:$("input[type='checkbox']").prop("checked", function( i, val ) { return !val; });
  • NOTE: In IE prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data().
  • NOTE:Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 6, 7, or 8. To avoid potential problems, use .prop() instead$(‘p’).removeClass(‘myClassanotherClass’);
  • NOTE:In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties as checked, disabled, or selected.
  • To animate colors use jQueryUINote that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.
  • jQuery

    1. 1. Julie Iskander Lecturer at ITIMSc. Communication and Electronics
    2. 2. OutlinesO Introduction and Using jQueryO Selectors and AttributesO EventsO Height and WidthO DOM Manipulation and ModificationO Effects and AnimationO Store arbitrary data and add your functions.O Ajax
    3. 3. Introduction
    4. 4. DefinitionO jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
    5. 5. John ResigO Developed by John Resig from Mozilla and was first announced in January 2006.O Dean of Computer Science at Khan Academy and the creator of the jQuery JavaScript library.O Author of Pro JavaScript Techniques and Secrets of the JavaScript Ninja.O http://ejohn.org/
    6. 6. Why Use jQuery?O Lightweight Footprint O Only 32kB minified and gzipped.O CSS3 Compliant O It supports CSS3 selectors to find elements as well as in style property manipulation.O Cross Browser O It supports IE 6+ and all current versions of Chrome, Firefox, Safari and Opera. It may face major issues in older browser version.
    7. 7. jQueryO Simplifies common scripting tasksO Abstracts away browser-specific featuresO Adds sophisticated effectsO Simplifies retrieving and manipulating DOMO Makes the DOM less scary
    8. 8. jQuery Support
    9. 9. Known Issues
    10. 10. Download jQueryO http://jQuery.com
    11. 11. Use jQueryO Store the jQuery library on your own computer,O Use the hosted jQuery library from Google or Microsoft. O Google O <script type="text/javascript" src=“http//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jqu ery.min.js”></script> O Microsoft O <script type="text/javascript" src=“http://ajax.microsoft.com/ajax/jquery/jquery- 1.9.0.min.js”></script>
    12. 12. Using jQuery
    13. 13. jQuery PhilosophyO “Write less, do more.” O Finding some elements, then do something with them O $(div).hide(); O Chaining multiple jQuery methods on elements O $(div).hide().text(new content).addClass("updatedContent").show() ; O Using the jQuery wrapper and implicit iteration
    14. 14. JavaScript Vs. jQuery JavaScript jQueryfor(i=0;i<=4;i++) $(“p”).html(“Change{ the page. ”);document.getElementsByTagName(“p”)[i].innerHTML=“Changethe page. ”;}
    15. 15. jQuery functionO Most used functionO Also called jQuery wrapperO jQuery() is also aliased as $()O Select node(s) from DOM returns a javaScript object that possesses a large number of useful predefined methods that can act on element(s).
    16. 16. Start at the start window loaded event Using JavaScript Using jQuerywindow.onload=function() $(“document”).ready( { function(){ alert(“Page alert(„‟Page loaded”);loaded”); }); } Executed when document is loaded not all page. Can be called multiple times
    17. 17. ExamplesO $(this).hide()O $("p").hide()O $("p.test").hide()O $("#test").hide()O $("p").last().addClass("selected");
    18. 18. Selectors
    19. 19. SelectorsO CSS 1–3 Selectors and jQuery selectors O All Selector O Element Selector O Class Selector O ID Selector O Multiple Selector O Attribute Selectors O Relation Selectors O Filter Selectors O Nth-filter Selector O Form Selector O Visibility Selector
    20. 20. All Selector (“*”)O Select all elements , $(“*”)O Select all elements in a certain context O $(“div#all”).find(“*”) O Selects all elements inside div with id all
    21. 21. Element SelectorO Selects all elements with the given tag, $(„tag‟).O Similar to document.getElementsByTagName()O Examples: O $(„p‟), select all p elements O $(„b‟), select all b elements
    22. 22. Class SelectorO $(„.className‟) O Selects all elements with the given class.O Examples: O $(„.red‟), all elements with class „red‟ O $(„p.red‟), all p elements with class „red‟
    23. 23. ID SelectorO Select a single element with the given id, $(„#id‟).O Similar to document.getElementById()O Examples: O $(„#all‟), select any element that have id=all O $(„h1#title‟), select only h1 element with id=titleO If the id contains characters like periods or colons must be escaped <div id="myID.entry[1]">id="myID.entry[2]"</div> <script>$("#myID.entry[1]").css("border","3px solid red");</script>
    24. 24. Multiple SelectorsO A list of selectors comma separetedO $(“selector1,selector2,selector2”)O Example: O $(“div,span,p.myClass”), selects all div, all span and all p with class=“myClass”
    25. 25. Attribute SelectorsO $(„[attr=“value”]‟): O attribute of exact valueO $(„[attr|=“value”]‟): O attribute with value equal to value or starting with value followed by „–‟O $(„[attr*=“value”]‟): O attribute with a substring as valueO $(„[attr~=“value”]‟): O attribute with a value containing a given word, delimited by spaces.
    26. 26. Attribute Selectors (Cont’d)O $(„[attr$=“value”]‟): O attribute with a value ending exactly with a given string.O $(„[attr!=“value”]‟): O attribute with a value not equal string or attribute not found.O $(„[attr^=“value”]‟): O attribute with a value beginning exactly with string.O $(„[attr]‟) O has the attributr specifiedO $(„[attrfilter1][attrfilter2]‟) O Multiple attribute selector
    27. 27. Relation SelectorsO $(“parent > child”), selects all direct children O e.g $(“ol > li”)O $(“parent descandant”), selects all descandant of parent O e.g $(“ol li”)O $(“prev + next”), select next adjacent sibling of prev onlyO $(“prev ~ siblings”), select all next siblings that follows prev
    28. 28. Filter SelectorsO $(“:even”), select even elements (0 indexed)O $(“:odd”), select elements with no childrenO $(“:first-child”), select all first child of elementsO $(“:first-of-type”), select all first child of elements of same typeO $(“:first”), select first element matchedO $(“:last”), select last element matchedO $(„:parent‟), select parent element
    29. 29. Filter SelectorsO $(“:animated”), select all animated elementO $(“:contains(text)”), select elements that contain the specified textO $(“:empty”), select elements with no childrenO $(“:has(selector)”), select element which contains atleast one element matching selector
    30. 30. Filter SelectorsO $(“:eq(n)”), select element with n indexO $(“:gt(n)”), select element with index greater than nO $(“:lt(n)”), select element with index less than nO $(“:not(selector)”),select all elements that don‟t match selector
    31. 31. Filter SelectorsO $(“lang(language)”), select element specified languageO $(“:header”), select all headers h1,h2,….O $(“:image”),select all elements of type imageO $(“:root”), select root of document
    32. 32. Nth-Filter SelectorsO :nth-child()O :nth-last-child()O :nth-of-type()O :nth-last-of-type()
    33. 33. Form SelectorsO $(“:button”), select all buttons (<button>,<input type=“button”>)O $(“:file”), select all elements of type file.O $(“:checkbox”), select all checkboxesO $(“:checked”), match all checked elementsO $(“:selected”), match all selected elementsO $(“:disabled”), match all disabled elementsO $(“:focus”), select element currently focused.
    34. 34. Form SelectorsO $(“:enabled”), select all enabled elementsO $(“:input”), select all input, textarea, select and button elements.O $(“:password”), select all element of type passwordO $(“:radio”), select all element of type radioO $(“:reset”), select all element of type resetO $(“:submit”), select all element of type submitO $(“:text”),select all elements of type text
    35. 35. Visibility filtersO $(“:hidden”), select all hidden elementsO $(“:visible”), select all visible elements
    36. 36. AttributesO Methods that get and set DOM attributes of elements O .addClass() O .attr() O .hasClass() O .html() O .prop() O .removeAttr() O .removeClass() O .removeProp() O .toggleClass() O .val()
    37. 37. .addClass()O .addClass( className ): Adds the specified class(es) to each of the selected elements.O .addClass( function(index, currentClass) ): function return class name(s) to be added to the existing class name(s). Receives the index position of the element and the existing class name(s) as arguments. Within the function, „this‟ refers to the current element in the set.O Adds a class not replaces already set classes
    38. 38. .attr()O .attr( attributeName ): Get the value of attribute for the first selected element.O To get the value for each element individually, use a looping construct such as .each() or .map() method.O Returns undefined for attributes that have not been set.
    39. 39. .attr()O .attr( attributeName, value ): Set an attribute with value for the selected elements.O .attr( attributes ): attributes is a plain object of attribute-value pairs to set.O .attr( attributeName, function(index, attr)): function(index, attr) is a function returning the value to set. „this‟ is the current element. Receives the index position of the element in the set and the old attribute value as arguments.
    40. 40. .hasClass()O .hasClass( className ): returns Boolean, to determine whether any of the matched elements are assigned the given class.
    41. 41. .html()O Get the HTML contents of the first element in the selected elements or set the HTML contents of every matched element. O .html() O .html( htmlString ) O .html( function(index, oldhtml) )
    42. 42. .prop()O Get the value of a property for the first selected element in or set one or more properties for every matched element. O .prop( propertyName ) O .prop( propertyName, value ) O .prop( properties ) O .prop(propertyName, function(index, oldPropertyVal ue))
    43. 43. .prop() versus .attr()O selectedIndex, tagName, nodeName, nodeTyp e, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method.
    44. 44. <input type="checkbox" checked="checked" />For the previous element: O elem.checked true O Will change with checkbox state O $(elem).prop("checked")true O Will change with checkbox state O elem.getAttribute("checked") "checked” O Initial state of the checkbox; does not change O $(elem).attr("checked”)  "checked” O Will change with checkbox state
    45. 45. Remove FunctionsO .removeAttr(attrName): O Remove attribute for each of the selected elementsO .removeClass([className]): O Remove a one or more classes or all classes of each of the selected elementsO .removeClass(function(index,class)) O The function returns one or more classes to be removed, it no classes are specified, all classes are removed.O $(‘p’).removeClass(‘myClass anotherClass’);
    46. 46. Remove Functions (Cont’d)O .removeProp(PropName): O Remove a property for the selected elements.
    47. 47. .toggleClass()O .toggleClass( [className] ): O One or more class names (separated by spaces) to be toggled for selected elements.O .toggleClass( className, switch ) O className: One or more class names (separated by spaces) to be toggled for each element in the matched set. O switch: A Boolean value to determine whether the class should be added or removed.O .toggleClass( [switch ] )O .toggleClass( function(index, class, switch) [, switch ] ) O function(index, class, switch): A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.
    48. 48. .val()O .val() O Get the current value of the first element in the matched elements.O .val( value ) O Set the value of each element in the selected elements.O .val( function(index, value) )
    49. 49. Events
    50. 50. Event Binding FunctionsO Any event has 3 overloads 1. Takes a function(eventObject) O A function to execute when the event is triggered. 2. Takes 2 parameters: eventData, function(eventObject) O An object containing data that will be passed to the event handler. O A function to execute when the event is triggered. 3. With no arguments, it is not a binding function but it triggers the event
    51. 51. Browser EventO .error(), Bind event handler to the “error” eventO .resize(), Bind event handler to the “resize” eventO .scroll(), Bind event handler to the “scroll” event
    52. 52. Loading EventO .load(), Bind event handler to the “load” eventO .unload(), Bind event handler to the “unload” eventO .ready(), execute when DOM is fully loaded
    53. 53. Form EventO .blur(), Bind event handler to the “blur” eventO .change(), Bind event handler to the “change” eventO .focus(), Bind event handler to the “focus” eventO .select(), Bind event handler to the “select” eventO .submit(), Bind event handler to the “submit” event
    54. 54. Keyboard EventO .keydown(), Bind event handler to the “keydown” eventO .keypress(), Bind event handler to the “keypress” eventO .keyup(), Bind event handler to the “keyup” event
    55. 55. Mouse EventO .click(), Bind to the “click” eventO .dblclick(), Bind to the “dblclick” eventO .mouseup(), Bind to the “mouseup” eventO .mousedown(), Bind to the “mousedown” eventO .mouseout(), Bind to the “mouseout” eventO .mouseover(), Bind to the “mouseover” event
    56. 56. Mouse EventO .hover(), Bind one/two handlers to be executed when the mouse enters and leavesO .mouseenter(), Bind to be fired when mouse entersO .mouseleave(), Bind to be fired when the mouse leavesO .mousemove(), Bind to the “mousemove” event
    57. 57. Event ObjectO Works cross browsersO Guaranteed to be passed to the event handlersO Properties: O target, element that initaited event O pageX, x coordinates mouse position O pageY, y coordinates mouse position O which, key/mouse key/button pressed O data, if sent in binding function, data passed
    58. 58. Height and Width
    59. 59. Remember
    60. 60. Element dimensionsO .height(), Get/Set element heightO .innerHeight(), Get element height + padding but not borderO .innerWidth(), Get element width + padding but not borderO .offset(), Get/Set element coordinates relative to the document O Coordinates is an object with 2 properties {top , left}O .outerHeight(boolean), Get the element height + padding + border, and optionally marginO .outerWidth(boolean), Get element width+ padding + border , and optionally marginO .position(), Get element coordinates relative to the offset parent O Coordinates is an object with 2 properties {top , left}O .width(), Get/Set element width
    61. 61. DOM
    62. 62. ManipulationO .after() O $(.inner).after(<p>Test</p>); O Insert p after all elements with class=„inner‟O .insertAfter() O $(<p>Test</p>).insertAfter(.inner); O Insert p after all elements with class=„inner‟O .append() O $(.inner).append(<p>Test</p>); O Insert p as last child of elements with class=„inner‟O .appendTo() O $(<p>Test</p>).appendTo(.inner); O Insert p as last child of elements with class=„inner‟
    63. 63. ManipulationO .prepend() O $(.inner).prepend(<p>Test</p>); O Insert p as first child of all elements with class=„inner‟O .clone() O Create deep copy of selected elementO .before() O $(.inner).before(<p>Test</p>); O Insert p before elements with class=„inner‟O .insertBefore() O $(<p>Test</p>).insertBefore(.inner); O Insert o before elements with class=„inner‟
    64. 64. ManipulationO .replaceAll() O $(<h2>New heading</h2>).replaceAll(.inner); O All elements with class=„inner‟ are replaced by h2O .replaceWith() O $(div.inner).replaceWith(<h2>New heading</h2>); O All divs with class=„inner‟ are replaced by h2O .wrap()/ .unwrap()/.wrapAll()/.wrapInner()
    65. 65. Effects andAnimation
    66. 66. Hide/Show EffectO .hide(), Hide the matched elements.O .show(), Display the matched elements.O .toggle(), Display or hide the matched elements.O http://api.jquery.com/category/effects/basi cs/
    67. 67. Fading EffectO Adjust the opacity of elements.O .fadeIn(), Display elements by fading to opaque.O .fadeOut(), Hide elements by fading to transparent.O .fadeTo(), Adjust the opacity of the elements.O .fadeToggle(), Display or hide the matched elements by animating their opacity.O http://api.jquery.com/category/effects/fading/
    68. 68. Sliding EffectO .slideDown(), Display elements with a sliding motion.O .slideUp(), Hide elements with a sliding motion.O .slideToggle(), Display or hide elements with a sliding motion.O http://api.jquery.com/category/effects/sliding/
    69. 69. Custom Effects .animate()O Perform custom animation of a set of CSS properties.O http://api.jquery.com/animate/
    70. 70. .delay()O Set a timer to delay execution of subsequent item in queueO .delay(duration [, queueName])
    71. 71. Store arbitrary data
    72. 72. .data()O jQuery‟s data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript objects.O Also can use the method on regular JavaScript objects and listen for changes.
    73. 73. .data()O Setter: O .data( key, value ) O .data( obj ) O An object of key-value pairs of data to update.O Getter: O .data( key ) O Return value O .data() O Return object with all key-value pairs stored
    74. 74. ExamplesO $(body).data(foo, 52);O $(body).data(bar, { myType: test, count: 40 });O $(„body‟).data(„foo‟);O $(„body‟).data();
    75. 75. HTML 5 data-*O http://ejohn.org/blog/html-5-data- attributes/O Valid custom data attributes added to any node.O Must start with data-
    76. 76. HTML 5 data-*O <div data-role="page" data-last- value="43" data-hidden="true" data- options={"name":"John"}></div>O $("div").data("role") === "page";O $("div").data("lastValue") === 43;O $("div").data("hidden") === true;O $("div").data("options").name === "John";
    77. 77. .removeData()O .removeData( [name] ) O A string naming the piece of data to delete.O .removeData( [list ] ) O An array or space-separated string naming the pieces of data to delete.
    78. 78. Add yourfunctions.
    79. 79. jQuery.fnO To write your own jQuery pluginO To create a shortcut for a set of functions you use often.
    80. 80. jQuery.fnjQuery.fn.yourFunction = function() { // function logic}$(div).yourFunction()
    81. 81. NoteO When using a jQuery selector, it can return multiple elements to work with O example $(div) usually matches several divs on the pageO Wrap the body of the function in $(this).each() to be sure every match is affectedO Return $(this), to sustain chainingO In some cases, other information needs to be returned, for example $(element).width() would probably return a number.
    82. 82. jQuery Ajax
    83. 83. $.ajax()O jQuery.ajax( url [, settings ] ), Returns: jqXHR O Perform an asynchronous HTTP (Ajax) request.
    84. 84. $.ajax()O Some Settings: O async: boolean default: true O complete: function(jqXHR,textString) O success: function(resp) O data: string or object
    85. 85. References[1] http://jquery.com/[2] http://learn.jquery.com[3]http://mathiasbynens.be/notes/css-escapes[4]Head First jQuery, O‟Reilly, RyanBenedetti, Ronan Cranley

    ×