$(document) or $() = reference the document element $(document).ready(function) or $(function) = call function when DOM is ready $('css-selector').addClass('classname') = add classname to everything selected by CSS $('css-selector').removeClass('classname') = remove classname in everything selected by CSS .removeClass() - remove all classes $(css selector string or DOM node(s)) pattern matching in attrs: $('a[href$^!*=str]'), filters can be chained like xpath :eq(1) = select the 2nd element that matches previous selector :nth-child(1) = select elements that are 1st child of their parent :odd/:even = 0 indexed odd/even selector :visible = select visible elements (display != none) form custom selectors: :text, :checkbox, :radio, :image, :submit, :reset, :password, :file, :button - :input - input, textarea, select, button :enabled, :disabled - form elements that are enabled/disabled :checked, :selected - radio buttons/checkboxes, and selected option elements (respectively) can combine them: $(':radio:checked') $(':password, :text:disabled') union of both :password and :text:diabled .filter(...): Filters result sets. Takes selector string or function as argument $('tr:odd') == $('tr').filter(':odd') Add class to external links (this == a tag): $('a').filter(function() { return this.hostname && this.hostname != location.hostname; }).addClass('external'); .next() - goes to next sibling of each result .nextAll() - all next siblings of each result .prev(), .prevAll() .andSelf() - can combine with above to also select self .parent(), .children() .siblings('selector') - select matching siblings .end() - used when chaining.. revert to the previous result set Example chaining: $('td:contains(Henry)').parent().find('td:eq(1)') .addClass('highlight').end().find('td:eq(2)') .addClass('highlight'); Accessing DOM nodes: $('...')[i] $ conflicts - call jQuery.noConflict(); to free up $ to the previous library (e.g. prototype) and then can use jQuery(...) instead of $(...) for jQuery and $(...) for prototype .ready(function($) { // can use $ here }); Events: ------- .bind('click', function() { ... }); $(this) in a function selects the current element can write .click(...) instead of .bind('click', ...) in addition to all the standard js events, it provides: .toggle(fn1, fn2[, fn3, ...]) fired on click and .hover(fIn, fOut) fired on mousein/out .hover prevents event bubbling (does it?) .click performs event bubbling (click a child, parent's onclick is called) functions that handle events may take the event as a parameter .live('click', function(){ ... }); - binds for all current and future matched elements .die - unbinds .live bindings event.target contains the object that was actually clicked can use it to control bubbling can use event.target.id to let one click event handle various children - called event delegation Another way to stop propagation is event.stopPropagation().. add to innermost object event to stop bubbling To prevent default actions like clicking taking you to new page, onsubmit submitting a form, can call event.preventDefault() .unbind('click') - unbind all click events .unbind('click', function) - unbind a particular function on click event .unbind() - unbind all events When binding, can name the event e.g. bind('click.collapse', fn) and then unbind('click.collapse') .one is same as .bind except that it only runs the event once and then unbinds it .toggleClass('classname') - if classname exists, hide it.. else add it .is('selector') tests to see if the selected object matches the selector .hasClass('classname') tests to see if the selected object has the given class .trigger('click') triggers a click event. .click() also works keyboard events: if you want to know what key the user pushed, you should observe the keyup or keydown event; if you want to know what character ended up on the screen as a result, you should observe the keypress event target of a keyboard event is the one that has keyboard focus (can be anchor, form elements, elements with a tabIndex property etc) Effects ------- .css to .style what .addClass is to .className x.css('property') - get x.css('property', 'value') - set .show and .hide may take a parameter that indicates animation speed - 'slow', 'normal', or 'fast' which are 6, 4, and 2 secs respectively. If a numeric value is provided, the effect will take that many ms show/hide modify width/height while modifying opacity at the same time .fadeIn and .fadeOut only modify opacity and can replace show/hide .slideUp, .slideDown, and .slideToggle only modify the height All these methods also take an optional callback method that is called when the effect is complete For custom animations, use .animate, which has 2 forms .animate(cssMap[, speed, easing type, callback]); .animate(cssMap, optionMap); optionMap = { duration: 'value', easing: 'value', complete: f, queue: boolean, step: callback } To toggle a fade effect: .animate({opacity: 'toggle'}, 'slow'); shorthand values provided for CSS properties - show, hide, toggle Properties that can be animated: width, height, opacity, left, top, fontSize, margin, padding, and borderWidth Can also say {fontSize: '+=10px'} and it will animate the change from current size to 10px Can use .outerWidth()/.outerHeight to get an element's width/height Can queue effects by calling .animate(...).animate(...)... in optionMap, setting queue: false makes the animation start without waiting for the previous one to finish When chaining, other methods like .css() don't wait for animation to finish. If that is desired, can use a callback or else obj.queue(function(){ stuff... obj.dequeue(); })... It is important not to forget dequeue or the animation will stop Color animation plugin exists for animating colors DOM Manipulation ---------------- .attr(map), .attr(attrget), .attr(attr, val), .attr(attr, fn) - set attributes value can come from function: fn(index) { return "value"; } .removeAttr(attr) - remove attribute .each(fn([index])) - run function for each object matched $('').insertAfter('jquery-selector'); alternate syntax: $('jquery-selector').after(''); First one allows chaining on new code, second one on selected nodes .append('') .prepend('') .after('') .before('') .replaceWith('') - replace matched elements with arg .html('') - replace contents of matched elements with arg .empty() - remove all desc nodes .insertAfter('selector'); - insert as next sibling of selected nodes .insertBefore('selector'); - insert as previous sibling of selected nodes .prependTo('selector'); - insert as first child of selected nodes .appendTo('selector'); - insert as last child of selected nodes .replaceAll('selector'); - replace selected nodes with nodes selected by arg Can move elements using selector.insertAfter('selector'), etc. Copies will be made as necessary. Wrapping elements: .wrapX(elem or html) elements.wrap('
'); -
match1
match2
elements.wrapAll('
'); -
match1 match2
elements.wrapInner('
'); -
children
... Cloning: .clone() or .clone(true) where true allows cloning event handlers .text([val]) - get/set the combined text value of matched nodes .remove() - remove all matched elements AJAX ---- $('selector').load('url'); - replace contents of selected nodes with response of url .load uses GET when no params are passed, and POST when params are passed .load('url selector') - loads and filters content $.getJSON('jsonurl', callback); - request a page and treat response as json callback function takes 1 parameter: function(data) { $.each(data, function(index, entry) { // do stuff with entry['key']; // if entry['key'] is array then $.each it }); } JSON syntax [ { "entry1key1": "entry1value1", "entry1key2": "entry1value2" }, { "entry2key1": [ "entry2value1.1", "entry2value1.2" ] } ] $.getScript('jsurl'); - dynamically load a JS file $.get('anyurl', callback); - HTTP GET a URL passing the result to callback. If returned content is XML, it will return a DOM object. If it is JSON it will return a JS object, etc. $.get('url', dataMap, callback, type) - type can be xml, html, script, json, jsonp, text. dataMap contains the query part of the request Can use jQuery to help look for things in XML x= $(data).find('tagname:has(desctag[attr])'); x.attr('attr'); etc. AJAX Events - each takes a callback function and is invoked on every AJAX request: ajaxComplete ajaxSuccess ajaxError ajaxStart - callback takes no params ajaxSend - before sending ajaxStop - callback takes no params callback function in most cases takes event, xmlhttprequest, ajaxoptions thrownError is available in ajaxError can use the args to differntiate the source of the ajax request and behave accordingly or can use $.ajax JSONP = clientprovidedstring(JSON) $.getJSON(url + '?callback=?', ...) the 2nd ? is auto replaced Idea behind JSONP is that the client can create a function and the server can then return a string that calls the function providing its result as an arg $.ajax(map) where map can have the following params: async - true/false for sync/async beforeSend - call before sending request cache - true/false whether or not to use the browser cache complete - call when request finishes (after success/error) contentType - e.g. application/x-www-form-urlencoded data - object or string, becomes query string dataFilter(data) - user function to filter response and return filtered response dataType - the expected response type, html, xml, json, jsonp, etc. error - error callback global - whether or not to trigger global ajax event handlers ifModified - if true, request is successful only if modified (Last-Modified) jsonp - override the callback function name in a jsonp request username/password - the user/pass to send when an HTTP auth request is received processData - whether or not to process the data being sent into a querystring scriptCharset - force request to be processed in a certain charset success - callback on success, takes returned data as param timeout - timeout in ms url - the url to request type - GET or POST xhr - callback for creating the xmlhttprequest object X-Requested-With HTTP header is sent when jQuery performs a request Table Manipultion ----------------- Sorting a table using jQuery: - write code to catch the click event - determine column index - grab all rows and call .sort() on DOM array (.get()) with custom fn - call .append() on the table - can precompute sorting key (e.g. normalise capitalisation) for speed Can write a plugin function for jQuery: jQuery.fn.myFunction = function() { ... } something.myFunction(); // can access something in myFunction using "this" should return this to allow chaining Can store additional data in a jQuery object using: .data('key', 'value') and get using .data('key'); Tooltips: - on hover, show the tooltip, hide the tooltip - on mousemove, position the tooltip using event.pageX, event.pageY Passing data: .bind(event, data, fn) - can pass data to function. data becomes part of event .bind('click', {'foo': myVar}, function(event) { event.data['foo'] ... }); Helps avoid closure messups Forms: ------ In some cases may want to replace a tag: $('tag').each(function() { $(this).replaceWith('' + $(this).text() + ''); }); $(formelement).val('xxx'); sets the value of a form element, .val() gets it validation plugin exists autocomplete plugin is part of jquery ui Input masking - allow only numbers to be typed: .keypress(function(event) { if (event.which && (event.which < 48 || event.which > 57)) event.preventDefault(); }); .which reports the character represented by the key pressed. arrow keys, delete, etc have no character var formData = $('#myform').serialize(); // can now use formData as data jQuery form plugin has a better .serialize(); Shufflers/Rotators ------------------ jCarousel plugin can do carousel SerialScroll allows scrolling any content Plugins ------- jQuery Google Group - good place to discuss jQuery plugins/development http://groups.google.com/group/jquery-en/ Form plugin: Convert a form to AJAX $('#myForm').ajaxForm(); .ajaxForm({ target: '#log', // place server response into this selector beforeSubmit: validateForm, success: formSuccess, url: 'newsubmiturl', type: 'get/post', dataType: null, xml, script, or json where null = text/html, resetForm: true/false, // reset the form to original values on success clearForm: true/false // clear the form on success // other params, same as .ajax() }); .ajaxSubmit can also be used.. it submits a form using ajax.. allows more control .ajaxSubmit does not capture the element that cause the form to submit jQuery UI: - Color animator animates backgroundColor and color - addClass, removeClass, toggleClass now take an optional second arg for animation duration - animate({data}, 'speed', 'easing') - easeInQuart ends the animation 4 times faster than start. Alternate syntax animate({data}, {duration: '...', easing: '...'}); - easing examples: http://gsgd.co.uk/sandbox/jquery/easing/ - hide by exploding into n pieces: $('#stuff').effect('explode', {pieces: 16}, 800) .hide also works (same syntax) - interactions available: draggable, droppable, resizable, selectable, sortable - Sortables - create a list ol/ul and then $('#list').sortable(); .sortable({ opacity: .5, // when dragging, use 50% opacity cursor: 'move', // + cursor axis: 'y' // move up/down only }); css class ui-sortable-helper is applied on drag - widgets: accordion, datepicker, dialog, progressbar, slider, tabs - Dialog widget - like alert() except it's HTML $('selector').dialog(); They are resizable and draggable by default .dialog({ autoOpen: false, // need to call .dialog('open') to display title: 'My Dialog', open: callOnOpen, buttons: { 'my button': callOnClick, 'my button 2': callOnClick } }); - Widgets can be themed - jQuery UI ThemeRoller site can be used to create themes - http://ui.jquery.com/themeroller/ - Some useful plugins: - Autocomplete: http://plugins.jquery.com/project/autocompletex - Validation: http://plugins.jquery.com/project/validate - Jeditable: http://plugins.jquery.com/project/jeditable - makes normal elements editable - Masked input: http://plugins.jquery.com/project/maskedinput - Tablesorter: http://plugins.jquery.com/project/tablesorter - jqGrid: http://plugins.jquery.com/project/jqGrids (like excel worksheet) - Flexigrid (alternative to above): http://plugins.jquery.com/project/flexigrid - Jcrop (image cropping): http://plugins.jquery.com/project/Jcrop - Magnify (image magnification): http://plugins.jquery.com/project/magnify - FancyBox (lightbox clone): http://fancy.klade.lv/ - Thickbox (alternative to above): http://jquery.com/demo/thickbox/ - BlockUI (modal dialog): http://plugins.jquery.com/project/blockUI - jqModal (alternative to above): http://plugins.jquery.com/project/jqModal - Flot (graphical plots): http://plugins.jquery.com/project/flot (use VML in IE, in other) - Sparklines (simple inline graphs): http://plugins.jquery.com/project/sparklines - Event plugins: - hoverIntent (tries to prevent animations when not desired based on mouse speed) http://plugins.jquery.com/project/hoverIntent - Live query (.live alternative): http://plugins.jquery.com/project/livequery Plugin Development ------------------ Two syntax: jQuery.myFunction = function() { } jQuery.myFunction2 = function() { } - jQuery.extend({ functionOne: function() { }, functionTwo: function() { } }); Can create a namespace within jQuery's namespace: jQuery.myPlugin = { functionOne: function() { }, functionTwo: function() { } }; jQuery.fn.myObjMethod = function() { alert(this.length + " elements"); } Don't forget to return to allow chaining To return a different of nodes, put them in an array and then return this.setArray(myArr); However, that overwrites the top of the jQuery stack. Should instead use: this.pushStack(myArr); Using maps: jQuery.fn.myFunction = function(opts) { opts.zIndex // get {zIndex} } Can have default options for maps: var myMapDefaults = { myParam: 'myValue', ... } var opts = jQuery.extend(myMapDefaults, userMap); // userMap can be null can move defaults to .extend(jQuery.fn.shadow.defaults, userMap); Custom CSS selector: jQuery.extend(jQuery.expr[':'], { 'mySelectorExpr': function(element, index, matches, set) { } } element - DOM element under consideration index - Index of the DOM element within result matches - Array containing result of the regex used to match. For :a(b), matches[3] contains the text between (..) set - The entire set of DOM eements matched until this point Convention: Filename: jQuery.myPlugin.js for jQuery.myPlugin Use jQuery instead of $ Preserve chaining, use stacks when it makes sense Use maps End method definitions with ; Use ScriptDoc format - scriptdoc.org