jQuery
- jQuery API
- Shoestring - a good lightweight substitute (IE8+)
OnLoad
$(document).ready(function () { //document is ready } //...but this is the same and shorter... $(function(){ //document is ready }); //(actually it's a callback from the ready event)
Events
- Buttons etc: $('#btn').click(function() { ... });
- Form elements: $('#txt').change(function() { ... });
- Text elements: keydown, keypress and keyup (last doesn't recognize tabs and CR)
$('#txt').keypress(function(event) { if (event.keyCode == '13') event.preventDefault(); });
- focus/blur, focusin/focusout, hover
- Pre 1.7: $('#btn').bind("click", function() { alert("clicked");});
- 1.7+: $('#btn').on("click", function() { alert("clicked");});
- 1.7+ Delegated handler for all buttons in table: $('#table1').on("click", ":button", function() { alert("clicked");});
Creating Html
Alternatives to innerHTML
$('div#target').html('<p class="New">New html!</p>'); $('div#target').add('<p class="New">New html!</p>'); //the same //You can also create a jQuery object from an html string $('<p class="New">New html!</p>').appendTo($('div#target'));
$('div#target').wrap("<div class='marker'/>") is also useful.
Nested searches
$('div#target').children('p').addClass("x"); //immediate descendents $('div#target').find('p').addClass("x"); //any descendents $('div#target').click(function() { $('p', this).addClass("x"); //selector context $(this).find('p').addClass("x"); //is the same });
If you're doing lots of chaining, .end() is nice for popping up the chain.
Selectors
Some unusual variations.
- Attribute Starts With
- $('a[href^="http"]')
- $('a[lang|="en"]') //begins en- (hyphen)
- Contains
- $('a[href*="com"]')
- $('a[class~="active"]') //contains a word (spaces either side)
- Text: $("p:contains('world')") //NB: case sensitive
- Attribute Ends With: $('a[href$="jpg"]')
- Hierarchy
- $('div p') //all descendents
- $('div > p') //immediate child
- $('div:has(p)') //select the parent which has a descendent
- $("ul li:nth-child(1)") //1 indexed
- $(this).closest("ul") //closest parent-
parent("ul") is just one level,
parents("ul") may have multiple parents
Check selector found something:
if($("#field).length) {}
Iteration
$('div').each(function(index) { //iterate over a jQuery object }); //NOT THE SAME AS... $.each(myArray, function(index, value) { //iterate over an array (or map, in which case index==key) });
Array functions
- $.grep(myArray, function( return this==2; }) //no regexs!
- .map(function()...) maps/transforms arrays
Show/Hide
- .show()/ .hide() / .toggle()
- animation: .show('slow').hide('fast')
- callbacks:
$('me').show('slow', function() { $('me2'}.show('slow'); });
- You can turn off all animation by jQuery.fx.off = true
- Detect with :visible selector.
Forms and Ajax
- Read (input/select): $("text").val();
- Write: $("text").val("Hello");
- Radios/checkboxes read (jQuery 1.6+): $("radio").prop("checked") returns boolean true
$("radio").attr("checked") returns "checked" (<input type="radio" checked="checked" >) - Radios/checkboxes write (jQuery 1.6+): $("radio").prop("checked", true)
Serializing forms
For ajax / HTTP gets
- HTTP GET
- //NB: elements need "name="
var data = $("form").serialize();
//forward slashes,@,& are encoded, so decode (NB don't use decodeURI)
var qs = decodeURIComponent(data);
- //NB: elements need "name="
- JSON
- var data = $("form").serializeArray(); //creates an array of all form elements
var json = JSON.stringify(d); //if IE7 or older you'll need json2.js; native in modern browsers
- var data = $("form").serializeArray(); //creates an array of all form elements
Ajax post
var data = $("form").serializeArray(); //creates an array of all form elements var json = JSON.stringify(d); //if IE7 or older you'll need json2.js; native in modern browsers $.ajax({ type: "POST", contentType: "application/json", url: "WebService.asmx/WebMethodName", data: json, success: function (x) { alert(x.Message); } });
Ajax getting data
$.getJSON('WebService.asmx/WebMethodName', function(data) { ..}) doesn't allow any posts (input data) and parses the output with $.parseJSON().
On the lower level $.ajax() call, you can JSON.parse(s).
You can register a page handler for .ajaxError