Madeline Salocks home
Jquery Example Functionality Note
DOM Selection
  1. $('div').show('slow');
  2. $('body > div').show('slow');
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)
  • $('p[a]')
  • $("p:has(a)")
Get all paragraphs that contain one or more links (both work)
  1. $(this).parent().css('background-color', '#033');
  2. $(this).parent().parent().css('background-color', '#903');
Get parent element with the parent() function Example #2: Gets parent of parent
  1. $(this).parent().children('div:nth-child(4)').children(":first").css('background-color', '#633');
  2. var firsttab = $("#tabs li:first-child");
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)
  1. $("tr:first")...
  2. $(this).parent().find("div > ul > li:first")...
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'
  1. $(".hdr_also_link[rel='" + sel + "']").css('font-weight','bold');
  2. $('[class="highlighted"]').removeClass("highlighted").not("#home_link");
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'
  1. if ($('img').length){...}
    or
    if ($('img').length != 0) {...}
  2. if($(this).find('span').length) {
    alert('there is a span under this element');
    }
    if(!$(this).find('span').length) {
    alert('there is not a span under this element');
    }
Determine if an element exists based on checking the length Example #1: Returns true if image elements are found on the page
  1. if( $('#some_element').is(':visible') ) { ... }
  2. if( $('#some_element').is(':hidden') ) { ... }
Determine visibility of an element
  1. if ($("#first_name").val() == "Jane")
  2. $('select.foo option:selected').val(); // get the value from a dropdown select
    $('select.foo').val(); // get the value from a dropdown select even easier
    $('input:checkbox:checked').val(); // get the value from a checked checkbox
    $('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons
    reference
  3. str = $("input[name='radio_button_name']:checked").val(); // get the value of a checked radio button
Get the value of an element
DOM Manipulation
  1. $(this).text("some new text");
Set text of an element
  1. $(this).attr('id', 'new_id_name');
  2. $(this).attr('src', 'new_image.jpg');
Change an attribute of an element
  1. data = $("#some_data").html();
    $("#content").append(data);
  2. $("#some_element").html("phone: 999-999-9999" + generic_part + "email: janedoe@test.com");
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
  1. $(this).addClass("highlighted");
  2. $(this).removeClass("highlighted");
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
  1. $(".some_class, .some_other_class").css('background','#fff');
  2. or: $(".some_class, .some_other_class").css({'background' : '#fff'});
  3. $(".some_class, .some_other_class").css( {width : '30px', height : '10px'} )
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'.
  1. $("#single_item").val("hello");
Set the value of an element
  1. $("input:radio[@name=name_of_radio_button_choices]").click(function() {...});
Do something when a radio button is clicked
  1. $("#main").css({ opacity: 0.5 });
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
  • $(this).find("span").show('slow');
  • $(this).find("span").hide('fast');
  • $(this).find("span").show('normal');
  • $(this).find("span").hide('12000');
  • $(this).find("span").toggle('1000',somefunc());
  • $(this).find("span").slideDown('slow');
  • $(this).find("span").slideUp('12000',);
  • $(".someclass").slideToggle('fast');
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.
  • $(this).find("span").fadeIn('slow');
  • $("#wrapper").fadeIn(4000);
  • $(this).find("span").fadeOut('fast', somefunc());
  • $(this).find("span").fadeTo('slow', 0.25, somefunc()); //speed,opacity,callback
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
  1. $(this).find("span").animate({opacity: 0.50, left: '+=50', height: 'toggle'},"slow", "linear", some_callback_func_to_call_when_done()); //$(selector).animate({params},[duration],[easing],[callback])
  2. $("#id_of_some_element").animate({width: '1000', marginLeft: 0},"fast", "linear");
    toggle with
    $("#id_of_some_element").animate({marginLeft: '0px', width: '1000px', height: '25px'},"fast", "linear");
  3. $("#id_of_some_element").animate({ width: '30px', height:'25px'}, '1000');
    toggle with
    $("#id_of_some_element").animate({ width: '1000px', height:'25px'}, '1000');
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
  1. $("#some_element").draggable({
    containment: 'parent', // contain to parent element
    //containment: '#test', // contain to element with this id
    grid: [125, 125], // make the element snap to a 125x125 grid when moved
    scroll: false
    });
  2. $("#id_of_some_element").slideFadeToggle().draggable({ handle: "h3" });
  3. $("#draggable_element").draggable({ cancel: "p.non_dragging_area" });
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
  1. $('#main_content').load('html_include/main_content_all.html', function() {});
  2. $.ajax({
    url : "html_include/main_content_all.html",
    success : function (data) {
    $("#main_content").html(data);
    } });
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
  1. $(this).parent().parent().css( {'width' : '980px', marginleft : '0px', paddingleft' : '0px', zindex : 9999 } );
  2. $(this).parent().parent().css( {'width' : '980px', 'margin-left' : '0px', 'padding-left' : '0px', 'z-index' : 9999 } );
CSS Syntax: Use hyphens or not Both of the examples have the same result.
Jquery supports hyphens, but the properties must be in quotes.
  1. $('#some_container').delay(1200).hide('slow');
  2. setTimeout(function() { $('#some_container').hide('slide', { direction: 'left' }, 600) }, 800);
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

  1. $("#some_element").hover(function() { // on mouseover
    //do something
    } , function() { // on mouseout
    //do something
    });
  2. $(this).hover(function(){
    $(this).find('h2').addClass('collapse');
    }, function(){
    $(this).find('h2').removeClass('collapse');
    })
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)
  • $(window).width(); // returns width of window
    $(document).width(); // also returns width of window
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
  1. $("a").click(function() {
    $("body").append($(this).attr("href"));
    return false;
    }
  2. $("a").click(function(e) {
    $("body").append($(this).attr("href"));
    e.preventDefault();
    e.stopPropagation();
    }
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