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
1. Julie Iskander
Lecturer at ITI
MSc. Communication and Electronics
2. Outlines
O Introduction and Using jQuery
O Selectors and Attributes
O Events
O Height and Width
O DOM Manipulation and Modification
O Effects and Animation
O Store arbitrary data and add your
functions.
O Ajax
4. Definition
O 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. John Resig
O 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. 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. jQuery
O Simplifies common scripting tasks
O Abstracts away browser-specific features
O Adds sophisticated effects
O Simplifies retrieving and manipulating
DOM
O Makes the DOM less scary
11. Use jQuery
O 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>
14. jQuery Philosophy
O “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
15. JavaScript Vs. jQuery
JavaScript jQuery
for(i=0;i<=4;i++) $(“p”).html(“Change
{ the page. ”);
document.getElementsByTagNa
me(“p”)[i].innerHTML=“Change
the page. ”;
}
16. jQuery function
O Most used function
O Also called jQuery wrapper
O 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).
17.
18. Start at the start
window loaded event
Using JavaScript Using jQuery
window.onload=function() $(“document”).ready(
{ function(){
alert(“Page
alert(„‟Page loaded”);
loaded”); });
}
Executed when document is
loaded not all page.
Can be called multiple times
22. Selectors
O 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
23. 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
24. Element Selector
O 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
25. Class Selector
O $(„.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‟
26. ID Selector
O 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=title
O 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>
27. Multiple Selectors
O A list of selectors comma separeted
O $(“selector1,selector2,selector2”)
O Example:
O $(“div,span,p.myClass”), selects all div, all
span and all p with class=“myClass”
28. Attribute Selectors
O $(„[attr=“value”]‟):
O attribute of exact value
O $(„[attr|=“value”]‟):
O attribute with value equal to value or starting with
value followed by „–‟
O $(„[attr*=“value”]‟):
O attribute with a substring as value
O $(„[attr~=“value”]‟):
O attribute with a value containing a given
word, delimited by spaces.
29. 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 specified
O $(„[attrfilter1][attrfilter2]‟)
O Multiple attribute selector
30. Relation Selectors
O $(“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 only
O $(“prev ~ siblings”), select all next siblings
that follows prev
31. Filter Selectors
O $(“:even”), select even elements (0
indexed)
O $(“:odd”), select elements with no children
O $(“:first-child”), select all first child of
elements
O $(“:first-of-type”), select all first child of
elements of same type
O $(“:first”), select first element matched
O $(“:last”), select last element matched
O $(„:parent‟), select parent element
32. Filter Selectors
O $(“:animated”), select all animated
element
O $(“:contains(text)”), select elements that
contain the specified text
O $(“:empty”), select elements with no
children
O $(“:has(selector)”), select element which
contains atleast one element matching
selector
33. Filter Selectors
O $(“:eq(n)”), select element with n index
O $(“:gt(n)”), select element with index
greater than n
O $(“:lt(n)”), select element with index less
than n
O $(“:not(selector)”),select all elements that
don‟t match selector
34. Filter Selectors
O $(“lang(language)”), select element
specified language
O $(“:header”), select all headers h1,h2,….
O $(“:image”),select all elements of type
image
O $(“:root”), select root of document
36. Form Selectors
O $(“:button”), select all buttons
(<button>,<input type=“button”>)
O $(“:file”), select all elements of type file.
O $(“:checkbox”), select all checkboxes
O $(“:checked”), match all checked elements
O $(“:selected”), match all selected elements
O $(“:disabled”), match all disabled elements
O $(“:focus”), select element currently focused.
37. Form Selectors
O $(“:enabled”), select all enabled elements
O $(“:input”), select all input, textarea, select and
button elements.
O $(“:password”), select all element of type
password
O $(“:radio”), select all element of type radio
O $(“:reset”), select all element of type reset
O $(“:submit”), select all element of type submit
O $(“:text”),select all elements of type text
39. Attributes
O 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()
40. .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
41. .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.
42. .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.
44. .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) )
45. .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))
46. .prop() versus .attr()
O selectedIndex, tagName, nodeName, nodeTyp
e, defaultChecked, and defaultSelected should
be retrieved and set with the .prop() method.
47. <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
48. Remove Functions
O .removeAttr(attrName):
O Remove attribute for each of the selected
elements
O .removeClass([className]):
O Remove a one or more classes or all classes of
each of the selected elements
O .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’);
50. .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.
51. .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) )
53. Event Binding Functions
O 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
54. Browser Event
O .error(), Bind event handler to the “error”
event
O .resize(), Bind event handler to the “resize”
event
O .scroll(), Bind event handler to the “scroll”
event
55. Loading Event
O .load(), Bind event handler to the “load” event
O .unload(), Bind event handler to the “unload”
event
O .ready(), execute when DOM is fully loaded
56. Form Event
O .blur(), Bind event handler to the “blur” event
O .change(), Bind event handler to the “change”
event
O .focus(), Bind event handler to the “focus”
event
O .select(), Bind event handler to the “select”
event
O .submit(), Bind event handler to the “submit”
event
57. Keyboard Event
O .keydown(), Bind event handler to the
“keydown” event
O .keypress(), Bind event handler to the
“keypress” event
O .keyup(), Bind event handler to the “keyup”
event
58. Mouse Event
O .click(), Bind to the “click” event
O .dblclick(), Bind to the “dblclick” event
O .mouseup(), Bind to the “mouseup” event
O .mousedown(), Bind to the “mousedown”
event
O .mouseout(), Bind to the “mouseout” event
O .mouseover(), Bind to the “mouseover” event
59. Mouse Event
O .hover(), Bind one/two handlers to be executed
when the mouse enters and leaves
O .mouseenter(), Bind to be fired when mouse
enters
O .mouseleave(), Bind to be fired when the mouse
leaves
O .mousemove(), Bind to the “mousemove” event
60. Event Object
O Works cross browsers
O Guaranteed to be passed to the event
handlers
O 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
63. Element dimensions
O .height(), Get/Set element height
O .innerHeight(), Get element height + padding but not border
O .innerWidth(), Get element width + padding but not border
O .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 margin
O .outerWidth(boolean), Get element width+ padding + border , and
optionally margin
O .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
65. Manipulation
O .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‟
66. Manipulation
O .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 element
O .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‟
67. Manipulation
O .replaceAll()
O $('<h2>New heading</h2>').replaceAll('.inner');
O All elements with class=„inner‟ are replaced by h2
O .replaceWith()
O $('div.inner').replaceWith('<h2>New
heading</h2>');
O All divs with class=„inner‟ are replaced by h2
O .wrap()/ .unwrap()/.wrapAll()/.wrapInner()
69. Hide/Show Effect
O .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/
70. Fading Effect
O 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/
71. Sliding Effect
O .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/
72. Custom Effects
.animate()
O Perform custom animation of a set of CSS
properties.
O http://api.jquery.com/animate/
73.
74.
75. .delay()
O Set a timer to delay execution of
subsequent item in queue
O .delay(duration [, queueName])
77. .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.
78. .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
80. 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-
81. 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";
82. .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.
86. Note
O When using a jQuery selector, it can return
multiple elements to work with
O example $('div') usually matches several divs on the
page
O Wrap the body of the function in $(this).each() to
be sure every match is affected
O Return $(this), to sustain chaining
O In some cases, other information needs to be
returned, for example $(element).width() would
probably return a number.
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”
<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:
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.