JQuery Notes

Some of this came from jquery.com, and some of this came from Learning jQuery 1.3 by Jonathan Chaffer and Karl Swedberg

Table of Contents

Basic Check 1

jquery.com or alert window (if jquery is loaded)

<script type="text/javascript">
$(document).ready(function(){
$("a.testclass").click(function(event){
alert("the link no longer took you to jquery.com");
event.preventDefault();
});
});
</script>

Basics

Adding class

Adding class to tag

<form>
<input type="button" value="make it bold"
onclick="makeitbold(); return(false);" />
<input type="button" value="unbold them"
onclick="makeitunbold(); return(false);" />
</form>

function makeitbold()
{
$("a").addClass("makeitbold");
}
function makeitunbold()
{
$("a").removeClass("makeitbold");
}

<style type="text/css">
a.makeitbold { font-weight: bold; }
</style>

Adding class to list

.horizontal {
float: left;
list-style: none;
margin: 10px;
}
.sub-level {
background: gray;
}
function changeorientation()
{
$('#selectedthings > li').addClass('horizontal');
}
function unchangeorientation()
{
$('#selectedthings > li').removeClass();
}
function addsublevel()
{
$('#selectedthings li:not(.horizontal)').addClass('sub-level');
}

Selectors

Basic

all of these and more from http://docs.jquery.com/Selectors
#id
$("#daID").css("border","3px solid red");
finds element with id "daID"
element
$("div").css("border","9px solid red");
matches all div elements
.class
$(".daClass").css("border","3px solid red");
matches all elements with class "daClass"
*
$("*").css("border","3px solid red");
matches everything
useful when combined with context to search in
selector1, selector2, selectorN
$("div,span,p.daClass").css("border","3px solid red");
finds the elements that match any of these 3 selectors

combinators and others

>
$('#selectedthings > li').addClass('horizontal');
selects child element
:not
$('#selectedthings li:not(.horizontal)').addClass('sub-level');
selects all things that are not the attribute.
^
$('a[href^=mailto:]').addClass('mailto');
selects all things that begin with
$
$('a[href$=.pdf]').addClass('pdflink');
selects all things that end with
*
$('a[href*=color]').addClass('colorlink');
selects all things match the item somewhere within

Attribute Selectors

