69
Introduction To jQuery Dave Berthiaume Thomson Reuters November 30, 2011

Iniciando com jquery

Embed Size (px)

DESCRIPTION

Iniciando com jquery

Citation preview

Page 1: Iniciando com jquery

Introduction To jQuery

Dave BerthiaumeThomson Reuters

November 30, 2011

Page 2: Iniciando com jquery

• Open source JavaScript library/framework

• Created by John Resig in Jan. 2006

• Mantra: “Faster, smaller and more extensible”

• Cross-browser compatible– IE 6+, Firefox 2+, Safari 2.0+, Opera 9+

• Fully supported by Microsoft (with Intellisense)

• Very small footprint

What is jQuery?

2

Page 3: Iniciando com jquery

• Built with plug-in architecture

• Easy to learn / use

• Chaining methods

• Unobtrusive Javascript

• CSS v1-3 compatible

• Namespacing (plays nice with other libraries)

• Great docs and community

• Designed to change the way you write Javascript

What is jQuery?

3

Page 4: Iniciando com jquery

• jQuery() function– Everything starts with a call to jQuery()– Since it’s called so often, the $ variable is set up as an

alias to jQuery(). (Cobalt doesn’t use the $ shortcut)

• Basic structure:

FindSomething.DoSomething

$(SomethingToFind).DoSomething();

How Does It work?

4

Page 5: Iniciando com jquery

• To find something, we can use common CSS syntax:– $(css selector)– This is known as a “selector”– Returns a jQuery object containing an array of elements

that match the selector– The returned jQuery object is known as a “collection”,

“wrapper” or “wrapped set”

• The returned object contains a number of predefined methods that can act on the group of elements returned by selector

Selector Basics

5

Page 6: Iniciando com jquery

• $(“img”)

– Selects all images

• $(“p a”)

– Selects all links nested under a paragraph

• $(“div.myClass”)

– Selects all divs with a class of “myClass”

