JQuery
From Helpful
| For more webdev-related articles, see the webdev category. Among the more interesting are general webdev notes, Javascript related notes, CSS notes, browser peculiarities, jQuery |
Contents |
Basics
Introductionary examples
jQuery is one of a few major javascript libraries that aims to make JS coding simpler and productive. Things such as creating node content, applying events to nodes, and selecting the nodes in the first place.
jQuery is primarily on selections. A query object repreesnts a selection of DOM elements, which you can do something with general-purpose node functions can be called on one of these objects. To get a feel of what jQuery code looks like:
//Select all elements with the class 'headerClass', set/overwrite some CSS styling $('.headerclass').css({color:"#993300", fontWeight:"bold"}); // or add an outline to every element on the page: $('*').css('outline','1px solid red') // Functions may alter the set, and usually return the same selection they took // so you can chain on further functions, e.g.: $('.headerclass').css({fontWeight:"bold"}).addClass("highlight"); // It may return a different selection, when that makes sense (e.g. navigating around elements) $('img').parents(); //elements with images directly in them //show outline on element and its parent (to get an idea of padding and such) $('img').css('outline','1px solid red').parents().css('outline','1px solid red'); // the above functions were per-node getters. They can also be other things, such as: // - things that apply to the whole set: alert( 'There are '+$("div").size()+' divs on this page' ); // - things that operate only on the first element $("div").html(); // ...since you usually want some logic for each of these elements, e.g. using $.each // - triggering registered events $('#tags span').click() // - per-node event function registration $('#tags span').click( function(){alert('I am now clickable');} ) // Many of these things use .each internally, which is also occasionally useful to use directly, // For example, to assign a *different* handler function to each: $('#tags span').each(function(index) { //'this' refers to the element currently being handled (so $(this) creates a selection of one) $(this).click( function(){ alert('I am now clickable. At the time, I was item numero '+index); } ); }); // Some functions can be used as both setters and getters. // For example, HTML is strings-to-DOM and DOM-to-strings: $('body').append('<div id="foo"><b>'+$('title').html()+ '</b><br/> Like an apparition <div>you don\'t seem real at all</div></div>'); // (Note: as per jquery docs, html() returns only the first element's contents // instead of for all elements, which mostly just makes sense) // Or, say, outlines on everything on the page, with random colors function randomcolor(){ return '#'+ Math.floor(16+225*Math.random()).toString(16)+ Math.floor(16+225*Math.random()).toString(16)+ Math.floor(16+225*Math.random()).toString(16); } $('*').each(function(){ $(this).css('outline','1px solid '+randomcolor()); }); // Note that $('*').css('outline','1px solid '+randomcolor());}) is valid code // but only executes randomcolor() once so would color everything the same. //More complex example: // Make each h2 element with the 'title' class toggle // the visibility of the next div sibling when clicked' '' $('h2.title').click(function(){ $(this).next('div').toggle() })
For an overview of what functions are available in the jQuery core, see cheat sheets such as this one.
For more complete reference, see the API, in visual browser form such as in jquery api, jquery api browser, or visual jquery, or just the relevant sections of the documentation wiki (which should be the most up-to-date; few of the browsable references currently list prevAll() or nextAll(), new in 1.2).
See also various tutorials.
Element selection - selectors
A query string can be both CSS-style selectors or simple XPath, so will easily handle id, class, relational position and other useful tests.
Note that jQuery interprets it, which removes any browser inconsistencies, and allows some advanced tests and pseudo-classes. Again, see cheat sheets, and e.g. the jQuery API reference for selectors.
Basic selectors:
- $('p') - all paragraph elements
- $('span,div') - all spans and divs
- $('.classy') - all elements with class 'classy' set
- $('img.lower') - all img elements with class 'lower' set
- $('#id_335') - the element with id="id_335"
These usually go a long way.
Further CSS-style selectors
- $('p a') - direct or indirect children (decendants)
- $('p>a') - direct children
- $('th+td') - directly following sibling
- $('input~') - all singlings
- $('input~div') - specific singlings
Attribute-based selectors
- $('a[@title]') - things with title attribute
- $('a[@title="Image 1."]') - equivalence
- $('a[@title^="Im"]') - starts with
- $('a[@title$="."]') - ends with
- $('a[@title*="mage"]') - contains
- $('a[@title*="mage"][@alt*="mage"]') - multiple tests
Pseudoclasses, positional (indices are 0-based):
- positional in selection
- $('a:first'), $('a:last'), $(':eq(2)') - select first, last, and third link (...thing in the selection)
- $('a:gt(2)'), $('a:lt(2)') - select fourth and later elements, select first two
- :even, :odd - you can guess by now.
- Positional within document sibling set, in other words elements that are themselves the:
- :first-child, :last-child
- :nth-child(index)
- :only-child
Pseudoclasses, by content:
- $('*:empty') - everything without children
- $('*:parent') - everything that does have children (is a parent)
- $('a:contains("click")') - links that probably say 'click here' - naughty naughty
- $('div:has(a)') - divs with links in them (directly or indirectly)
- :not(selector) is mild magic that effectively negates sense of the inner selector. Examples:
- $('div:not(a)'): divs that do not have an a directly under them
- $('a:not(:gt(2))') - inner selector is '<2', so result is '>=2'
- $('*:not(:parent)') gives the same results as $('*:empty')
Pseudoclasses, forms:
- :input,
- :text, :password, :radio, :checkbox
- :button, :submit, :image, :reset
- :file
- :hidden
- :checked, :selected
- :enabled, :disabled
Pseudoclasses, styling:
- :hidden, :visible
- :animated
- :header: refers to h1 through h6
If you need more that you cannot easily build with the above, question whether what you are wishing for can't be done in another way, or look at plugins such as Extra selectors for JQuery.
Element selection - code
You'll often use.filter() is also quite useful, in case you can't do all your selection in one go, you can filter down a selection with another query.
The element-centric variations are also occasionally useful:
- $('query',element) searches the dom subtree under a specific element. (An alternative for the same would be $(element).find('xpquery'))
- $(element) constructs a selection from a single DOM element reference, or from an array of them.
This also allows $(window) and $(document), though note that you should have jQuery loaded in each to actually use jQuery across documents.
Note $ is just a very short reference to an object called jQuery; jQuery===$, and you can extend jQuery by adding functions to that object
Events
jQuery comes with its own event binding functions, which also handle multiple handlers automatically. You shouldn't use other ways of triggering events at the same time (e.g. onsomething="" attributes) since that can interact badly.
One of the useful basics you should know about is:
- $(function() { code here } ), which is is a shorthand for $(document).ready(function(){code here}) - i.e. gets executed when the page is loaded (...enough that you can start using the DOM).
To work on selected elements, you bind functions to events supported by jQuery though a function.
For example, you can make the last paragraph you clicked larger than the others - and, oh, yellow. The following adds as many click handlers as there are p tags:
$('p').click(function() { $('p').css('font-size','100%').css('background-color','transparent'); $(this).css('font-size','120%').css('background-color','#ffa'); });
This also demonstrates how this is the DOM element, so has to be jQuery-ized again before using it that way. Also that, since this is a function like any other, you can use new jQuery objects if you like.
Helper functions
These work on more primitive data instead of element lists:
- $.each(o,f) can iterate over objects, arrays,and hashes, so you can do:
h={'a':2,3:'d'}; a=[5,6,7,8]; $.each( h, function(i) { alert('['+i+']: '+this); } ) $.each( a, function(i) { alert('['+i+']: '+this); } )
- $.grep(a,f[,b]) arrays (filtering) (can be positive and negative filter, see third argument)
- $.map(a,f) for arrays
- $.merge(a,othera) merges arrays. (also filters out duplicates)
- $.extend(o,other) lists and hashes with others.
Usage summary
AJAX
There are a number of variations for many purposes. Most basic functions take a URL, an optional parameter map, and an optional callback funtion. Note this is a success callback only(verify) - but note you can regularly use a global error/complete handler instead of one for each request.
Various simple ways
If you are fetching things to be put into the DOM, you can use:
- .load( url[,data[,callback]] ) - Do fetch, parse as HTML, enter data into DOM
- .loadIfModified( url[,data[,callback]] )
The ...IfModified variants do a conditional fetch based on Last-Modified headers (presumably jQuery stores the last modified time in window-global state).
If you want to handle the data yourself, you want one of the following helper functions. They return a XMLHttpRequest object, but you can usually ignore it and do your work in the callback, which gives you the fetched data.
- $.get( url[,data[,callback]] ), a basic GET
- $.getIfModified( url[,data[,callback]] )
- $.post( url[,data[,callback]] ), a basic POST
And special cases:
- $.getJSON( url[,data[,callback]] ), in which the callback data is an object evaluated from the fetched JSON
- $.getScript( url[,callback] ), load and execute a script:
The hard way
If you want more control on the fetch, use the function the above are base on, $.ajax(), which takes only a map, in which you can set:
- url: the URL
- type: 'GET' or 'POST' (default: GET)
- data: more parameters, processed into the URL unless you use processdata:true
Callbacks:
- beforeSend: passes the XMLHttpRequest, allowing you to use setRequestHeader()
- error: error handler
- success: success handler that passes the fetched data - often simpler than:
- complete: called on any result (success, error, abort()). Passes in the XMLHttpRequest and a string describing the type of result, one of 'success', 'error', 'timeout', 'notmodified', or 'parsererror'.
- global: whether or not to trigger the global handlers for this request (default is true)
Some handle-things-for-me options:
- processData: true is default. False leaves data as request data in POSTs
- ifModified: true or false (default: false)
- timeout: timeout for this specific request. null/0 disables timeout (default), otherwise a number in milliseconds.
- dataType: one of
- 'xml' - return XML structure (Note that Content-Type headers also help - for example, xml types will trigger 'xml' treatment)
- 'html' - return plain text (script tags are apparently evaluated)
- 'script' (eval()uated in global context)
- 'json' (returns eval() of data)
- 'jsonp' (verify)
- async: defaults to true, asynchronous requests. If set to false, makes request synchronous
On Timeouts
- You can manually call abort() on a XMLHttpRequest
- a timeout or abort() will set readyState=0 and trigger the error() and complete() callbacks (verify)
Global setup, global callbacks
You can set some global settings to apply to all requests via
- $.ajaxSetup(), sets global setings. You can pass any option you can pass to on $.ajax()
This is useful to do things like make things GET that would normally be POST
You can also add global callback handlers like:
- ajaxSend ( func ) (think beforeSend)
- ajaxError( func )
- ajaxComplete ( func )
- ajaxSuccess ( func )
- ajaxStart ( func ) and ajaxStop ( func ) are events reflecting whether there are or aren't any current requests. Useful for things like 'loading...' messages.
Related: Form encoding
You may also be interested in serialize() and plugins like jQuery Form Plugin, which allow you to select form elements and serialize them into a query string, allowing you to imitate a form submit via an AJAX call.
Plugins
See primarily the the plugins page. Plugins themselves add functions on the jQuery ($) object when loaded.
Some random interesting ones:
- Interface
- hovertips plugin / JTip / Tooltip
- date selector (apparently based on another date picker)
- AJAXable editing
- lightbox-like: greybox / thickbox / slightly Thickerbox / modalContent
- Pretty checkboxes: http://kawika.org/jquery/checkbox/
clueTip
| These are primarily notes This is probably not going to be complete in any real sense, and exists to contain bits of useful information. |
Seems flexible in that you can get it to do clickable popup windows and and link/image hovertips, and load from title attribute, a local DOM element, and AJAX it in.
Will use hoverIntent when it is available (but does not require it). hoverIntent can be useful when you want hover tips to be smarter about recognizing mouse deceleration.
Tip contents:
- from title="something"
- $('a.title').cluetip({splitTitle: '|'});
- ...that example splits title and contents from the same text
- from in-DOM contents via a selector (suggestion is a hidden div referenced via an #identifier selector)
- use {local:true} in options,
- add selector in rel, e.g. rel="#hint01"
- from AJAX:
- URL in rel, e.g. rel="ajax.html"
- (default when there is a rel, unless you specify local:true or splitTitle(verify)),
- There are some added rules for <a> tags so that you can differentiate between content to ajax in and content to link to.
Tip styling:
You can add your own styling by setting cluetipClass:'something', then overriding the css you want to (This is also used to use existing themes, see http://plugins.learningjquery.com/cluetip/#subdetails4).
http://plugins.learningjquery.com/cluetip/#subdetails2
Options:
See http://plugins.learningjquery.com/cluetip/#options.
Overriding defaults can be done by setting values in $.fn.cluetip.defaults, for example:
var _qtd = $.fn.cluetip.defaults; _qtd['local']=true; _qtd['cluetipClass']='jtip'; _qtd['activation']='click'; _qtd['mouseOutClose']=false; _qtd['sticky']=true; _qtd['width']='350'; _qtd['arrows']=true; _qtd['leftOffset']=29; _qtd['closePosition']='title'; _qtd['closeText']='<img src="img/x.png" alt="close"/>'; _qtd['cluezIndex']=1101;
Unsorted:
If you use arrows, you probably want more leftOffset (30ish)
You can make tips abort viewing by having adding an onActivate function and having it return false.
Since there is only one cluetip visible ever, and it has DOM id cluetip, you can easily refer to it. For example, you can have a clicks elsewhere on the page close the cluetip with something like the following:
$('body').click(function(){ $('#cluetip').hide(); });
(this does assume that you don't use the return-false-to-stop-events hack anywhere.)
jEditable
The last editable code I used looked something like:
$('.editable').mouseover( function(){$(this).addClass('hover')} ).mouseout( function(){$(this).removeClass('hover')} ).editable( 'url.save',{indicator:'Saving...', submit:'OK', onblur:'ignore', type:'textarea', rows:8, width:'none', } );
Notes:
- The mouseovered class is there for highlighting, a visual cue about what you can click to edit, for example:
.editable { background:#fffff8; border:1px solid #ccc; } .editable.hover { background:#ffffaa; }
- An area is only clickable if it has a background color rather than the default transparent, so make sure it has a color set.
- You may also want to make sure it has width and height, so that it won't be unclickable when it shows an empty string. A div with some padding helps.
- submit:'OK', onblur:'ignore' means things stay editable until you submit them by pressing an 'ok' button. This is probably the easiest to understand to users.
- For visual consistency, and because the content size estimation isn't always nice on relatively small, I fairly consistently use the same look, type:'textarea', rows:8
- The indicator can also be '<img src="whatever">' (as the jEditable examples show)
- The width is set on creation time, but it isn't too smart and may be a few pixels too wide. To set it via your stylesheets, you should set width:'none' first. (see also cssclass) You could also add somewhat iffier hacks, such as the CSS .editable *[name='value'] {width:95% !important;}
The AJAX part consists of
- it sending the typed text to the server,
- (server-side processing and likely) database storing, and sending back whatever the field should show.
This looks a little complex, perhaps, but it enables writing of some useful behaviour.
For example, you can taking a string that you'll interpret as HTML to show, safety-strip-and-transform it server-side, storing the cleaned version in the database, and sending it back; the next edit will show the cleaned version and should be (almost) identical to the version you stored (there is some handling of <, > and & that you may want to watch).
Also, you can avoid showing an empty string. Imagine the following implementation: If a database entry is an empty string, you can create the HTML-to-become-jeditable with a constant string, like '(click here to add)' . Once your server-side code gets this code, you can you can test for / remove that exact string. You can then store an empty string, but still send that same same '(click here to add)' , back to be displayed - also to avoid an empty, unclickable field.
Note that you usually want to strip()/trim() whitespaces.
History
| This article/section is a stub — probably a pile of half-sorted notes and assertions some of which may well be wrong, and not verified as a whole. Feel free to add or refine. |
[3] fixes the back button in major browsers.
In the doc's onload, you have to register a function that takes a hash value and does whatever needs to happen to the page:
$.history.init(loader_callback);
The given example also adds code to replace regular <a href="#thing"> style links with replacement onclick handlers (using rel="history"; a class may be simpler/cleaner) that call whatever centralized #-based reload function you've written. In some cases this allows you to add some graceful degradation, but if you're going for full-on scripting, you may wan to use $.history.load directly.
Tooltip
I wanted to use this as an alternative for the basic title="" attributes that does line wrapping on all browsers, and a no-brainer drop-in at that.
By default the text goes into a h3. The plugin optionally splits into a h3 and a p, but that's extra work at HTML generation time, so I chose to strip the h3's major formatting with something like:
#tooltip h3 { font-size: medium; font-weight:normal; font-family: sans-serif; padding:.7em 1em .7em 1em; margin:0px; } #tooltip { border: 1px solid #aaa; background: #ffe; /* The opacity's here for kicks. It'll work in at least FF and IE */ opacity:0.95;-moz-opacity:0.95; filter:alpha(opacity=95); }
It means the following is enough for a page:
$('[@title]').Tooltip({showURL:false,delay:0});
Unsorted
Profiling
Using firebug will probably only tell you that CPU time is going to jquery functions like unique and inArray, which often means your selectors are not very efficient. To figure out which selectors those are, try the profile plugin.
Simple extensions
For example, I wanted a 'what does this select' test for debugging once:
// Quick and dirty jquery functions to put an outline() or border() on a selection. // can take their respective css styles; defaults to '#777 solid 1px' for both. if (window.jQuery) { jQuery.fn.outline = function(args){ if (!args) args='#777 solid 1px'; $(this).css('outline',args); return this; }; jQuery.fn.border = function(args){ if (!args) args='#777 solid 1px'; $(this).css('border',args); return this; }; //If you're even lazier with typing: jQuery.fn.o = jQuery.fn.outline; jQuery.fn.b = jQuery.fn.border; } //Now you can do things like $('.fork').outline();
See also
- Getting started, a useful overview of basic and intermediate jQuery
- learningjquery.com
- jQuery wiki
References:
Also:
Unsorted
http://net.tutsplus.com/tutorials/javascript-ajax/20-helpful-jquery-methods-you-should-be-using/