Look for things that have a specific attribute (e.g. an image's alt attribute).
$('img[alt]')

Custom Selectors

:eq, :gt, :lt
$('div.horizontal:eq(1)
$('div#blah p:eq(1)').addClass('sub-level');
$('div#blah p:gt(1)').addClass('sub-level');
$('div#blah p:lt(1)').addClass('sub-level');
selects all things that are equal, greater than, or less than the attribute.
:odd, :even
$(.tr:odd').addClass('alt');
grab the odd or even rows (remember 0 based counting)
not the best because multiple tables on page will continue counting of rows (even/odd etc)...
:nth-child() with even, odd
$('tr:nth-child(even)').addClass('alt');
select the nth-child with given attribute
:contains
$('td:contains(2-2)').addClass('highlight');
matches entry that has value in it (note it is case sensitive)

1-1 1-2 1-3
2-1 2-2 2-3
3-1 3-2 3-3
4-1 4-2 4-3
5-1 5-2 5-3

1-1 1-2 1-3
2-1 2-2 2-3
3-1 3-2 3-3
4-1 4-2 4-3
5-1 5-2 5-3

Form selectors

:text, :checkbox, :radio, :image, :submit, :reset, :password, :file input elements with type attribute to match (excluding colon). :radio selects <input type="radio">
:input
textarea, select, button
:button
button
:enabled
form elements that are enabled
:disabled
form elements that are disabled
:checked
checked radio buttons or checkboxes
:selected
selected option elements

Selectors can be combined -
$(':password, :text:disabled')
means select all password inputs and diabled text inputs.

DOM traversal methods

.filter apply filter to search
$('tr').filter(':even').addClass('highlight');
OR
//highlight the a href urls that have hostnames that aren't the local hostname $('a').filter(function() {
return this.hostname && this.hostname != location.hostname;
}).addClass('highlight');
.next
.prev
$('td:contains(argh2)').next().addClass('highlight');
.nextAll
.prevAll
$('td:contains(3-3)').prevAll().addClass('highlight');
.find
.end
note the chaining
$('td:contains(argh1)') //find every cell containing argh1 (including this table)
.parent() //go to parent
.find('td:eq(1)') //find 2nd descendant
.addClass('highlight') //add highlight class
.end() //go back to argh1
.find('td:eq(2)') //find 3rd descendant
.addClass('highlight'); // add highlight class
.get()
[]
Get to the dom element directly (e.g. to get a tagname or some other property)
var daTag = $('da-element').get(0).tagname;
OR
var daTag = $('da-element')[0].tagname;

argh1 1-2 1-3
argh2 2-2 2-3
argh3 3-2 3-3

Special Effects

a href with class hide me
div with class hideme

$(".hideme").click(function(event){
event.preventDefault();
$(this).hide("slow");
});

Get Height of Window

http://api.jquery.com/height/
$( window ).height(); // returns height of browser viewport
$( document ).height(); // returns height of HTML document
...

Chaining

$("a").addClass("test").show().html("foo");
Everything returns an object and can have method applied to it. .end will finish the current chain and go back to the first Selector (or 'destructive' operation in the chain

Events

Loading script at doc load

$(document).ready(functionname);   //recommended version 1
OR with document passed through by default
$().ready(functionname);
OR for a anonymous/lambda function
$(document).ready(function() {     //recommended version 2
  $("a").addClass("makeitbold");
});
OR for a anonymous/lambda function and implicit call to (document).ready
$(function() {
  $("a").addClass("makeitbold");
});

Coexisting with other libraries

<script src="otherlibrary.js" type="text/javascript"></script>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.noConflict(); //frees up $ identifier
</script>
<script src="myscripts.js" type="text/javascript"></script>
//------call jQuery statements with jQuery in front-------
<script type="text/javascript">
jQuery(document).ready(function($) {
    //javascript statements that use $
});
//OR
jQuery(function($) {
    //javascript statements that use $
});
</script>

Simple events

can hook into any event (not just onload), such as onclick, onchange, onresize, etc...
body.large {
  font-size: 1.5em;
}
body.narrow {
  width: 300px;
}
.selected {
  font-weight: bold;
}
//-----
function bindclicks()
{
	$('#switcher :button').bind('click', function() {   	// bind to click for every button in id switcher
		$('body').removeClass();                        // remove the classes from body element
		$('#switcher :button').removeClass('selected'); // remove 'selected' class from every button in switcher
		$(this).addClass('selected');			// for this button, add class 'selected'
	});
	$('#switcher-narrow').bind('click', function() {	// bind to click for id 'switcher-narrow'
		$('body').addClass('narrow');			// add class 'narrow' to the body element
	});
	$('#switcher-large').bind('click', function() {		// bind to click for id 'switcher-large'
		$('body').addClass('large');			// add class 'large' to body element
	});
};

Basic Events that can be bound

blur, change, click, dblcklick, error, focus, keydown, keypress, keyup, load, mousedown, mousemove, mouseout, mouseover, mouseup, resize, scroll, select, submit, unload
use these as shorthand after matched item instead of bind
$('#daMatchedID').click(function() { alert('hi'); });

Compound Events that can be bound

.ready
.toggle each click invokes the next function
.hidden {
  display: none;
}
//----
<form>
<input id="togglenowyouseeme" 
		value="toggle nowyouseeme" type="button">
<div id="nowyouseeme">Now you see me...</div>
</form>
//----
$(document).ready(function() {
	$('#togglenowyouseeme').toggle(function() {
		$('#nowyouseeme').addClass('hidden');
	}, function() {
		$('#nowyouseeme').removeClass('hidden');
	});
});
Now you see me...
.hover toggle on enter and than exit
will work across browser unlike :hover pseudo-event
.hover {
  cursor: pointer;
  background-color: #afa;
}
//----
<div id=hoverdiv 
	style="border: 1px solid black; width: 200px;">
content in the div
</div>
//----
$(document).ready(function() {
	$('#hoverdiv').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
});
content in the div

Event Capturing vs. Bubbling

div
span
a
<div id=dummyalert1 style="border: 1px solid black; 
    padding-left: 10px; padding-right: 10px; 
    background: silver; width: 100px; text-align: center;">
<form>
    <input value="alert" onclick="dummyalert(); 
        return(false);" type="button">
</form></div>

$(document).ready(function() { $('#dummyalert1').click(function(event) { if (event.target == this) { //make sure this item //not bubble $('#dummyalert1 :button').toggleClass('hidden'); } }); });



ignoring default actions

<a id=dummyalert2 
    href="http://www.google.com">google or dummyalert2</a>

$(document).ready(function() { $('#dummyalert2').click(function(event) { alert("dummyalert2"); event.stopPropagation(); event.preventDefault(); }); });

google or dummyalert2

Event Delegation (e.g. grouping)

Looking for events on subelements...
<div id=boxer1 style="...">
    <div id=subboxer1 style="background: silver; ...">
                                                  click 1<div>
    <div id=subboxer2 style="(no background) ...">click 2<div>
    <div id=subboxer3 style="...">click 3<div>
<div>

//boxer1 and subboxer1 2 and 3 $(document).ready(function() { $('#boxer1 div').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); }); $('#boxer1').click(function(event) { if ($(event.target).is('#boxer1')) { $('#boxer1 :div').toggleClass('hidden'); } else if (event.target.id == 'subboxer1') { alert('clicked subboxer1'); } else { alert('clicked ' + event.target.id); } }); });
click 1
click 2
click 3

Binding, Unbinding, Rebinding

.bind (or a shortcut such as .click)
.unbind
.one  (will unbind the event after one use)

Event namespacing

$('#boxer1').bind('click.collapse'). function(event) {
    ...
}

//click is bound but you can refer (e.g. unbind) the
//specific event click.collapse
//
//other click events would not be affected

Simulating user interaction

$('#boxer1').trigger('click');
  OR
$('#boxer1').click();

//trigger the click event for the element with the boxer1 id

Keyboard events

keydownwhen the key is pressed
keyupwhen the key is released
keypressthe resulting key that is pressed

<div id=updown style="border: 1px solid black; 
    background: silver; width: 200px; padding: 20px;">
    Press U or D.
    <div id=up1 style="border: 1px dotted black; 
        width: 200px;">&nbsp;</div>
    <div id=down1 style="border: 1px dotted black; 
        width: 200px;">&nbsp;</div>
</div>

$(document).ready(function() { $('#up1').addClass('hover'); $(document).keyup(function(event) { switch (String.fromCharCode(event.keyCode)) { case 'U': $('#down1').removeClass('hover'); $('#up1').addClass('hover'); break; case 'D': $('#up1').removeClass('hover'); $('#down1').addClass('hover'); break; } }); });
Press U or D.
 
 

Effects

CSS modification

If you don't want to .addClass or .removeClass, you can get or set css to/from the element/tag specifically with:
.css
.css('background-color')	//get the css feature
.css('backgroundColor')		//camel-cased for DOM notation
.css('property','value')	//set the property
.css({'property1: 'value1', 'property-2': 'value2'})
				//set multiple properties
<div id=demotext2 style="border: 1px solid black;">
...
</div>

<div id=prestochango>
	<div class="label">Text Size
		<button id=pc-default>Default</button>
		<button id=pc-larger>Larger</button>
		<button id=pc-smaller>Smaller</button>
	</div>
</div>

$(document).ready(function() { var $speech = $('div#demotext2'); //$ is a reminder that we have a jQuery object var defsize = $speech.css('fontSize'); $('#prestochango button').click(function() { var daNum = parseFloat( $speech.css('fontSize'), 10 ); //parseFloat looks at string left to right until //it encounters non-numeric char. String is //converted to floating-point. 10 makes sure it's //a base10 number. switch (this.id) { case 'pc-larger': daNum *= 1.4; break; case 'pc-smaller': daNum /= 1.4; break; case 'pc-default': daNum = parseFloat(defsize, 10); } $speech.css('fontSize', daNum + 'px'); }) })
Demo text
When, in the course of human events, it becomes necessary for one people to dissolve the political bonds which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the laws of nature and of nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.
Text Size

hide, show, fade, and slide

<div id=demotext3 style="border: 1px solid black;">
<p>...</p>
<p>...</p>
<a href="#" class=showmore>show more</a> | 
<a href="#" class=showmoreslow>show more slow</a> | 
<a href="#" class=showmore850>show more 850</a> | 
<a href="#" class=fadetoggle>fade toggle in</a> | 
<a href="#" class=slidetoggle>slide toggle in</a>
</div>
$(document).ready(function() {
	var $firstPara = $('div#demotext3 p:eq(1)')
	$firstPara.hide();
	$('a.showmore').click(function() {
		$('div#demotext3 p:eq(1)').show();
		$(this).hide();
			//could be toggle
		return false;
	});
	$('a.showmoreslow').click(function() {
		$('div#demotext3 p:eq(1)').show('slow');
		$(this).hide();
		return false;
	});
	$('a.showmore850').click(function() {
		$('div#demotext3 p:eq(1)').show(850);
		$(this).hide();
		return false;
	});
	$('a.fadetoggle').click(function() {
		if ($firstPara.is(':hidden')) {
			$firstPara.fadeIn('slow');
			$(this).text('fade toggle out');
		} else {
			$firstPara.fadeOut('slow');
			$(this).text('fade toggle in');
		}
		return false;
	});
		$('a.slidetoggle').click(function() {
		$firstPara.slideToggle('slow');
			//could be slideIn or slideOut
		var $link = $(this);
		if ( $link.text() == "slide toggle in" ) {
			$link.text('slide toggle out');
		} else {
			$link.text('slide toggle in');
		}
		return false;
	});
});

When, in the course of human events, it becomes necessary for one people to dissolve the political bonds which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the laws of nature and of nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable rights, that among these are life, liberty and the pursuit of happiness. That to secure these rights, governments are instituted among men, deriving their just powers from the consent of the governed. That whenever any form of government becomes destructive to these ends, it is the right of the people to alter or to abolish it, and to institute new government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their safety and happiness....

show more | show more slow | show more 850 | fade toggle in | slide toggle in

.animate()

.animate({property1: 'val1', property2: 'val2'},
	speed, 
	easing, 
	callbackfunction()   //called after animation is complete
                             //can be function() { ... }
);
	OR
.animate({properties}, {options});
	WHICH TRANSLATES TO
.animate({
	prop1: 'val1',
	prop2: 'val2'
}, {
	duration: 'val',
	easing: 'val',
	complete: callbackfunction(),
	queue: boolean,
	step: callback
});

size and opacity example

<div id=demotext4 style="border: 1px solid black;">
    <p>When, in the course ....</p>
    <p>We hold these truths to be self-evident,....</p>
    <a href="#" class=animateshowmore>animate show more</a> |
    <button id=dt4-default>Default</button>
    <button id=dt4-larger>Larger</button>
    <button id=dt4-smaller>Smaller</button>
</div>

$(document).ready(function() { var $daFirstPara = $('div#demotext4 p:eq(0)') var daFirstParaDefSize = $daFirstPara.css('fontSize'); var $dasecondPara = $('div#demotext4 p:eq(1)') $dasecondPara.hide(); $('a.animateshowmore').click(function() { $dasecondPara.animate({ opacity: 'toggle', height: 'toggle' }, 1200); ... }); $('div#demotext4 button').click(function() { var num = parseFloat( $daFirstPara.css('fontSize'), 10 ); switch (this.id) { case 'dt4-larger': num *= 1.4; break; case 'dt4-smaller': num /= 1.4; break; default: num = parseFloat(daFirstParaDefSize, 10); } $daFirstPara.animate({fontSize: num + 'px'}, 'slow'); }); });

When, in the course of human events, it becomes necessary for one people to dissolve the political bonds which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the laws of nature and of nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable rights, that among these are life, liberty and the pursuit of happiness. That to secure these rights, governments are instituted among men, deriving their just powers from the consent of the governed. That whenever any form of government becomes destructive to these ends, it is the right of the people to alter or to abolish it, and to institute new government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their safety and happiness....

animate show more |

moving, height, borderwidth example

<div id=container1 style="border: 1px dotted silver;">
	<div id=label5 style="position: relative; 
			border: 1px solid black; background: aqua; 
			height: 50px; width: 170px;">
		Click me to move the div
	</div>
</div>

$(document).ready(function() { $('div#label5').click(function() { var daParaWidth = $('div#container1').width(); var $daBox = $('div#label5'); var daBoxWidth = $daBox.outerWidth(); $daBox.animate({left: daParaWidth - daBoxWidth - 8, height: '+=20px', borderWidth: '5px'}, '1500'); }); });

Click me to move the div
Click me to queue move the div

in the function for the second box...
var daParaWidth = $('div#container1').width();
var $daBox = $('div#label6');
var daBoxWidth = $daBox.outerWidth();
$daBox
	.fadeTo('fast',0.5)		//make sequential to queue
	.animate({
		'left': daParaWidth - daBoxWidth
		}, 'slow')
	.fadeTo('slow',1.0)
	.queue(function() {		//use queue function to queue
		$daBox			//things that shouldn't be able to
		    .css('backgroundColor', '#f00')
		    .dequeue();		//let the rest of the items queue
	})
	.slideUp('slow')
	.slideDown('slow');

callbacks

If you animate multiple elements/tags one after another, they will animate (just about simultaneously). A way around this is with callbacks.
$(document).ready(function() {
	var $firstPara = $('div#demotext7 p:eq(0)');
	var $secondPara = $('div#demotext7 p:eq(1)');
	$('button#dt7-animate').click(function() {
		$firstPara
			.css('border', '1px solid #333')
			.click(function() {
			    $(this).next().slideDown('slow',function() {
			        $firstPara.slideUp('slow');
			    });
			})
	});
	$secondPara.css('backgroundColor', '#ccc').hide();
});

When, in the course of human events, it becomes necessary for one people to dissolve the political bonds which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the laws of nature and of nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.

We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable rights, that among these are life, liberty and the pursuit of happiness. That to secure these rights, governments are instituted among men, deriving their just powers from the consent of the governed. That whenever any form of government becomes destructive to these ends, it is the right of the people to alter or to abolish it, and to institute new government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their safety and happiness....

(than click on the paragraph)

DOM Manipulation

Element/Tag Attributes

Iterating using each()

.each() interates starting with 0 as the index.
$(document).ready(function() {
    $('div.chapter a[href=*=blah]').each(function(index) {
        var $thisLink = $(this);
        $(this).attr({  //set the attributes
            'rel': 'external',        //rel to external
            'id': 'wikilink' + index, //id to wikilink0, ..1,
            'title': 'check out more about '
                     + $thisLink.text() 
                     + ' at blah.'    //add custom title link
        });
    });
});

Inserting new or cloned elements

$('...') create the text to insert
$('<b>hello</b>')
insertAfter()
after()
$('<b>hello</b>').insertAfter('div#demotext8 p')
('div#demotext8 p').after('<b>hello</b>');

insertBefore()
before()
Similar to insertAfter() and after() above
prependTo()
prepend()
prepends to beginning of element
$('<b>Title<br /></b>').prependTo('div#demotext8')
appendTo()
append()
appends to end of element
$('<br /><b>The End</b>').appendTo('div#demotext8')
wrap() wraps element around another element.
$('div#demotext8 p').wrap('<ul></ul>').wrap('<li></li>');
OR
$('div#demotext8 p').wrap('<ul><li></li></ul>');
wrapall() wraps all elements in set in another element.
$('div#demotext8 p').wrapAll('<div style="border: 5px dotted blue;"></div>');
OR
$('div#demotext8 p').wrapAll('div'); (can be DOM element)
wrapinner() wraps each inner element matched in another element. Good when you have multiple layers of elements.
$('div#demotext8 p').wrapInner('<i></i>');
OR
$('div#demotext8 p').wrapAll('i'); (can be DOM element)
clone() clones elements for copying. put true as argument to copy associates events also
$('div#demotext8 p:eq(0)').clone().insertAfter('div#demotext8 p:eq(0)');

para 1

para 2

Replacing and removing elements

.html() Get or Set the innerHTML of the element (doesn't work for straight XML).
$('div#demotext12 p:eq(0)').html("para 3 is not bold");
.text() Get or Set the combined text of all mateched elements.
var daText11 = $('div#demotext12 p').text();
$('div#demotext12-2').text(daText11);

.replaceAll()
.replaceWith()
Replace all elements matched with specific text/html/element. Post 1.3.2 - returns inserted elements.
$("<p>There <i>was</i> a paragraph here.</p>").replaceAll('div#demotext12 p');
$('div#demotext12 p').replaceWith("<p>That <i>would be</i> a paragraph.</p>");

.empty() empties all child nodes including text nodes
$('div#demotext12 p').empty();
.remove() removes elements from DOM but not from jQuery object
$('div#demotext12-2').empty(); //there's a &nbsp; in div#demotext12-2
$('div#demotext12 p').remove().appendTo('div#demotext12-2');


para 1 is bold

para 2 is italics


 

Moving elements

<div id=demotext9 style="border: 1px solid black;">
	<p>para 1</p>
	<span class=footnote>footnote a</span>
	<p>para 2</p>
	<span class=footnote>footnote b</span>
	<hr>
	<span id=footer></span>
</div>

$('div#demotext9 span.footnote').insertBefore('div#demotext9 #footer');

para 1

footnote a

para 2

footnote b

Cloning and pulling elements

The css, jquery/javascript and background images for this section were pulled pretty much very close to verbatim from Learning jQuery 1.3 by Jonathan Chaffer and Karl Swedberg. Please buy their book.

...Prudence, indeed, will dictate that governments long established should not be changed for light and transient causes; and accordingly all experience hath shown that mankind are more disposed to suffer, while evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long train of abuses and usurpations, pursuing invariably the same object evinces a design to reduce them under absolute despotism, it is their right, it is their duty, to throw off such government, and to provide new guards for their future security...

--Such has been the patient sufferance of these colonies; and such is now the necessity which constrains them to alter their former systems of government. The history of the present King of Great Britain is a history of repeated injuries and usurpations, all having in direct object the establishment of an absolute tyranny over these states. To prove this, let facts be submitted to a candid world.

Marking, numbering, linking, appending, wrapping

$(document).ready(function() {
  $('button#demobutton10').click(function() {
    $('<ol id="demo10notes"></ol>').insertAfter('div#demotext10');
    $('div#demotext10 span.footnote').each(function(index) {
      $(this)
        .before(
          ['<a href="#foot-note-',
            index+1,
            '" id="context-',
            index+1,
            '" class="context">',
              '<sup>' + (index+1) + '</sup>',
          '</a>'
          ].join('')
        )
        .appendTo('#demo10notes')
        .append( '&nbsp;(<a href="#context-' + (index+1) + '">context</a>)' )
        .wrap('<li id="foot-note-' + (index+1) + '"></li>');
    });
  });
});

para 1

footnote a

para 2

footnote b

Modifying a form

Type in something:

AJAX

http://docs.jquery.com/Ajax

load txt (or html)

<div id=DateAndTime 
style="border: 1px solid blue; width: 300px;">
...
</div>

<form>
<input type="button" value="get time from server"
onclick="gettimefromserver(); return(false);" />
</form>

function gettimefromserver()
{
$("#DateAndTime").load("DateAndTime.php");
}

<?php
$time = time();
echo date("m/d/y g:i:s a", $time);
?>

...

load xml

<div id=xmlversion class=boxedmono></div>

function grabdaxml() {
$.get("/AJAXDomJavaScript/proutxml2.php",putdaxml,"xml");
return false;
}
var totaltable = "";
var totaltable2 = "";
function putdaxml(daxml, successorfailure) {
if (successorfailure == "success") {
//var dachildren = $(daxml).children();
proutchildnodes($(daxml).children());
//put totaltable into the innerhtml of the element with id xmlversion
$("#xmlversion").html(totaltable);
} else {
alert("There was an error retrieving the xml");
}
}
function proutchildnodes(dalist) {
//print the node, subnodes, and text values
for (var i=0; i < dalist.length; i++) {
if (dalist[i].nodeType == 1) {
totaltable += "&lt;div class=indentedmono&gt;&lt;" +
dalist[i].nodeName + "&gt;";
var childnodes = $(dalist[i]).children();
//for each child - call proutchildnotes
if (childnodes.length > 0) {
proutchildnodes(childnodes);
} else { //if there's no childnodes and text betw nodenames prout it
totaltable += $(dalist[i]).text();
}
totaltable += "&lt;/" + dalist[i].nodeName + "&gt;" + "</div>";
}
}
};

DOM table reprint

Character names and descriptions only

load JSON

JavaScript Object Notation (JSON)
{
	"key"	: "value",
	"key 1"	: "value1",
	"key 2"	: [
		"array val 1",
		"array val 2",
		"array val 3",
	]
}
{ /* 2nd entry */
	"key"	: "value2",
	"key 1"	: "value3",
	"key 2"	: [
		"array val 4",
		"array val 5",
		"array val 6",
	]
}

$(document).ready(function() { $('#daButtonID').click(function() { $.getJSON('dafile.json', function(data) { $('#daDataDisplayDivID').empty() /* empty the div */ $.each(data, function(daIndex, daEntries) { var daHTML = ''; daHTML += '<div>' + entry['key'] + '-' + entry['key 1'] + '<br />'; if (daEntries['key 2']) { $.each(daEntries['key 2']), function(daArrayIndex, daArrayLine) { daHTML += '<div class=indented>' + daArrayLine + '</div>'; } } daHTML += '</div>'; } $('#daDataDisplayDivID').html(daHTML); } } }

get/execute a script

$(document).ready(function() {
    $('#daID a').click(function() {
        $.getScript('blah.js');
        return false;
    });
});

basic GET request

$(document).ready(function() {
  $('#demobutton13').click(function() {
    $.get('demo13.php', {'text': $('#demotext13input')[0].value} , function(data) {
      $('#demotext13output').html(data);
    });
  });
});
//something like GET /AJAXDomJavaScript/demo13.php?text=demotext13 will be sent with the HTTP request

<?php $daInput = $_REQUEST['text']; echo '<span style="color: blue;">' . $daInput . '</span>'; echo '<span style="color: red;">' . $daInput . '</span>'; ?>
 

basic POST request

$(document).ready(function() {
    $('#demobutton14').click(function() {
        $.post('demo13.php', {'text': $('#demotext14input')[0].value} , function(data) {
            $('#demotext14output').html(data);
        }); 
        // PREVIOUS 3 LINES COULD ALSO BE
        $('#demotext14output').load('demo13.php', {'text': $('#demotext14input')[0].value});
    });
});
 

additional stuff on POST

$('#daID').load('dahtml.html .daClass'); will load things from dahtml.html only if they have a class of .class

Serializing the form

<?php
    while (list($key, $value) = each($_REQUEST)) {
        echo "$key => $value 
\n"; } ?>
$(document).ready(function() { $('#demobutton15').click(function() { $test15 = $('#demoform15').serialize(); /* could be $.post, or could use .load ... */ $.get('demo15.php', $('#demoform15').serialize(), function(data) { $('#demotext15output').html(data); }); }); });
 
demo15:
demo152:

ajaxStart, ajaxStop

Do something when ajax calls start or stop...
$(document).ready(function() {
    $('<div id="herewego">here we go</div>')
    .insertBefore('#daID')
    .ajaxStart(function() { 
        $(this).show(); 
    }); 
});

.live

Look at all events on page of type indicated.
$(document).ready(function() {
    $('.daClass').live('click', function() {
        $(this).siblings('a').slideToggle();
    })
})

Getting scripts/data from alternate server

danger - be sure you trust the server you are getting the data from

insert <script> tag

Script has to effect a local global variable.
$(document.createElement('script'))
    .attr('src', 'http://asdf.com/example.js')
    .appendTo('head');

JSONP

<?php
    print($_GET['callbackvar'] .'('. $data .')');
    /* $data is JSON data */
?>

(javascript)... $.getJSON(foreignurl + '?callbackvar="', function(data) { ... /* JQuery replaces ?, parses result, passes success function as data coming from local server */

customizing AJAX call

this is lower level than other calls...
$.ajax({
      url: 'blah.html',
      type: 'GET',
      dataType: 'html',
      success: function(data) {
        $('daID').html(data);
      }
});

$.ajaxSetup like above but sets vars for future calls

Forms

double
Personal Info
  1. (required)
  2. (required)
    • (required when corresponding checkbox checked)
    • (required when corresponding checkbox checked)
    • (required when corresponding checkbox checked)


Hotkeys

hotkeys.html

JQuery TOC

testtoc.html