• $(“#myElement”)

– Selects element with an id of “myElement”

• $(“#nav li.current a”)

– Selects all links under any list item with class=“current” that exist under the “nav” element

Simple Selector Examples

6

Page 7: Iniciando com jquery

Custom Selectors

7

:checkbox Selects checkboxes

:checked Selects checkboxes or radio buttons that are checked

:contains(foo) Selects elements containing the text “foo”

:disabled Selects disabled form elements

:header Selects elements that are headers (<h1>, etc)

:input Selects form elements (input, select, textarea, button)

:not Negates the specified filter

:selected Selects option elements that are selected

:submit Selects submit buttons

These are just a few of the 20+ available

Page 8: Iniciando com jquery

• :checkbox:checked:enabled– Selects checkboxes that are enabled and checked

• input:not(:checkbox)– Selects non-checkbox <input> elements

• div p:not(:hidden)– Selects all visible <p> elements nested under a div

Using Custom Selectors

8

Page 9: Iniciando com jquery

Selecting By Position

9

:first :only-child :even and :odd

:last :nth-child(n) :eq(n)

:first-child :nth-child(even|odd) :gt(n):last-child :nth-child(Xn+Y) :lt(n)

• p:odd

– Returns every odd paragraph element

• li:last-child

– Returns last item of each list (last child of parent element)

• td:eq(2)

– Returns third table cell

• Selectors start counting from 0 (except :nth-child, which starts from 1 for CSS compatibility)

Page 10: Iniciando com jquery

More Selector Examples

10

$(“li:last”) Selects last list item

$(“tr:nth-child(1)”) Selects the first row of each table

$(“tr:nth-child(even)”) Selects even numbered table rows

$(“body > div:has(a)”) Selects direct <div> children of <body> containing links

$(“img[alt]”) Selects images with ALT attribute

$(“a[href*=jquery.com]”) Matches all <a> elements that reference the jQuery site

$(“a[href$=pdf]”) Selects links to PDF files

$(“a[href^=https://]”) Selects all links starting with “https://”

Powerful stuff!

Page 11: Iniciando com jquery

• Can leverage your knowledge of CSS selectors to get up and running fast

• Learn about the more advanced selectors jQuery supports:– http://docs.jquery.com/selectors

Selectors Summary

11

Page 12: Iniciando com jquery

Selectors Demo

12

Page 13: Iniciando com jquery

• Once we have our collection, we can execute jQuery commands on it:

$(“div.hideMe”).addClass(“co_hideState”);

– This is how we hide elements on the Cobalt platform

Commands

13

Page 14: Iniciando com jquery

• One of the most powerful features of jQuery is chaining

• jQuery commands (when finished with their action) return the same group of elements, ready for another action

$(“div.hideMe”).hide().addClass(“removed”);

– After the divs are hidden, we give them all a class “removed”

• DOM operations can be expensive. No need to loop over elements- All done behind the scenes

• Chains can continue indefinitely

Chaining

14

Page 15: Iniciando com jquery

• Get text:– $(“span#msg”).text();

• Set text:– $(“span#msg”).text(‘The thing was updated’);

• Get HTML (of first matched element):– $(“div.intro”).html();

• Set HTML:– $(“div.intro”).html(“<em>Look, HTML</em>”);

HTML

15

Page 16: Iniciando com jquery

• Get value (for first matching element):– var href = $(“a.nav”).attr(“href”);

• Set value:– $(“a.nav”).attr(“href”,”http://flickr.com”);

– $(“a.nav”).attr({

“href”: “http://westlaw.com”,

“id”: “westlaw” } );

• Remove attribute:– $(“#intro”).removeAttr(“id”);

Attributes

16

Page 17: Iniciando com jquery

• attr() also accepts a function:

$(“*”).attr(“title”, function(index) {

return “I am element “ + index +

“ with an id of “ + this.id;

});

– Runs through all elements on the page, setting the title attribute on each

Attributes

17

Page 18: Iniciando com jquery

• $(“#intro”).addClass(“highlighted”);

• $(“#intro”).removeClass(“highlighted”);

• $(“#intro”).toggleClass(“highlighted”);

• $(“div”).hasClass(“highlighted”);

– True if at least 1 element has the class

• $(“p”).css(“font-size”, “20px”);

• $(“p”).css({“font-size”: “20px”,

“color”: “red”});

CSS

18

Page 19: Iniciando com jquery

• css() also accepts a function:

$(“div.expandable”).css(“width”, function() {

return $(this).width() + 20 + “px”;

});

– Expands the width of all selected elements by 20px

• More on “this” later

CSS

19

Page 20: Iniciando com jquery

width()

height()– Replacement for style.width, style.height

– Computes and returns size of element

– Return numbers instead of strings

width(value)

height(value)$(“div.foo”).width(500); is same as:

$(“div.foo”).css(“width”, “500px”);

Height and Width

20

Page 21: Iniciando com jquery

• You can treat collections as arrays:– $(“div.myClass”).length = number of matched

elements

– $(“div.myClass”)[0] = the first <div> in the collection

• Or you can call methods on collections:– $(“div.myClass”).size() = number of matched

elements

– $(“div.myClass”).get(0) = the first <div> in the collection

Collections As Arrays

21

Page 22: Iniciando com jquery

• Adds elements to the collection:

$(“img[alt]”).addClass(“thickBorder”)

.add(“img[title]”)

.addClass(“seeThrough”);

• Can also be used to add new elements:$(“p”).add(“<div>Hi there!</div>”)

• This adds elements to the collection, not the DOM

The add() Method

22

Page 23: Iniciando com jquery

• Returns a subset of the wrapped set, based on position of elements within the set (zero-based)

• Returns a new set

$(“*”).slice(2,3);– Creates new set containing only the third element on the

page

$(“*”).slice(0,4);– Creates new set containing the first four elements on the

page

$(“*”).slice(4);– Creates new set containing all but the first four elements on

the page

The slice() Method

23

Page 24: Iniciando com jquery

• Filters out elements from the collection

• Can accept a selector or a function as a parameter

• Selector as parameter:

$(“img”).addClass(“seeThrough”)

.filter(“[title*=dog]”)

.addClass(“thickBorder”)– Reduces set to images with a title attribute containing ‘dog’

The filter() Method

24

Page 25: Iniciando com jquery

• When passed a function, invokes that function for each wrapped element and removes any whose method invocation returns false.

$(“td”).filter(function(){

return this.innerHTML.match(/^\d+$/);

})

– Creates a collection of <td> elements that contain a numeric value

• “this” is the current element being processed

The filter() Method

25

Page 26: Iniciando com jquery

• Searches through a collection, returns a new set that contains all elements that match a passed selector expression

• Powerful when combined with chaining:

$(“p”).find(“span”).fadeIn(); – Starts with all paragraphs and searches for descendant <span>

elements

– Same as $(“p span”)

• Can also be used with variable:

var mySet = $(“p”);

mySet.find(“span”);

The find() Method

26

Page 27: Iniciando com jquery

• filter() selects a subset of the already selected elements:– $(“td”).filter(expr)

• Removes any <td> elements that don't match the filter criteria

• find() selects a set of elements that are descendants of the already selected elements– $(“td”).find(“span”)

• Will find <span> elements inside <td> elements• Functionally similar to $(“td span”);

filter() vs find()

27

Page 28: Iniciando com jquery

• Easiest way to inspect or modify the component elements of a matched set

• Traverses matched set invoking the passed iterator function for each

• Can be used to easily set a property value onto all elements in a collection

$(“img”).each(function(n){

this.alt = “This is image[“ + n

+ “] with an id of “ + this.id;

});

The each() Command

28

Page 29: Iniciando com jquery

• Can also be used to collect all values for a specific property into an array:

var allAlts = new Array();

$(‘img’).each(function(){

allAlts.push(this.alt);

});

• To obtain property from just a single element, remember set can be treated like a Javascript array:

var altVal = $(‘#myImg’)[0].alt;

The each() Command

29

Page 30: Iniciando com jquery

• You can get new wrapped sets from existing sets based on relationships

• These methods return a new collection, leaving the original set unchanged:

$(“div:first”).nextAll().addClass(“after”); – Locates first <div> on page, creates new collection of all

siblings that follow, and assigns them a class

Relationships

30

children() nextAll() prev()

contents() parent() prevAll()

next() parents() siblings()

Page 31: Iniciando com jquery

Commands Demo

31

Page 32: Iniciando com jquery

$(“p”).each(function() {

var id = this.id, $this = $(this), images = $this.find(“img”);

});

• “this” is a DOM element

• Wrap in $() to make it a jQuery object

• Now you can issue jQuery commands

• $ prefix on variable name is a common convention to indicate it’s a jQuery object

What is “this”?

32

Page 33: Iniciando com jquery

• The $ function is versatile enough to perform many duties

• We can create DOM elements on the fly by passing the $() function a string that contains the HTML markup for those elements

• To create a new paragraph element:$(“<p>Hi there!</p>”)

– Creates a “disembodied” element that is not part of the DOM

Creating New Elements

33

Page 34: Iniciando com jquery

• Use one of jQuery’s DOM manipulation functions to attach new elements to the correct element

<p id=“foo”>Follow me!</p>

$(“<p>Hi there!</p>”).insertAfter(“#foo”);

Result:Follow me!

Hi there!

Add New Element To DOM

34

append() insertAfter() before()

appendTo() prepend() insertBefore()

insert() prependTo()

Page 35: Iniciando com jquery

<p id=“foo”>Follow me!</p>

$(“<p>”).html(“Hi there!”).insertAfter(“#foo”);

var container = $(“<div>”).html(“Div contents”).appendTo(“body”);

$(“<img>”).attr(“src”, “http://myimageurl”).appendTo(container);

Example: Add Elements To DOM

35

Page 36: Iniciando com jquery

• Some chains can generate multiple sets:

$(“img”).clone().appendTo(“#somewhere”);

– In this example, clone() creates a second set

– This is the set that appendTo() operates on

• What if we want to apply a command to the original set? You can’t tack it onto the existing chain.

Managing Chains

36

Page 37: Iniciando com jquery

• The end() method, when used in a jQuery chain, will back up to a previous wrapped set and return it as a value

• Subsequent operations will apply to the previous set

$(“img”).clone().appendTo(“#somewhere”).end().addClass(“beenCloned”);

• Without the end() command, addClass() would have operated on the set of clones

The end() Command

37

Page 38: Iniciando com jquery

• In 1.7, new on() and off() methods unify event handling in jQuery so there’s no need to use bind(), delegate() or the older live() calls. The syntax:

$(elements).on( events [, selector] [, data] , handler );

$(elements).off( [events] [, selector] [, handler] );

Event Model

38

Page 39: Iniciando com jquery

• Old methods (1.6 and earlier)

$("a#mylink").click( myHandler );

$("a#mylink").bind( "click", myHandler );

$("a#mylink").unbind( "click” );

• New method (1.7 and later)

$("a#mylink").on( "click", myHandler );

$("a#mylink").off( "click” );

Example: Bind a Click Event

39

Page 40: Iniciando com jquery

• Old method (1.6 and earlier)

$("a#mylink").live( "click", myHandler );

• New method (1.7 and later)

$(document).on( “click”, "a#mylink”, myHandler );

Example: On

40

Page 41: Iniciando com jquery

• Bad practice:

<a onclick=“doIt()” href=“foo.html”>Click!</a>

• Good practice:

<a href=“foo.html” class=“doIt”>Click!</a>

$(“a.doIt”).on( “click”, function(){

// Do something here

alert(“You did something. Woo-Hoo!”);

});

Unobtrusive Javascript

41

Page 42: Iniciando com jquery

$("a#mylink").on( "click", function () {

// your handler code goes here

});

Example: Anonymous Handler

42

Page 43: Iniciando com jquery

• NEEDS WORK FOR 1.7!!!

• jQuery provides shortcut commands to these specific event handlers:

Specific Event Binding

43

blur focus mousedown resize

change keydown mousemove scroll

click keypress mouseout select

dblclick keyup mouseover submit

error load mouseup unload

$(‘img’).click(function(event) {

alert(‘Hi there!’);

});

Page 44: Iniciando com jquery

• Cancel a default action and prevent it from bubbling:$(‘form’).on(‘submit’, function() {

  return false; 

})

• Cancel only the default action:– $(‘form’).on(‘submit’, function(event){   event.preventDefault(); });

• Stop only an event from bubbling:– $(‘form’).on(‘submit’, function(event){   event.stopPropagation(); });

Event Propagation

44

Page 45: Iniciando com jquery

• trigger() method:$(“:submit”).trigger(“click”); 

• Shortcut methods:

$(“:submit”).click();

• jQuery also supports custom events

Triggering Event Handlers

45

blur click focus select submit

Page 46: Iniciando com jquery

Zebra Stripe Demo

46

Page 47: Iniciando com jquery

You can store data about an element with the element :

Store:

$(“#myDiv”).data(“keyName”, { foo : “bar” });

Retrieve:

$(“#myDiv”).data(“keyName”); // { foo : “bar” }

Data Methods

47

Page 48: Iniciando com jquery

You can store data about an element with the element :

Store:

$(“#myDiv”).data(“keyName”, { foo : “bar” });

Retrieve:

$(“#myDiv”).data(“keyName”); // { foo : “bar” }

Callbacks Object

48

Page 49: Iniciando com jquery

• Some visibility functionality is built into core jQuery:$(‘h1’).hide();

$(‘h1’).show();

$(‘h1’).toggle();

• Works by setting “display” to “none” or “block”

Show / Hide Elements

49

Page 50: Iniciando com jquery

• The hide/show/toggle commands are more complex than you might think

• Calling them with no parameters instantaneously shows/hides the elements

• Passing a “speed” provides a gradual animation effect

• Optional parameters:– Speed

• Numeric (milliseconds)• Predefined string (‘slow’, ‘normal’, ‘fast’)

– Callback• Optional function invoked when animation completes

Show / Hide Elements Gradually

50

Page 51: Iniciando com jquery

$(‘h1’).hide();– Instantly hides elements

$(‘h1’).hide(2000);– Hiding takes place gradually over 2 seconds

$(‘h1’).hide(‘slow’);– Predefined ‘slow’ transition time

$(‘h1’).hide(‘fast’);– Predefined ‘fast’ transition time

Show / Hide Examples

51

Page 52: Iniciando com jquery

• Fading$(‘h1’).fadeIn();

$(‘h1’).fadeOut(2000);

$(‘h1’).fadeTo(‘fast’, 0.5);

• Sliding$(‘h1’).slideUp();

$(‘h1’).slideDown(‘slow’);

$(‘h1’).slideToggle(3000);

• show() / hide() / toggle() change scaling and opacity

• Fading/sliding methods effect only opacity

Fade / Slide Effects

52

Page 53: Iniciando com jquery

$(‘#block’).animate({

width: ‘+=60px’,

opacity: 0.4,

fontSize: ‘3em’,

borderWidth: ‘10px’

}, 1500);

• Many more effects available via plug-ins and the jQuery UI library

Custom Animations

53

Page 54: Iniciando com jquery

Effects Demo

54

Page 55: Iniciando com jquery

<div id=‘container’></div>

• Old school:

var span = document.createElement(‘span’);

span.innerHTML = ‘My Text’;

span.className = ‘myClass’;

var container = getElementById(‘container’);

container.appendChild(span);

Before / After Example

55

Page 56: Iniciando com jquery

<div id=‘container’></div>

• Old school:

var span = document.createElement(‘span’);

span.innerHTML = ‘My Text’;

span.className = ‘myClass’;

var container = getElementById(‘container’);

container.appendChild(span);

• With jQuery:

$(‘<span/>’).text(‘My Text’).addClass(‘myClass’).

appendTo(‘div#container’);

Before / After Example

56

Page 57: Iniciando com jquery

/// <reference path=“jquery-vsdoc.js"/>

$(function() { // executes at startup

$(“a”).on(“click”, function() {

var $this = $(this);

var linkText = $this.find(“img”).attr(“alt”);

if (linkText === undefined) {

linkText = $this.text();

}

West.Westlaw.Web.UI.Services.LinkTracking.

OnHyperlinkClick(linkText);

});

});

Putting It All Together

57

Page 58: Iniciando com jquery

Utility Functions

58

$.trim() Trims strings

$.each() Iterates through properties and collections

$.grep() Filters arrays

$.map() Iterates through array, translating items into new array

$.inArray() Returns index position of value in array$.makeArray() Converts array-like object into an array$.unique() Returns array of unique elements in

original array$.extend() Extend target object with properties of

other objects$.getScript() Dynamically load a script from url

Page 59: Iniciando com jquery

var myValue = [1, 2, 3];

jQuery.isFunction(myValue); // false

jQuery.isPlainObject(myValue); // false

jQuery.isArray(myValue); // true

jQuery.isNumeric(myValue[0]); // true

Type Checking

59

Page 60: Iniciando com jquery

• jQuery is extensible through plug-ins, which add new methods to the jQuery object

• http://plugins.jquery.com

Plug-ins

60

AJAX Animation and Effects Browser Tweaks Data DOM Drag-and-Drop Events Forms Integration JavaScript jQuery Extensions

Layout Media Menus Metaplugin Navigation Tables User Interface Utilities Widgets Windows and Overlays

Page 61: Iniciando com jquery

• Example plug-in usage:$(“img[src$=.png]”).ifixpng();

• Create your own, using $.fn:$.fn.hideLinks = function() {

return this.find(“a[href]”).hide().end();

}– fn is actually a shortcut to ‘prototype’

• Now use it:– $(“p”).hideLinks();

Plug-in Examples

61

Page 62: Iniciando com jquery

To enable Intellisense support, add this to the top of your .js file:

/// <reference path=“jquery-vsdoc.js"/>

Intellisense

62

Page 63: Iniciando com jquery

• http://docs.jquery.com

Documentation / Tutorials

63

Page 64: Iniciando com jquery

http://oscarotero.com/jquery/

http://jqapi.com/

Other Doc & Cheat Sheets

64

Page 65: Iniciando com jquery

Books

65

Designer-focused Developer-focused

Page 66: Iniciando com jquery

• Moved many user interface plug-ins into one core

• Supported by core contributors

• Includes (currently in v1.8):

jQuery UI

66

• Drag / Drop • Sortable• Selectables• Resizables• Autocomplete

• Calendar• Slider• Table• Tabs• Buttons

• Accordion• Shadow• Progress Bar• Magnifier

http://www.jqueryui.com/

Page 67: Iniciando com jquery

jQuery UI Demos

67

Page 68: Iniciando com jquery

• Official site:www.jquery.com

• jQuery Fundamentals: http://jqfundamentals.com

• Selector Tester:http://www.woods.iki.fi/interactive-jquery-tester.html

• Learn jQuery & Javascript for Free:http://learn.appendto.com/

• jQuery for Absolute Beginners:http://net.tutsplus.com/articles/web-roundups/jquery-for-absolute-beginners-video-series/

• Addy Osmani’s Blog: http://addyosmani.com/blog/?s=jQuery

Resources

68

Page 69: Iniciando com jquery

Questions?

69