dom scripting toolkit - jquery

44
The DOM Scripting Toolkit: jQuery Remy Sharp Left Logic

Upload: remy-sharp

Post on 17-May-2015

16.779 views

Category:

Technology


3 download

DESCRIPTION

Detailed presentation on the jQuery API with a few details about jQuery you may not have used yet.

TRANSCRIPT

Page 1: DOM Scripting Toolkit - jQuery

The DOM Scripting Toolkit: jQueryRemy SharpLeft Logic

Page 2: DOM Scripting Toolkit - jQuery

Why JS Libraries?

• DOM scripting made easy

• Cross browser work done for you

• Puts some fun back in to coding

Page 3: DOM Scripting Toolkit - jQuery

Why jQuery?

• Lean API, makes your code smaller

• Small (16k gzip’d), encapsulated, friendly library - plays well!

• Plugin API is really simple

• Large, active community

• Big boys use it too: Google, BBC, Digg, Wordpress, Amazon, IBM.

Page 4: DOM Scripting Toolkit - jQuery

What’s in jQuery?

• Selectors & Chaining

• DOM manipulation

• Events

• Ajax

• Simple effects

Page 5: DOM Scripting Toolkit - jQuery

$ function

Page 6: DOM Scripting Toolkit - jQuery

$

• Selectors

• DOM elements or raw HTML

• “Ready” functions

Page 7: DOM Scripting Toolkit - jQuery

$

• $(‘ul’)

• $(document.createElement(‘ul’))

• $(‘<ul />’)

• $(fn)

Page 8: DOM Scripting Toolkit - jQuery

