introduction to jquery. jquery quick facts is a cross-compatible javascript library released in 2006...
TRANSCRIPT
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!
CSE 3345 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.
CSE 3345 4
Getting jQuery
• You can download and locally host a copy which can be downloaded here.
• Hotlink Google’s copy which is available here.
• I prefer hot linking to Google’s copy.
CSE 3345 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.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
CSE 3345 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 3345 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 3345 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 3345 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 3345 10
jQuery Selectors
Supports CSS selectors versions 1-31. 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 3345 11
jQuery selectors
• See here for complete list.
CSE 3345 12
Your turn<html> <head><title>Quiz</title></html> <body>
<div id="nav"> <a href="http://www.google.com">Google</a> <a href="http://www.bing.com">Bing</a>
<p class="warning">You should be careful!! jQuery is super powerful and may be harmful to small babies</p>
</div> </body></html>
-Select the google anchor element ( I can think of 5 ways to do this)-Select the element with an id equal to nav-Select the element with the class equal to warning
CSE 3345 13
jQuery Example Link
• http://jsfiddle.net/blinkmacalahan/UYANa/
CSE 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 elements containing block.
CSE 3345 25
CSS Methods .css()
• .css() – 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 3345 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 3345 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 3345 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 3345 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 3345 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 wastefulvar node = $('div')[0];$(node).css('color'); // "black"
//This example is useful$(document.body).css('display'); // "block"
CSE 3345 32
Subset of jQuery Events
• .click()• .dblclick()• .focus(), .focusin(), .focusout()• .hover()• .keydown(), .keyup(), .keypress()• .mousedown(), .mouseup()• .mousemove()• .ready()
CSE 3345 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 3345 34
.hover() example
• http://jsfiddle.net/blinkmacalahan/M5Ccz/
CSE 3345 35
Ways to use .hover()
• Fade in/out objects
• Make elements grow/shrink
• Change element’s class and take advantage of CSS
CSE 3345 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 3345 37
.css() revisited
• Using .css() as a setter method only modifies the element’s inline style.
• You can unset an applied inline styles by supplying an empty string a the property value.
• Note this does NOT remove a style that has been applied with a CSS rule in a stylesheet or <style> element.
CSE 3345 38
Unsetting inline CSS property //this removes any inline color style applied$('div:first').css('color', '');
CSE 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 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 3345 48
.fadeOut()
• Very similar to fadeIn() except for the following:1. Matched elements fade to transparent2. At the end of the animation, the element’s
display property is set to none.
CSE 3345 49
.fadeOut() Example$('img').fadeOut(100, function() {
alert("The element's display property value is now none");
});
CSE 3345 50
Premade hiding/showing animations
• .hide() – Hide the matched elements• .show() – Display the matched elements
CSE 3345 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 3345 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 3345 54
Premade slide animations
• .slideDown() – Display the matched elements with a sliding motion.
• .slideUp() – Hide the matched elements with a sliding motion.
CSE 3345 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 3345 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 3345 58
Custom Animation
• If you need more power than the premade animations, then you can make your own.
CSE 3345 59
.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 3345 60
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 3345 61
.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 3345 62
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 3345 63
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 3345 64
.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 3345 65
.each() example$('div').each( function(i) { console.log( i + ': ' + this.tagName +
' ' + $(this).text(););});
Store data with jQuery.data()
• Store arbitrary data associated with the specified element.
• Data is cleared when page reloads
jQuery.data(element, key, value)
CSE 3345 68
Get data with jQuery.data()
• Returns a value for the named data store on the element.
jQuery.data(element, key);
CSE 3345 69
jQuery.data() examplejQuery.data(document.body, 'foo', 'bar'); // 'bar'jQuery.data(document.body, 'foo'); // 'bar'
//In chrome $0 is shorthand for document.bodyjQuery.data($0, 'json', "{ 'name' : 'fred' }"); // "{ 'name' : 'fred'}"jQuery.data($0, 'json'); // "{ 'name' : 'fred'}"
jQuery.data($0, 'id', 52); // 52jQuery.data($0, 'id'); // 52
jQuery.data($0, 'isAwesome', true); // truejQuery.data($0, 'isAwesome'); // true
CSE 3345 70
Use can also do ajax with jQuery// Assign handlers immediately after making the request,// and remember the jqxhr object for this requestvar 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 abovejqxhr.always(function() { alert("second complete"); });
CSE 3345 71
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.