| Jquery Example | Functionality | Note |
|---|---|---|
| DOM Selection | ||
|
Get all of a particular element | Example #1: Gets all divs Example #1: Gets all direct div children of the body (">" means only direct children) |
|
Get all paragraphs that contain one or more links (both work) | |
|
Get parent element with the parent() function | Example #2: Gets parent of parent |
|
Get child element(s) with the children() function | |
| $(".slide:last div:first").append("<span style='color:blue;'>something</span>"); | get first/last element | Using the :first and :last selectors, this gets the last element with the class 'slide' and then gets the first child div under that and appends a span |
| selection = $(this).parent().prev().find(".tab").attr("id"); | Get previous element with prev() function | This example gets the id for the element that has the class of 'tab' and is within the sibling element previous to the current element's parent |
| $("#some_element").next().attr("src", "images/some_image.gif"); | Get next element with the next() function | This example gets the next sibling to the current element and sets its src attribute |
| $this.closest('li').find('div.caption'); | Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree. | This example gets the nearest li element up the tree (and then finds a div with the class 'caption' under it) |
|
Get the first of a particular type of element | |
| $('input[@name=email]') | Get the input element with the name 'email' | |
| $('a[@href^="http://"]') | Get all the external links (links that start with 'http://') | Uses '^', the 'starts with' selector |
| $("a[href$=.pdf]") | Get all the PDF files (links that end with '.pdf') | Uses '$', the 'ends with' selector |
| $("td:empty)") | Get all the empty table cells | Uses the ':empty' selector, meaning there are no children (including text) |
| $("ul.topnav > li").css("border", "3px double red"); | Get children | Using the child selector (>), this gets all the li elements under the ul with class 'topnav' and sets a border |
| $("table.striped > tr:odd") | Get all the odd numbered rows in a table with the class 'striped' | |
|
Get an element with a specific attribute value |
Example #1: Looks for an element with class 'hdr_also_link' with a 'rel' attribute that has a specific value (and in this case that value is in a variable) Example #2: Finds all elements with class 'highlighted' and removes the class from all except for the element with id 'home_link' |
|
Determine if an element exists based on checking the length | Example #1: Returns true if image elements are found on the page |
|
Determine visibility of an element | |
|
Get the value of an element | |
| DOM Manipulation | ||
|
Set text of an element | |
|
Change an attribute of an element | |
|
Append HTML to an element | In the first example, a div with the id 'content' is populated with data from id 'some_data'. In the second example, some contact information is inserted into a div (and note the concatenation operator works to include a string variable). |
| $("#content *").remove(); | Remove HTML within an element | In this example, all the HTML within the id of 'content' is removed |
| $("a#" + sel).trigger("click"); | Force an event with trigger() | In this example, a click is executed on an anchor element with the id of the value in 'sel' |
|
$('#myphoto').attr('title', 'Photo by Madeline Salocks');
$('#myphoto').removeAttr('title'); |
Add and remove an attribute | |
| $("img").each(function (i) { ... } | Loop through like elements with each() to do/apply something to all | In this example, we are finding all img elements and doing something |
|
Apply a class dynamically to an element | Example #1: Applying a class called 'highlighted' to the current element Example #2: Removing a class called 'highlighted' from the current element |
|
Apply css to multiple selectors | In this example, css is applied to all elements with either the 'some_class' class or the 'some_other_class' class. The last example shows multiple css properties applied |
| $('#.a.b.c') | Select with multiple identifiers | In this example, only elements containing classes 'a', 'b', and 'c' are selected. (Note, for this intersection to work, there must be no space between the classes.) |
|
$(document).ready(function() { $('#test').live('click', function() { $('span',this).show(); return false; }); //init: $('span',this).hide(); }); ... show this is something this is something else
|
Use the second parameter to narrow selection to children of an element | In this example, the selection is narrowed to only spans that are within 'this'. |
|
Set the value of an element | |
|
Do something when a radio button is clicked | |
|
Apply opacity filter to a div | (By applying the opacity with jQuery, not only do you get valid CSS 2.1 markup, but you also get jQuery to handle Internet Explorer's "unique" CSS settings for you. —http://forum.jquery.com/topic/apply-50-opacity-to-a-div) |
| Rich Internet Application (RIA) Functions | ||
|
Basic show, hide, slide, and toggle(show/hide) | The speed parameter, if a number, is in milliseconds. If there is a callback function as second parm, that is the function to call once the animation has completed. |
|
Basic fade-in and fade-out | |
| $('#some_element').toggle('slide', { direction: 'left' }, 600); | Slide element to the left | |
| $(this).find("span").animate({height: 'show'},"slow", "linear"); | Custom animate element--with slow speed and linear easing | Note: need the height as one of the parameters |
|
Example #1: Custom animate element, going to 50% opacity, positioning (moving) 50px to left--with slow speed, linear easing, and then performing some_callback_func_to_call_when_done(); Setting height to 'toggle' toggles the height between 0 and full Example #2: Grows the element from right to left (however note: I've had problems with jerkiness when using margin-left this way) Example #3: Grows the element from left to right |
|
|
Make an element draggable |
Example #1: Makes the entire element draggable, and it's confined to its parent element, and also confined to a grid
Example #2: Makes an element draggable and assigns a specific part of the element to be the draggable handle--in this case the h3 element Example #3: Makes an element draggable and assigns a specific part of the element to be excluded from the dragging functionality-- in this case a paragraph element with the class 'non_dragging_area'. |
|
if( !$('#some_element').is(':animated')) { $('#another_element').fadeSliderToggle(); } else { setTimeout(function() { $('#another_element').fadeSliderToggle(); }, 1200); } |
Check if an animation is still in process | |
| Includes/Imports/Loads | ||
|
Include data or HTML from external file | |
| $.getScript('js/snippet1.js', function() { }); | Include external javascript | |
| $('#tabs a.tab').live('click', function() { ... } }); | Enable events for dynamic data using live(); .live() works for existing and future matching elements | Note: .live need not be put inside document ready; see this article: http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/ |
|
var testdata1 = { "firstName" : "Susie", "lastName" : "Q" }; ... $(document).ready(function() { $('#inline_json_data_here').html(testdata1.firstName); }); <div id="inline_json_data_here"></div> |
Display data from internal JSON object | |
|
external file test_json_1.js: { "firstName" : "John", "lastName" : "Doe" } $(document).ready(function() { $.getJSON("test_json_1.js", function( obj ) { for ( var property in obj ) { $("ul").append("<li>" + property + ": " + obj[property] + "</li>"); } }); }); <ul></ul> |
Display data from JSON object in external file | Note on keyword: 'prop' can be substituted for 'property' |
|
external file test_xml_1.js: <root> <item>Joe</item> <item>Jane</item> </root> $(document).ready(function() { $.ajax({ url: "test_xml_1.xml", success: function( xml ) { $(xml).find("item").each(function(){ $("ul.xml").append("<li>" + $(this).text() + "</li>"); }); } }); }); <ul class='xml'></ul> |
Display data from external XML file | |
| Miscellaneous | ||
|
Core Jquery library source from Google: "http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" (or other version) (O'Reilly recommends accessing JQuery this way.) Latest JQuery is also here: http://code.jquery.com/jquery-latest.min.js JQuery drag and drop library for script tag: http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js |
Links for accessing JQuery libraries via Google hosting | Note: occasionally an older version may do what you want more than a newer |
|
$.fn.myFunction = function() { ... } ... $('').myFunction(); // call the function |
Create your own JQuery function | |
|
if (jQuery.browser.msie) { // } |
Detect Internet Explorer | |
|
CSS Syntax: Use hyphens or not | Both of the examples have the same result.
Jquery supports hyphens, but the properties must be in quotes. |
|
Delay execution (in milliseconds) with delay() or setTimeout() | Useful for controlling animation; also useful for debugging sometimes Example #1: Delays by 1200 milliseconds Example #2: Delays by 800 milliseconds |
|
Toggle functions for opposite events | Example #2: The toggle functions are adding and removing a class to/from an h2 element within the current element on mouseover/mouseout respectively |
|
$('.draggable_element').mousedown(function(){ $('.flippable_and_draggable').css('z-index','999'); $(this).css('z-index','1000'); }); |
When there are several draggable elements with the same class, make the selected one always on top. | |
|
$(function() { $('#list').sortable({items: '> li:not(.pin)'}); }); |
Make one element of a sortable list unsortable (un-reorderable) | |
|
Get miscellaneous values | |
|
style: .odd { background: #f2f2f2; } script: $(document).ready(function() { $("tr:odd").addClass("odd"); }); |
Put zebra stripes on a table | |
|
jQuery.fn.equalCols = function(){ //Array Sorter var sortNumber = function(a,b){return b - a;}; var heights = []; //Push each height into an array $(this).each(function(){ heights.push($(this).height()); }); heights.sort(sortNumber); var maxHeight = heights[0]; return this.each(function(){ //Set each column to the max height $(this).css({'height': maxHeight}); }); }; //Usage jQuery(function($){ //Two examples of selecting the columns that need to be equal e.g $('div.column').equalCols(); $('#leftcol,#rightcol').equalCols(); }); |
Make columns equal height | |
|
Use return false or preventDefault() and stopPropagation() | Both examples have the same effect. preventDefault() prevents the default action from happening (for example, navigation on clicking an a tag); stopPropagation() prevents the event from bubbling up through the parents of the element; return false does both. |
|
$(document).ready(function() { $('.mysample_nav').live('click', function() { $('.mysample_content').hide(); var showit = $(this).attr('id'); showit += "_content"; $("#"+showit).show('slow'); /*other menu items-set to regular style*/ $(".mysample_nav").removeClass('mysample_nav_curr'); /*curr menu item-set to curr style*/ $(this).addClass('mysample_nav_curr'); return false; }); //init: $('.mysample_content').hide(); $("#firstitem_content").show('slow'); $("#firstitem").addClass('mysample_nav_curr'); }); ... <a href="" class='mysample_nav' id="firstitem">First Item</a> <a href="" class='mysample_nav' id="seconditem">Second Item</a> ... <div class="mysample_content" id="firstitem_content"> ... </div> <div class="mysample_content" id="seconditem_content"> ... </div> |
Simple code for showing a different div based on selection from a menu list | |