Selectors$(‘#emails a.subject’);

Page 9: DOM Scripting Toolkit - jQuery

Selectors

• “Find something, do something with it”

• CSS 1-3 selectors at the core of jQuery

• Custom selectors

Page 10: DOM Scripting Toolkit - jQuery

CSS Selectors

$(‘div’)

$(‘div.foo’)

$(‘a[type=”application/pdf”]’)

$(‘tr td:first-child’)

Page 11: DOM Scripting Toolkit - jQuery

Tricky Selector

<div id=“content.block” />

$(‘#content.block’) // won’t work :-(

$(‘#content\\.block’) // will work :-)

Page 12: DOM Scripting Toolkit - jQuery

Custom Selectors

$(‘div:visible’)

$(‘:animated’)

$(‘:input’)

$(‘tr:odd’)

Page 13: DOM Scripting Toolkit - jQuery

Custom selectors

• Roll your own

$.expr[‘:’], { within: ‘jQuery(a).parents(m[3]).length > 0’});

$(‘a.subject’).is(‘:within(“#email”)’);

Page 14: DOM Scripting Toolkit - jQuery

Selector Performance$(‘#email’) // same as getElementById$(‘.email’) // like getElementsByTagName

// using context$(‘div.email’)$(‘#emails .subject’)$(‘.subject’, this)

// Cachingvar $subjects = $(‘#emails .subject’);

Page 15: DOM Scripting Toolkit - jQuery

Chaining$(‘#emails .subjects’) .click() .addClass(‘read’);

Page 16: DOM Scripting Toolkit - jQuery

Chaining

• jQuery returns itself *

• We can use the selector once, and keep manipulating

* except when requesting string values, such as .css() or .val()

Page 17: DOM Scripting Toolkit - jQuery

Chaining Example

// simple tabs$(‘a.tab’).click(function () { // tabs = $(‘div.tab’) $tabs .hide() .filter(this.hash) // refers to page.html#hash .show();});

Page 18: DOM Scripting Toolkit - jQuery

More Chaining

var image = new Image();

$(image) .load(function () { // show new image }) .error(function () { // handle error }) .attr(‘src’, ‘/path/to/large-image.jpg’);

Page 19: DOM Scripting Toolkit - jQuery

Working the DOM$(this).addClass(‘read’).next().show();

Page 20: DOM Scripting Toolkit - jQuery

DOM Walking

• Navigation: children, parent, parents, siblings, next, prev

• Filters: filter, find, not, eq

• Collections: add, end

• Tests: is

$(‘div’) .find(‘a.subject’) .click(fn) .end() // strip filter .eq(0) // like :first .addClass(‘highlight’);

Page 21: DOM Scripting Toolkit - jQuery

Manipulation

• Inserting: after, append, before, prepend, html, text, wrap, clone

• Clearing: empty, remove, removeAttr

• Style: attr, addClass, removeClass, toggleClass, css, hide, show, toggle

var $a = $(document.createElement(‘a’)); // or $(‘<a>’)$a.css(‘opacity’, 0.6).text(‘Click!’).attr(‘href’, ‘/home/’);$(‘div’).empty().append(a);

Page 22: DOM Scripting Toolkit - jQuery

Data

• .data() clean way of linking data to element

• Storing data directly against elements can cause leaks

• All handled by jQuery’s garbage collection

$(el).data(‘type’, ‘forward’);

var types = $(‘a.subject’).data(‘type’);

$(‘a.subject’).removeData();

Page 23: DOM Scripting Toolkit - jQuery

Events$(‘a.subject’).click();

Page 24: DOM Scripting Toolkit - jQuery

DOM Ready

• Runs after DOM, but before images

$(document).ready(function () {})

// or as a shortcut:

$(function () {})

Page 25: DOM Scripting Toolkit - jQuery

Binding

• Manages events and garbage collection

• Event functions are bound to the elements matched selector

• Also supports .one()

$(‘a.reveal’).bind(‘click’, function(event) { // ‘this’ refers to the current element // this.hash is #moreInfo - mapping to real element $(this.hash).slideDown();}).filter(‘:first’).trigger(‘click’);

Page 26: DOM Scripting Toolkit - jQuery

Helpers

• Mouse: click, dlbclick, mouseover, toggle, hover, etc.

• Keyboard: keydown, keyup, keypress

• Forms: change, select, submit, focus, blur

• Windows: scroll

• Windows, images, scripts: load, error

Page 27: DOM Scripting Toolkit - jQuery

Custom Events

• Roll your own

• Bind to element (or elements)

• Trigger them later and pass data

$(‘div.myWidget’).trigger(‘foo’, [123/*id*/]);// id access via // .bind(‘foo’, function (event, id, etc) {})

Page 28: DOM Scripting Toolkit - jQuery

Event Namespaces

• Support for event subsets via namespaces

• If you don’t want to unbind all type X events - use namespaces

$(‘a’).bind(‘click.foo’, fn);

$(‘a’).unbind(‘.foo’);

Page 29: DOM Scripting Toolkit - jQuery

Ajax$.ajax({ url : ‘/foo’, success : bar });

Page 30: DOM Scripting Toolkit - jQuery

Ajax Made Easy

• Cross browser, no hassle.

• $.ajax does it all

• Helpers $.get, $.getJSON, $.getScript, $.post, $.load

• All Ajax requests sends:X-Requested-With = XMLHttpRequest

Page 31: DOM Scripting Toolkit - jQuery

Simple Ajax

/* Loads the #links element with the content from link.html matched in the selector */

$(‘#links’).load(‘link.html #links li’);

Page 32: DOM Scripting Toolkit - jQuery

JSON for Data

• Uses eval for conversion

• Use JSONP for cross server data (flickr, twitter, delicious, etc)

• JSON simple to use, and less space than XML

Page 33: DOM Scripting Toolkit - jQuery

Twitter Example

// Run when the DOM has completed.// i.e. don’t hang on a script request$(funtion () { var url = ‘http://www.twitter.com/statuses/user_timeline/rem.json?callback=?’; $.ajax({ dataType: ‘jsonp’, url: url, success: function (data) { $(‘#status’).html(data[0].text); // update with my latest tweet } });});

Page 34: DOM Scripting Toolkit - jQuery

$.ajax$(‘form.register’).submit(function () { var el = this; // cache for use in success function $.ajax({ url : $(this).attr(‘action’), type : ‘post’, data : { ‘username’ : $(‘input.username’, this).val() }, beforeSend : showValidatingMsg, // function dataType : ‘json’, success : function (data) { // do something with data - show validation message }, error : function (xhr, status, e) { // handle the error - inform the user of problem console.log(xhr, status, e); } }); return false; // cancel default browser action});

Page 35: DOM Scripting Toolkit - jQuery

Effects$(this).slideDown();

Page 36: DOM Scripting Toolkit - jQuery

Base Effects

$(‘div:hidden’).show(200, fn);$(‘div:visible’).hide(200);$(‘div’).fadeIn(200);$(‘div’).slideDown(100);

$(‘div’).animate({ ‘opacity’ : 0.5, ‘left’ : ‘-=10px’ }, ‘slow’, fn)

Page 37: DOM Scripting Toolkit - jQuery

Utilities$.browser.version

Page 38: DOM Scripting Toolkit - jQuery

Utilities

• Iterators: each, map, grep

• Browser versions, model and boxModel support

• isFunction

Page 39: DOM Scripting Toolkit - jQuery

Core Utilities

• jQuery can plays with others!

• Good guys come last

$ === jQuery; // true$ === $j; // false

$j = $.noConflict(); // store jQuery in $j

$j === $; // false$j === jQuery; // true

Page 40: DOM Scripting Toolkit - jQuery

Plugins$(‘#emails .subjects’).doMagic()

Page 41: DOM Scripting Toolkit - jQuery

Plugins

• Simple to write

• Makes your code more reusable

• Don’t break the chain!

Page 42: DOM Scripting Toolkit - jQuery

Simple Plugin

jQuery.fn.log = function () { // returning continues the chain return this.each(function() { if (this.nodeName == ‘A’) { console.log(this.href); } });};

$(‘a’).log().filter(‘[hash=#first]’).log()

Page 43: DOM Scripting Toolkit - jQuery

Core Utilities

• Extend jQuery, merge objects and create settings from defaults

var defaults = { ‘limit’ : 10, ‘dataType’ : ‘json’ };var options = { ‘limit’ : 5, ‘username’ : ‘remy’ };

var settings = $.extend({}, defaults, options);

// settings = { ‘limit’ : 5, ‘dataType’ : ‘json’, ‘username’ : ‘remy’ }