<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>
<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>
.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');
}
#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 |
> $('#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 |
$('img[alt]')
: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 |
: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 |
.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 |
|||||||||||||||
.nextAll .prevAll |
|||||||||||||||
.find .end |
note the chaining
|
||||||||||||||
.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 |
$(".hideme").click(function(event){
event.preventDefault();
$(this).hide("slow");
});
http://api.jquery.com/height/ $( window ).height(); // returns height of browser viewport $( document ).height(); // returns height of HTML document
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 }); };
.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'); }); }); |
.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
|
<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'); } }); });
<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(); }); });
<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); } }); });
.bind (or a shortcut such as .click) .unbind .one (will unbind the event after one use)
$('#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
$('#boxer1').trigger('click'); OR $('#boxer1').click(); //trigger the click event for the element with the boxer1 id
keydown | when the key is pressed |
keyup | when the key is released |
keypress | the 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;"> </div> <div id=down1 style="border: 1px dotted black; width: 200px;"> </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; } }); });
.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'); }) })
<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({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 });
<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 |<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'); }); });
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');
$(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)$(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 }); }); });
$('...') | 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
.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 in div#demotext12-2 $('div#demotext12 p').remove().appendTo('div#demotext12-2'); |
para 1 is bold
para 2 is italics
<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 apara 2
footnote b...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.
$(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( ' (<a href="#context-' + (index+1) + '">context</a>)' ) .wrap('<li id="foot-note-' + (index+1) + '"></li>'); }); }); });
para 1
footnote apara 2
footnote b<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);
?>
{ "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); } } }
$(document).ready(function() { $('#daID a').click(function() { $.getScript('blah.js'); return false; }); });
$(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>'; ?>
$(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}); }); });
<?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); }); }); });
$(document).ready(function() { $('<div id="herewego">here we go</div>') .insertBefore('#daID') .ajaxStart(function() { $(this).show(); }); });
$(document).ready(function() { $('.daClass').live('click', function() { $(this).siblings('a').slideToggle(); }) })
$(document.createElement('script')) .attr('src', 'http://asdf.com/example.js') .appendTo('head');
<?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 */
$.ajax({ url: 'blah.html', type: 'GET', dataType: 'html', success: function(data) { $('daID').html(data); } });
$.ajaxSetup like above but sets vars for future calls