Commit c1722b05 authored by O'Reilly Media, Inc's avatar O'Reilly Media, Inc
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading

README.md

0 → 100644
+15 −0
Changes for README.md: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
## Example files for the title:  
  
# jQuery Pocket Reference, by David Flanagan
  
[![jQuery Pocket Reference, by David Flanagan](http://akamaicovers.oreilly.com/images/9781449397227/cat.gif)](https://www.safaribooksonline.com/library/view/title/9781449398958//)
  
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
  
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
  
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
  
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
  
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.

code/README

0 → 100644
+37 −0
Changes for code/README: 37 added lines, 0 removed lines.
Original line number Diff line number Diff line
These files are the examples code from the book jQuery Pocket Reference
(ISBN: 978-1-4493-9722-7) by David Flanagan. The examples are copyright
2011 by O'Reilly Media.  You can use them under the terms of O'Reilly's
code reuse policy:

      This book is here to help you get your job done. In general, you
      may use the code in this book in your programs and
      documentation. You do not need to contact us for permission unless
      you're reproducing a significant portion of the code. For example,
      writing a program that uses several chunks of code from this book
      does not require permission.  Selling or distributing a CD-ROM of
      examples from O'Reilly books does require permission. Answering a
      question by citing this book and quoting example code does not
      require permission.  Incorporating a significant amount of example
      code from this book into your product's documentation does require
      permission.

      We appreciate, but do not require, attribution. An attribution
      usually includes the title, author, publisher, and ISBN. For
      example: "From _jQuery Pocket Reference_, by David
      Flanagan. Copyright 2011 O'Reilly Media, Inc., ISBN 978-1-4493-9722-7".

      If you feel your use of code examples falls outside fair use of
      the permission given above, feel free to contact us at
      permissions@oreilly.com.

This book does not contain numbered code examples. Instead it includes
lots and lots of short code snippets. In general, these snippets are not
complete programs and will not run on their own. You can cut-and-paste
them into your own code, if you want to however.  The files in this
directory correspond to the chapters of the book, and each file includes
all of the code snippets from its chapter.

I hope these examples are helpful to you!

     David Flanagan
     http://davidflanagan.com

code/ch01.js

0 → 100644
+84 −0
Changes for code/ch01.js: 84 added lines, 0 removed lines.
Original line number Diff line number Diff line

var divs = $("div");
------------------------------------------------------------

$("p.more").css("background-color", "gray").show("fast");
------------------------------------------------------------

$(".hide").click(function() { $(this).slideUp("slow"); });
------------------------------------------------------------

<script src="jquery-1.4.2.min.js"></script>
------------------------------------------------------------

var img = $("<img/>",      // Create a new <img> tag
            { src:url,     // With this src attribute
              alt:desc }); // And this alt attribute
------------------------------------------------------------

jQuery(function() { // Invoked when document has loaded
    // All jQuery code goes here
});
------------------------------------------------------------

jQuery.noConflict();  // Restore $ to its original state
jQuery(function($) {  
    // Use $ as a local alias for the jQuery object
    // Put all your jQuery code here
});
------------------------------------------------------------

// Call the jQuery function each() to invoke the
// function f once for each element of the array a
$.each(a,f);

// Call the jQuery() function to obtain a jQuery
// object that represents all <a> elements in the
// document. Then call the each() method of that 
// jQuery object to invoke the function f once for 
// each selected element.
$("a").each(f);
------------------------------------------------------------


div            // all <div> elements
#surname       // the element with id="surname"
.warning       // all elements with class="warning"
------------------------------------------------------------

$("body").length  // => 1: documents have only one body
$("body")[0]      // This the same as document.body
------------------------------------------------------------

// Find all <script> elements in the document body
var bodyscripts = $("script", document.body);
bodyscripts.selector   // => "script"
bodyscripts.context    // => document.body
bodyscripts.jquery     // => "1.4.2"
------------------------------------------------------------

// Number the divs of the document, up to div#last
$("div").each(function(idx) { // Invoke for each <div>
    // Create a jQuery object from the element
    // And insert the index at start of it.
    $(this).prepend(idx + ": ");  
    // Stop iterating when we reach #last
    if (this.id === "last") 
        return false;
});
------------------------------------------------------------

$(":header")                // Find all headings.
    .map(function() {       // Map them to
            return this.id; // their ids.
         })
    .toArray()              // Convert to a true array
    .sort();                // And sort that array
------------------------------------------------------------

$("div").each(function() {     // For each <div> element
    if ($(this).is(":hidden")) // Skip hidden elements
        return;
    // Do something with the visible ones here
});
------------------------------------------------------------

code/ch02.js

0 → 100644
+157 −0
Changes for code/ch02.js: 157 added lines, 0 removed lines.
Original line number Diff line number Diff line

// Query the action attr of 1st form
$("form").attr("action");
// Set the src attribute of element with id icon
$("#icon").attr("src", "icon.gif");
// Set 4 attributes at once
$("#banner").attr({src:"banner.gif",
                   alt:"Advertisement",
                   width:720, height:64});
// Make all links load in new windows
$("a").attr("target", "_blank"); 
// Compute the target attribute to load local links
// locally and load off-site links in a new window
$("a").attr("target", function() {
    if (this.host == location.host) return "_self"
    else return "_blank";                
});
// We can also pass functions like this
$("a").attr({target: function() {...}}); 
// Make all links load in this window
$("a").removeAttr("target");             
------------------------------------------------------------

$("h1").css("font-weight"); // Get font weight of 1st <h1>
$("h1").css("fontWeight");  // Camel case works, too
$("h1").css("font"); // ERROR: can't query compound style
$("h1").css("font-variant", // Set style on all <h1> tags
            "smallcaps");         
$("div.note").css("border", // Okay to set compound styles
                  "solid black 2px");
// Set multiple styles at once
$("h1").css({ backgroundColor: "black",  
              textColor: "white",
              fontVariant: "small-caps",
              padding: "10px 2px 4px 20px",
              border: "dotted black 4px" });
// Increase all <h1> font sizes by 25%
$("h1").css("font-size", function(i,curval) {    
              return Math.round(1.25*parseInt(curval));
            });
------------------------------------------------------------

// Add a CSS class to all <h1> tags
$("h1").addClass("hilite");
// Add 2 classes to <p> tags after <h1>
$("h1+p").addClass("hilite firstpara");
// Pass a function to add a computed class to each elt.
$("section").addClass(function(n) {    
    return "section" + n;              
});

// Remove a class from all <p> tags
$("p").removeClass("hilite");
// Multiple classes are allowed
$("p").removeClass("hilite firstpara");
// Remove computed classes from tags
$("section").removeClass(function(n) { 
    return "section" + n;              
});
// Remove all classes from all <div>s
$("div").removeClass(); 

// Toggle a CSS class: add the class if it is not
// there or remove it if it is.
$("tr:odd").toggleClass("oddrow");
// Toggle two classes at once
$("h1").toggleClass("big bold");
// Toggle a computed class or classes
$("h1").toggleClass(function(n) {      
    return "big bold h1-" + n;
});
$("h1").toggleClass("hilite", true);  // Like addClass
$("h1").toggleClass("hilite", false); // Like removeClass

// Testing for CSS classes: does any <p> have this class?
$("p").hasClass("firstpara")           
// This does the same thing.
$("#lead").is(".firstpara")            
// is() is more flexible than hasClass()
$("#lead").is(".firstpara.hilite")     
------------------------------------------------------------

// Get value from the surname text field
$("#surname").val() 
// Get single value from <select> 
$("#usstate").val()              
// Get array of values from <select multiple>
$("select#extras").val()         
// Get val of checked radio button
$("input:radio[name=ship]:checked").val()  
// Set value of a text field
$("#email").val("Invalid email address")   
// Check any checkboxes with these names or values
$("input:checkbox").val(["opt1", "opt2"])  
// Reset all text fields to their default
$("input:text").val(function() { 
    return this.defaultValue;
})
------------------------------------------------------------

var t = $("head title").text(); // Get document title
var hdr = $("h1").html()        // Get html of first <h1>
// Give each heading a section number
$("h1").text(function(n, current) {   
    return "§" + (n+1) + ": " + current
});
------------------------------------------------------------

var elt = $("#sprite"); // The element we want to move
var pos = elt.offset(); // Get its current position
pos.top += 100;         // change the Y coordinate
elt.offset(pos);        // Set the new position

// Move all <h1> tags to the right by a distance 
// that depends on their position in the document.
$("h1").offset(function(index,curpos) {
    return {
        left: curpos.left + 25*index,
        top:curpos.top
    };
});
------------------------------------------------------------

var body = $("body");
// Four different widths, depending on what's included
var contentWidth = body.width();
var paddingWidth = body.innerWidth();
var borderWidth = body.outerWidth();
var marginWidth = body.outerWidth(true);
// Sums of the l and r padding, borders and margins
var padding = paddingWidth-contentWidth;
var borders = borderWidth-paddingWidth;
var margins = marginWidth-borderWidth;
------------------------------------------------------------

// Scroll the window by n pages.
// n may be fractional or negative.
function page(n) {      
    // Wrap the window in a jQuery object
    var w = $(window);  
    // Get the size of a page
    var pagesize = w.height();   
    // Get the current scrollbar position
    var current = w.scrollTop(); 
    // Set new scrollbar position n pages down
    w.scrollTop(current + n*pagesize);  
}
------------------------------------------------------------

$("div").data("x", 1);            // Set some data
$("div.nodata").removeData("x");  // Remove some data
var x = $('#mydiv').data("x");    // Query some data
------------------------------------------------------------

$(e).data(...)   // The method form
$.data(e, ...)   // The function form
------------------------------------------------------------

code/ch03.js

0 → 100644
+55 −0
Changes for code/ch03.js: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line

// Add content at end of the #log element
$("#log").append("<br/>"+message); 
// Add section sign at start of each <h1>
$("h1").prepend("§");              
// Insert a rule before and after each <h1>
$("h1").before("<hr/>");           
$("h1").after("<hr/>");            
// Replace <hr/> tags with <br/> tags
$("hr").replaceWith("<br/>");      
// Replace <h2> with <h1>, keeping content
$("h2").each(function() {          
    var h2 = $(this);
    h2.replaceWith("<h1>" + h2.html() + "</h1>");
});
// after() and before() can also be called on text nodes.
// Here is Another way to add § at the start of each <h1>
$("h1").map(function() {    // Map each <h1> element to
    return this.firstChild; // its first content node
}).before("§");
------------------------------------------------------------

// Append html to #log
$("<br/>+message").appendTo("#log");
// Append text node to <h1>s
$(document.createTextNode("§")).prependTo("h1");
// Insert rule before and after <h1>s
$("<hr/>").insertBefore("h1");
$("<hr/>").insertAfter("h1");
// Replace <hr/> with <br/>
$("<br/>").replaceAll("hr");
------------------------------------------------------------

// Append a new div, with id "linklist" to the document
$(document.body)
    .append("<div id='linklist'><h1>Links</h1></div>");
// Copy all links in the document into that new div
$("a").clone().appendTo("#linklist");
// Add a <br/> after each link so they don't run together
$("#linklist > a").after("<br/>");
------------------------------------------------------------

// Wrap all <h1> tags with <i> tags
// Produces <i><h1>...</h1></i>
$("h1").wrap(document.createElement("i")); 
// Wrap the content of all <h1> tags. 
// Produces <h1><i>...</i></h1>
$("h1").wrapInner("<i/>");
// Wrap the first paragraph in an anchor and div
$("body>p:first")
    .wrap("<a name='f'><div class='first'></div></a>");
// Wrap all the other paragraphs in another div
$("body>p:not(:first)")
    .wrapAll("<div class='rest'></div>");
------------------------------------------------------------
Loading