|
Home Pages Pidgin Azarennya (S|N) Mac Textanium Reference ToDo Food Local Edit Local: Hide Weather • GoWhere? • YahooMaps (mine) • GoogleMaps • Metro (map) • FairfaxConnector • GreaterGreaterWashington • DCMetrocentric • WhatsUpArlington • Restonian • BeyondDC • BaconsRebellion Language: Hide Fantasy: Hide • AnnalsOfArda • Arda • SilmarillionChronology • TolkienGateway • SciFi: Hide • CentauriDreams • ColdNavy • ConceptShips • RavenstarStudios • SkyscraperPage • StarTrek • StarTrekVsStarWars • Film: Hide IMDB • BigHollywood • DKnowsAll • Jabootu • KyleSmith Music: Hide REALbasic: Hide • Resources • Garage • University • WebRing • Forums: • REAL • ElfData • Plugins and Code: • BKeeney • DeclareSub • Einhugur • Joe • Restrepo • Tempelmann • ZAZ Coding: Hide Forums: • PowWeb • PHP • Webmaster • Coding • Walkers • Perl • Intro • Monks • PHP • JavaScript • Toolbox • UnobtrusiveJavaScript • JavaScriptCompressor • RegularExpressions (test) • JSLint • SQL • Cocoa • CocoaBuilder • CocoaDev • CocoaLab • AppleScript • BBS • Userland • Faqintosh • FileMaker • FileMakerTips • FileMakerWorld • FileMakerPlugins Science: Hide DarwinCentral • PhysOrg • PandasThumb • TalkOrigins • TalkRational • AstronomyDailyPics • Curmudgeon • SmallThings • ArchaeoBlog • AntiEvolution.org • SkepticsGuide • EvC • BadAstronomer • PhysicsForum • SlashdotScience • JunkScience • Engadget • Thunderbolts • Icecap • CentauriDreams • NewScientist • Gizmodo • CO2Science • ClimateDebate • ScienceDaily • Nrich • Math • TalkOrigins • GoodMathBadMath • Magazines • AmericanScientist • NationalGeographic • Space.com History: Hide • 1421 News/Politics: Hide WideAwakes • Anchoress • Lucianne • Strata • AceOfSpades • BigLizards • BlackAndRight • Cannonfire • DrSanity • FloppingAces • GatewayPundit • HillBuzz • HotAir • Husaria • JawaReport • JimTreacher • JsCafeNette • LittleGreenFootballs • MyVRWC • Newsbusters • Pal2Pal • PinkFlamingo • PowerLine • RachelLucas • RogerLSimon • SisterToldjah • StolenThunder • SultanKnish • TCSDaily • UppityWoman • Wizbang • NewsGroper • NewsRightNow • OriginalSignal • Blogs... Cults/Crime: Hide Miscellaneous: Hide Fun: Agony ICanHas? ObSkills Snopes Pix: Deviant Places Renderosity Blender Artists X86: OSX86 ArsTech OSNews TUAW Tools: Calculator AsciiArt XMLVal FunStuff: Pictures: Photobucket (eg Dubai) Videos: YouTube Subtitler InterestingThings: LibraryThing FlashCards GoogleDocs Wowio Bubbl.us Colemak Audible PodioBooks WonderfulInfo BooksOnline AboutUs.org |
WebProgrammingPHP HintsStrings
Arrays
Files
Predefined variables
JavaScript Hints"For" loops: Use For each property in an object: var record = "Wine 1<br><br>"
for (var prop in wine1) {
record += prop + " = " + wine1[prop] + "<BR>"
}
Creating an object with custom properties on the fly: myPetDog=new Object();
myPetDog.name="Barney";
myPetDog.breed="beagle";
myPetDog.year=1981;
// Adding function "woof()" to object as a method:
myPetDog.sound=woof;
Creating a prototype object: function petDog(name, breed, year) {
this.name = name;
this.breed = breed;
this.year = year;
}
Creating an object from a prototype: myPetDog = new petDog("barney","beagle",1981);
yourPetDog=new petDog("max","terrier",1990);
jQuery HintsShortcut to do something as soon as the DOM is ready: $(function(){ /* do something when DOM is ready */ });
Append HTML to the content of every DIV of class "foo": $("div.foo").append("<b>Hello!</b>");
Change the CSS property "color" for all paragraphs: $("p").css("color","red");
Have every link show an alert when clicked: $(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
Have a button's "click" event download and display a quote: $(document).ready(function(){
$("#generate").click(function(){
$("#quote p").load("get_quote.php");
});
});
<!-- HTML -->
<div id="quote"><p><!-- QUOTE GOES HERE --></p></div>
<input type="submit" id="generate" value="Generate!">
Equivalent to "onSubmit": $("form#chatform").submit(function(){ /* Code */ });
Clicking on a given link shows or hides a given DIV: $('a#slick-toggle').click(function() {
$('#slickbox').toggle(400);
// Show or hide DIV in 400 ms.
// Or use 'slow', 'normal', or 'fast'.
// Or call .slideToggle(400) instead.
return false;
});
Submit form to server and handle response: $("form#chatform").submit(function(){
$.post(
"backend.php", // PHP script
{
message: $("#msg").val(), // Script parameters
name: $("#author").val(),
action: "postmsg",
time: timestamp
},
function(xml) { // Response handler
doSomethingWith(xml);
}
);
return false; // Ensures we don't leave the page!
});
DOM selection examples: $('div.panel')
// All divs with class=“panel”
$('p#intro')
// The paragraph with id=“intro”
$('div#content a:visible')
// All visible links inside the div with id=“content”
$('input[@name=email]')
// All input fields with name=“email”
$('table.orders tr:odd')
// “odd” numbered rows in a table with class “orders”
$('a[@href^="http://"]')
// All external links (links that start with http://)
$('p[a]')
// All paragraphs that contain one or more links
$('li:eq(0)')
// gets the first list item.
$('li:even')
// gets items [0], [2], [4], [6], etc.
$('li:lt(3)')
// gets items "less than" [3] -- i.e., [0], [1], [2].
$('li:not(.foo)')
// gets all list items that aren't of class "foo".
$('p a[@href*=#]')
// gets any links that contain "#". (Space between "p"
// and "a" means that "a" is a descendant of "p".)
$('code, li.foo')
// gets all code elements AND any list item of class "foo".
$('ol .foo > strong')
// gets all strong elements that are children of any "foo"-
// class element, if that element is anywhere inside an
// ordered list (it does not specifically have to be a CHILD
// of the ordered list).
$('li + li > a[@href$=pdf]')
// gets all links ending in "pdf" that are children of any list
// item that has another list item as its previous sibling.
$('span:hidden')
// gets any span element that is hidden.
$('a[@href^=http]').not('[@href*=mysite.com]')
// gets all links containing "http" but not containing "mysite.com"
// (intention: to get all links to other websites, perhaps so you
// could append an "external link" graphic)
DOM alteration examples: $('div#primary').width(300);
// Set the width of div id=“primary” to 300 px.
$('p').css('line-height', '1.8em');
// Apply a line-height of 1.8em to all paragraphs.
$('li:odd').css({color: 'white', backgroundColor: 'black'});
// Apply two CSS rules to every other list item; note that the css()
// function can take an object instead of two strings.
$('a[@href^="http://"]').addClass('external').attr('target', '_blank');
// Add a class of “external” to all external links (those beginning
// with http://), then add target=“_blank” for good measure.
$('blockquote').each(function(el) { alert(jQuery(this).text()) });
// Iterate over every blockquote on the page, and alert its textual
// content (excluding HTML tags).
$('a').html('Click here!');
// Replace all link text on the page with the insidious “Click here!”.
DOM inspection examples: var width = $('div').width();
// How wide is the first div on the page?
var src = $('img').attr('src');
// What’s the src attribute of the first image on the page?
var color = $('h1').css('color');
// What color is the first h1?
DOM traversal examples: $('div').not('[@id]')
// Returns divs that do not have an id attribute.
$('h2').parent()
// Returns all elements that are direct parents of an h2.
$('blockquote').children()
// Returns all elements that are children of a blockquote.
$('p').eq(4).next()
// Find the fifth paragraph on the page, then find the next element
// (its direct sibling to the right).
$('input:text:first').parents('form')
// Find the form parent of the first input type=“text” field on the
// page. The optional argument to parents() is another selector.
Element "stack" examples (using .end()): $('form#login')
// hide all the labels inside the form with the 'optional' class
.find('label.optional').hide().end()
// add a red border to any password fields in the form
.find('input:password').css('border', '1px solid red').end()
// add a submit handler to the form
.submit(function(){
return confirm('Are you sure you want to submit?');
});
Create a DIV, set its attributes, and prepend to another DIV: var div = $('<div>Text</div>').addClass('inserted').attr('id', 'foo');
div.prependTo('div#primary');
Trigger an event: $('p:first').click();
// Send a fake “click” to the first paragraph on the page.
Have links be highlighted in orange when the mouse hovers over them: $('a').hover(function() {
$(this).css('background-color', 'orange');
}, function() {
$(this).css('background-color', 'white');
});
Set up a one-time-only event handler: $('p').one('click', function() {
alert(jQuery(this).html());
});
// The paragraph contents appear in an alert only on the FIRST
// time you click on the paragraph, not thereafter.
Change the first letter in the first paragraph to a drop cap: var first_paragraph = $('#main-content p')[0];
if (!first_paragraph) return false;
var node = first_paragraph;
while (node.childNodes.length) {
node = node.firstChild;
}
var text = node.nodeValue;
var first_letter = text.substr(0,1);
var match = /[a-zA-Z]/.test(first_letter);
if ( match ) {
node.nodeValue = text.slice(1);
$('<img />')
.attr('src','/images/caps/' + first_letter.toLowerCase() + '.gif')
.attr('alt',first_letter)
.addClass('fancy-letter')
.prependTo( first_paragraph );
}
}
Ajax options(http://docs.jquery.com/Ajax/jQuery.ajax#options) Code like what I expect to use: $.ajax({
type: "POST",
url: "find.php",
data: "q=abc&c=def",
datatype: "json", // or "html" if your script returns that instead.
success: function(data){
// Do something with data returned from server.
// If datatype was "json" then data should be an object.
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown will have info
}
});
Load and execute a JavaScript file: $.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
Retrieve the latest version of an HTML page: $.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
OptimizationjQuery has a "speed hierarchy":
To speed up class access, put all items of a given class inside an element with an ID, then use |