diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..8b808995d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.js, *.xsl] +indent_style = tab diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..b7ca95b5b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# JS files must always use LF for tools to work +*.js eol=lf diff --git a/.github/configs/hydra-config.json b/.github/configs/hydra-config.json new file mode 100644 index 000000000..2173722b4 --- /dev/null +++ b/.github/configs/hydra-config.json @@ -0,0 +1,10 @@ +{ + "//": [ + "2023-05: twitter.com serves broken redirect-loop", + "2025-04: The oembed endpoint responds HTTP 429 Too Many Requests too often; perhaps because almost every page links to one" + ], + "exclude_scheme_prefixes": [ + "https://twitter.com/", + "https://api.jquery.com/wp-json/oembed/1.0/embed" + ] +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..aa2f74565 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: monthly + + # Group all dependabot version update PRs into one + groups: + github-actions: + applies-to: version-updates + patterns: + - "*" diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml new file mode 100644 index 000000000..30412870c --- /dev/null +++ b/.github/workflows/node.js.yml @@ -0,0 +1,32 @@ +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs + +name: Node.js CI + +on: + pull_request: + push: + branches-ignore: "dependabot/**" + +jobs: + build: + + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18.x, 20.x] + + steps: + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Update apt-get cache + run: sudo apt-get update + - name: Install xmllint + run: sudo apt-get install -y libxml2-utils + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: ${{ matrix.node-version }} + cache: 'npm' + - run: npm ci + - run: npm test diff --git a/.github/workflows/spider-check.yaml b/.github/workflows/spider-check.yaml new file mode 100644 index 000000000..95ea1ea24 --- /dev/null +++ b/.github/workflows/spider-check.yaml @@ -0,0 +1,32 @@ +name: spider-check +on: + # Once a week on Friday at 00:00 + schedule: + - cron: '0 0 * * 5' + # Or manually + workflow_dispatch: + # Or when developing this workflow + push: + paths: + - .github/workflows/spider-check.yaml + - .github/configs/hydra-config.json + pull_request: + paths: + - .github/workflows/spider-check.yaml + - .github/configs/hydra-config.json + +jobs: + spider-check: + if: ${{ github.repository_owner == 'jquery' }} # skip on forks + runs-on: ubuntu-latest + env: + # Site address to crawl + MY_SITE: https://api.jquery.com + steps: + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Run hydra-link-checker + run: | + curl -O https://raw.githubusercontent.com/jquery/hydra-link-checker/v2.0.0/hydra.py + python3 hydra.py "$MY_SITE" --config .github/configs/hydra-config.json diff --git a/.github/workflows/typesense.yaml b/.github/workflows/typesense.yaml new file mode 100644 index 000000000..de973410d --- /dev/null +++ b/.github/workflows/typesense.yaml @@ -0,0 +1,30 @@ +name: typesense +on: + # Once a day at 11:30 UTC + schedule: + - cron: '30 11 * * *' + # Or after a deployment + push: + branches: + - main + # Or manually + workflow_dispatch: + +jobs: + typesense: + name: Update Typesense + if: ${{ github.repository_owner == 'jquery' }} # skip on forks + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Docsearch Scraper + shell: bash + run: | + docker run \ + -e TYPESENSE_API_KEY=${{ secrets.TYPESENSE_ADMIN_KEY }} \ + -e TYPESENSE_HOST="${{ secrets.TYPESENSE_HOST }}" \ + -e TYPESENSE_PORT="443" \ + -e TYPESENSE_PROTOCOL="https" \ + -e CONFIG="$(cat docsearch.config.json | jq -r tostring)" \ + typesense/docsearch-scraper:0.9.1 diff --git a/.gitignore b/.gitignore index 2dc8b339c..633f1bdef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,3 @@ -dist -entries_tmp -node_modules -config.json -.project -*~ -*.diff -*.patch -.DS_Store -.settings \ No newline at end of file +/dist/ +/node_modules/ +config.js* diff --git a/.mailmap b/.mailmap new file mode 100644 index 000000000..5f931fbce --- /dev/null +++ b/.mailmap @@ -0,0 +1,6 @@ +Matic Potočnik +Michał Gołębiowski-Owczarek +Timmy Willison +Timmy Willison <4timmywil@gmail.com> +Timmy Willison +Timo Tijhof diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 000000000..3c032078a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +18 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..9a004cd36 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,5 @@ +Welcome! Thanks for your interest in contributing to api.jquery.com. You're **almost** in the right place. More information on how to contribute to this and all other jQuery Foundation projects is over at [contribute.jquery.org](https://contribute.jquery.org). You'll definitely want to take a look at the articles on contributing [documentation](https://contribute.jquery.org/documentation). + +You may also want to take a look at our [commit & pull request guide](https://contribute.jquery.org/commits-and-pull-requests/) and [style guides](https://contribute.jquery.org/style-guide/) for instructions on how to maintain your fork and submit your code. Before we can merge any pull request, we'll also need you to sign our [contributor license agreement](https://contribute.jquery.org/cla). + +You can find us on [IRC](https://irc.jquery.org), specifically in #jquery-dev and #jquery-content should you have any questions. If you've never contributed to open source before, we've put together [a short guide with tips, tricks, and ideas on getting started](https://contribute.jquery.org/open-source/). diff --git a/Gruntfile.js b/Gruntfile.js new file mode 100644 index 000000000..10aa18ab0 --- /dev/null +++ b/Gruntfile.js @@ -0,0 +1,48 @@ +module.exports = function( grunt ) { + +grunt.loadNpmTasks( "grunt-jquery-content" ); + +grunt.initConfig({ + xmllint: { + all: [ + "entries/**", + "includes/**", + "categories.xml", + "entries2html.xsl", + "notes.xsl" + ] + }, + "build-posts": { + page: "pages/**" + }, + "build-xml-entries": { + all: "entries/**" + }, + "build-resources": { + all: "resources/**" + }, + wordpress: (function() { + + // There's no config for CI, but we don't need one for basic testing + var config = {}; + try { + config = require( "./config" ); + } catch ( error ) {} + config.dir = "dist/wordpress"; + return config; + })() +}); + +grunt.registerTask( "lint", [ "xmllint" ]); + +grunt.registerTask( "build", [ + "build-posts", + "build-resources", + "build-xml-entries", + "build-xml-categories", + "build-xml-full" +]); + +grunt.registerTask( "deploy", [ "wordpress-deploy", "deploy-redirects" ] ); + +}; diff --git a/LICENSE-MIT.txt b/LICENSE.txt similarity index 61% rename from LICENSE-MIT.txt rename to LICENSE.txt index e8b475d68..203b68a7b 100644 --- a/LICENSE-MIT.txt +++ b/LICENSE.txt @@ -1,9 +1,14 @@ -Copyright (c) 2009 Packt Publishing, http://packtpub.com/ -Copyright (c) 2012 jQuery Foundation, http://jquery.org/ +Copyright Packt Publishing (https://www.packtpub.com/), +jQuery Foundation (https://jquery.org/), and other contributors. This software consists of voluntary contributions made by many individuals. For exact contribution history, see the revision history -and logs, available at http://github.com/jquery/api.jquery.com +available at https://github.com/jquery/api.jquery.com + +The following license applies to all parts of this software except as +documented below: + +==== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the @@ -23,3 +28,18 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation and all examples and demos. + +CC0: https://creativecommons.org/publicdomain/zero/1.0/ + +==== + +All files located in the node_modules directory are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/README.md b/README.md index d5dfc651e..f79208030 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,17 @@ -## Referencing Bug Tracker Tickets +# api.jquery.com -* Pull requests for changes that were requested or recommended via the [jQuery Bug Tracker](http://bugs.jquery.com) should include a link back to the relevant ticket. +## Building and Deploying -## Building +To build and deploy your changes for previewing in a [`jquery-wp-content`](https://github.com/jquery/jquery-wp-content) instance, follow the [workflow instructions](https://contribute.jquery.org/web-sites/#workflow) from our documentation on [contributing to jQuery Foundation web sites](https://contribute.jquery.org/web-sites/). ### Requirements -* libxml2 -* libxslt -The `xmllint` and `xsltproc` utilities need to be in your path. If you are on Windows, you can get libxml2 and libxslt from zlatkovic.com. +* [libxml2](http://xmlsoft.org/) +* [libxslt](http://xmlsoft.org/libxslt/) -### Build +The `xmllint` and `xsltproc` utilities need to be in your path. If you are on Windows, you can get libxml2 and libxslt from zlatkovic.com. -To build and deploy your changes for previewing in a [jquery-wp-content](https://github.com/jquery/jquery-wp-content) instance, follow the [workflow instructions](http://contribute.jquery.org/web-sites/#workflow) from our documentation on [contributing to jQuery Foundation web sites](http://contribute.jquery.org/web-sites/). +**Note**: If you're using Windows and you receive the error "Error" when executing the task `build-xml-entries:all`, try to add the DLL `libwinpthread-1.dll` in the root of the project. ## Style Guidelines @@ -27,13 +26,15 @@ To build and deploy your changes for previewing in a [jquery-wp-content](https:/ * **No**: The `load`, `scroll` and `error` events (e.g., on an `` element) do not bubble #### Spelling + * The documentation standardizes on American English spelling. For example: * **Yes**: color, while, among, customize, argument * **No**: colour, whilst, amongst, customise, arguement #### Pronoun Usage + * Use second-person pronoun ("you") when necessary, but try to avoid it. -* Favor the definite article ("the") over second-person possesive ("your"). +* Favor the definite article ("the") over second-person possessive ("your"). * **Yes**: Insert the paragraph after the unordered list. * **No**: Insert your paragraph after the unordered list. * When editing current entries, change first-person plural pronouns ("we," "our," "us") to second-person. @@ -41,28 +42,32 @@ To build and deploy your changes for previewing in a [jquery-wp-content](https:/ * **No**: And now we have our paragraph beneath the unordered list. #### "Voice" + * Prefer active voice over passive. * **Active**: Calling `.click()` binds a click handler to the elements in the collection * **Passive**: Click handlers are bound to elements in the collection when `.click()` is called ### Code Style -Code in the API documentation should follow the [jQuery Core Style Guide](http://docs.jquery.com/JQuery_Core_Style_Guidelines) with the following addition and exception: + +Code in the API documentation should follow the [jQuery Core Style Guide](https://contribute.jquery.org/style-guide/) with the following addition: * **Document ready syntax**: Use `$( document ).ready(function() {` instead of `$(function() {` as it's harder for new users to distinguish the difference between the latter and an IIFE. -* **Indentation**: Core guidelines say to use tabs. In API documentation, *use 2 spaces instead*. This helps keep the line width manageable and avoid horizontal scrollbars. #### Code within prose content (paragraphs and the like): -* Methods: use a dot, followed by the method name, followed by parentheses: e.g. The `.focus()` method is a shortcut for `.bind('focus', handler)` in the first and second variations, and `.trigger('focus')` in the third. + +* Methods: use a dot, followed by the method name, followed by parentheses: e.g. The `.focus()` method is a shortcut for `.on( "focus", handler )` in the first and second variations, and `.trigger( "focus" )` in the third. * Properties: use a dot, followed by the property name: e.g. `.length`. * Functions: use the function name, followed by parentheses: `myFunction()`. #### Examples + * Examples should indicate what the expected result will be before presenting the code. This makes code clearer and skimming easier, especially for newer coders who may not understand what is supposed to be happening from reading the code itself. * **Yes**: Find all p elements that are children of a div element and apply a border to them. * **No**: Find all p elements that are children of a div element. * Make your example easy to follow with good comments so that the explanation isn't necessary. ### Rhetorical Context + * Subject * The entirety of jQuery's public API * Audience @@ -80,5 +85,5 @@ Code in the API documentation should follow the [jQuery Core Style Guide](http:/ * Strong in English writing * Tone * Middle ground between formal and familiar. Err on the side of formality. - * Authoritive + * Authoritative * Tactful diff --git a/categories.xml b/categories.xml index 43277b9df..0f7d4df12 100644 --- a/categories.xml +++ b/categories.xml @@ -1,18 +1,18 @@ - + - + - + - + - + @@ -36,19 +36,87 @@ + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -78,31 +146,29 @@ @@ -150,15 +213,15 @@ - + + A few of these methods—such as .attr(), .html(), and .val()—also act as "getters," retrieving information from DOM elements for later use. + ]]> @@ -217,16 +280,19 @@ + + + ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

+

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

]]>
, will select <a href="example.html" rel="nofollow">Some text</a> but not <a href="example.html" rel="nofollow foe">Some text</a>.

-

Attribute values in selector expressions must follow the rules for W3C CSS selectors; in general, that means anything other than a valid identifier should be surrounded by quotation marks.

+

Attribute values in selector expressions must follow the rules for W3C CSS selectors; in general, that means anything other than a valid identifier should be surrounded by quotation marks.

  • double quotes inside single quotes: $('a[rel="nofollow self"]')
  • single quotes inside double quotes: $("a[rel='nofollow self']")
  • @@ -240,7 +306,7 @@ - + @@ -258,7 +324,7 @@ - + @@ -283,116 +349,284 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config-sample.json b/config-sample.json index ee1430bea..2a56329c3 100644 --- a/config-sample.json +++ b/config-sample.json @@ -1,5 +1,5 @@ { - "url": "dev.api.jquery.com", - "username": "admin", - "password": "secret" + "url": "http://local.api.jquery.com", + "username": "dev", + "password": "dev" } diff --git a/docsearch.config.json b/docsearch.config.json new file mode 100644 index 000000000..f420af4af --- /dev/null +++ b/docsearch.config.json @@ -0,0 +1,52 @@ +{ + "index_name": "jquery_com", + "start_urls": [ + { "url": "https://api.jquery.com", "selectors_key": "api", "page_rank": 20 }, + { "url": "https://jquery.com", "page_rank": 10 } + ], + "stop_urls": [ + ".com/category/" + ], + "selectors": { + "default": { + "lvl0": { + "selector": "#menu-top .menu-item.current > a", + "global": true, + "default_value": "Documentation" + }, + "lvl1": "#content h1", + "lvl2": "#content h2", + "lvl3": "#content h3", + "lvl4": "#content h4", + "lvl5": "#content h5", + "text": "#content p, #content li, #content tr" + }, + "api": { + "lvl0": { + "selector": "#categories .cat-item.current-cat > a", + "global": true, + "default_value": "API" + }, + "lvl1": "#content h1", + "lvl2": "#content h2, #content h4.name", + "lvl3": "#content h3, #content h4:not(.name)", + "lvl4": "#content h5, #content strong:first-child", + "text": ".entry-content p, .entry-content li" + } + }, + "custom_settings": { + "token_separators": ["_", "-", "."] + }, + "selectors_exclude": [ + "header ~ article", + ".returns", + ".version-details", + ".section-title", + ".icon-link.toc-link", + "[class^=toclevel]", + "#toctitle", + ".desc strong:first-child" + ], + "min_indexed_level": 2, + "scrape_start_urls": false +} diff --git a/entries/add.xml b/entries/add.xml index 71ba5074f..bb95b0f0b 100644 --- a/entries/add.xml +++ b/entries/add.xml @@ -9,19 +9,19 @@ 1.0 - + One or more elements to add to the set of matched elements. 1.0 - + An HTML fragment to add to the set of matched elements. - 1.3.2 - + 1.1 + An existing jQuery object to add to the set of matched elements. @@ -34,98 +34,125 @@ The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. - Add elements to the set of matched elements. + Create a new jQuery object with elements added to the set of matched elements. -

    Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

    +

    Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to .add() can be pretty much anything that $() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.

    +

    Do not assume that this method appends the elements to the existing collection in the order they are passed to the .add() method. When all elements are members of the same document, the resulting collection from .add() will be sorted in document order; that is, in order of each element's appearance in the document. If the collection consists of elements from different documents or ones not in any document, the sort order is undefined. To create a jQuery object with elements in a well-defined order and without sorting overhead, use the $(array_of_DOM_elements) signature.

    The updated set of elements can be used in a following (chained) method, or assigned to a variable for later use. For example:

    -
    -      
    -$("p").add("div").addClass("widget");
    -var pdiv = $("p").add("div");
    -
    -    
    +
    
    +$( "p" ).add( "div" ).addClass( "widget" );
    +var pdiv = $( "p" ).add( "div" );
    +    

    The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

    -
    -      
    -var pdiv = $("p");
    -pdiv.add("div");  // WRONG, pdiv will not change
    -
    -    
    +
    
    +var pdiv = $( "p" );
    +pdiv.add( "div" ); // WRONG, pdiv will not change
    +    

    Consider a page with a simple list and a paragraph following it:

    -
    -      <ul>
    +    
    
    +<ul>
       <li>list item 1</li>
       <li>list item 2</li>
       <li>list item 3</li>
     </ul>
    -<p>a paragraph</p>
    -    
    +<p>a paragraph</p> +

    We can select the list items and then the paragraph by using either a selector or a reference to the DOM element itself as the .add() method's argument:

    -
    -      $('li').add('p').css('background-color', 'red');
    -    
    +
    
    +$( "li" ).add( "p" ).css( "background-color", "red" );
    +    

    Or:

    -
    -      $('li').add(document.getElementsByTagName('p')[0])
    -  .css('background-color', 'red');
    -    
    +
    
    +$( "li" ).add( document.getElementsByTagName( "p" )[ 0 ] )
    +  .css( "background-color", "red" );
    +    

    The result of this call is a red background behind all four elements. Using an HTML snippet as the .add() method's argument (as in the third version), we can create additional elements on the fly and add those elements to the matched set of elements. Let's say, for example, that we want to alter the background of the list items along with a newly created paragraph:

    -
    -      $('li').add('<p id="new">new paragraph</p>')
    -  .css('background-color', 'red');
    -    
    +
    
    +$( "li" ).add( "<p id='new'>new paragraph</p>" )
    +  .css( "background-color", "red" );
    +    

    Although the new paragraph has been created and its background color changed, it still does not appear on the page. To place it on the page, we could add one of the insertion methods to the chain.

    As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).

    -

    Note: To reverse the .add() you can use .not( elements | selector ) to remove elements from the jQuery results, or .end() to return to the selection before you added.

    +

    Note: To reverse the .add() you can use .not( elements | selector ) to remove elements from the jQuery results, or .end() to return to the selection before you added.

    Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow. - + +

    Added this... (notice no border)

    +]]>
    Adds more elements, matched by the given expression, to the set of matched elements. - - + + Adds more elements, created on the fly, to the set of matched elements. - - + + Adds one or more Elements to the set of matched elements. - - + + Demonstrates how to add (or push) elements to an existing collection - - + + - \ No newline at end of file + diff --git a/entries/addBack.xml b/entries/addBack.xml index 05056ac6c..f8c11f32f 100644 --- a/entries/addBack.xml +++ b/entries/addBack.xml @@ -13,37 +13,50 @@

    Consider a page with a simple list on it:

    
     <ul>
    -   <li>list item 1</li>
    -   <li>list item 2</li>
    -   <li class="third-item">list item 3</li>
    -   <li>list item 4</li>
    -   <li>list item 5</li>
    +  <li>list item 1</li>
    +  <li>list item 2</li>
    +  <li class="third-item">list item 3</li>
    +  <li>list item 4</li>
    +  <li>list item 5</li>
     </ul>
    -
    +

    The result of the following code is a red background behind items 3, 4 and 5:

    -
    $('li.third-item').nextAll().addBack()
    -  .css('background-color', 'red');
    -
    +
    
    +$( "li.third-item" ).nextAll().addBack()
    +  .css( "background-color", "red" );
    +    

    First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to .nextAll() then pushes the set of items 4 and 5 onto the stack. Finally, the .addBack() invocation merges these two sets together, creating a jQuery object that points to all three items in document order: {[<li.third-item>,<li>,<li> ]}.

    The .addBack() method causes the previous set of DOM elements in the traversal stack to be added to the current set. In the first example, the top stack contains the set resulting from .find("p"). In the second example, .addBack() adds the previous set of elements on the stack — in this case $("div.after-addback") — to the current set, selecting both the div and its enclosed paragraphs. + p, div { + margin: 5px; + padding: 5px; + } + .border { + border: 2px solid red; + } + .background { + background: yellow; + } + .left, .right { + width: 45%; + float: left; + } + .right { + margin-left: 3%; + } +]]> +$( "p" ).last().addClass( "selected" ); +]]> + p { + margin: 8px; + font-size: 16px; + } + .selected { + color: blue; + } + .highlight { + background: yellow; + } +]]> +

    Hello

    +

    and

    +

    Goodbye

    +]]>
    Add the classes "selected" and "highlight" to the matched elements. +$( "p" ).last().addClass( "selected highlight" ); +]]> + + + + + Add the classes "selected" and "highlight" to the matched elements (3.3+ syntax). + - + p { + margin: 8px; + font-size: 16px; + } + .selected { + color: red; + } + .highlight { + background: yellow; + } +]]> + Pass in a function to .addClass() to add the "green" class to a div that already has a "red" class. + div { + background: white; + } + .red { + background: red; + } + .red.green { + background: green; + } +]]> -

    Since .after() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $('p').first().after($newdiv1, newdiv2, existingdiv1). The type and number of arguments will largely depend on the elements that are collected in the code.

    +$( "p" ).first().after( $newdiv1, [ newdiv2, existingdiv1 ] ); + +

    Since .after() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $( "p" ).first().after( $newdiv1, newdiv2, existingdiv1 ). The type and number of arguments will largely depend on the elements that are collected in the code.

    + + Inserts some HTML after all paragraphs. - - - + + + Inserts a DOM element after all paragraphs. - - - + + + Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs. - - - + + + diff --git a/entries/ajaxComplete-shorthand.xml b/entries/ajaxComplete-shorthand.xml new file mode 100644 index 000000000..3f44abc14 --- /dev/null +++ b/entries/ajaxComplete-shorthand.xml @@ -0,0 +1,19 @@ + + + .ajaxComplete() + Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + + 1.0 + + The function to be invoked. + + + +
    +

    This API is deprecated. Use .on( "ajaxComplete", handler ) instead.

    +
    +
    + + + +
    diff --git a/entries/ajaxComplete.xml b/entries/ajaxComplete.xml index 8064a68cd..0c133516f 100644 --- a/entries/ajaxComplete.xml +++ b/entries/ajaxComplete.xml @@ -1,47 +1,65 @@ - - .ajaxComplete() + + ajaxComplete event + Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - 1.0 - + 1.7 + + The string "ajaxComplete". + + + + + The function to be invoked. - Register a handler to be called when Ajax requests complete. This is an AjaxEvent. -

    Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.

    +
    +

    This page describes the ajaxComplete event. For the deprecated .ajaxComplete() method, see .ajaxComplete().

    +
    +

    Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all registered ajaxComplete handlers are executed at this time.

    To observe this method in action, set up a basic Ajax load request:

    -
    <div class="trigger">Trigger</div>
    +    
    
    +<div class="trigger">Trigger</div>
     <div class="result"></div>
     <div class="log"></div>
    -
    +

    Attach the event handler to the document:

    -
    $(document).ajaxComplete(function() {
    +    
    
    +$( document ).on( "ajaxComplete", function() {
       $( ".log" ).text( "Triggered ajaxComplete handler." );
    -});
    -
    +} ); +

    Now, make an Ajax request using any jQuery method:

    -
    $( ".trigger" ).click(function() {
    +    
    
    +$( ".trigger" ).on( "click", function() {
       $( ".result" ).load( "ajax/test.html" );
    -});
    +} ); +

    When the user clicks the element with class trigger and the Ajax request completes, the log message is displayed.

    -

    Note: Because .ajaxComplete() is implemented as a method of jQuery object instances, you can use the this keyword to refer to the selected elements within the callback function. As of jQuery 1.8, however, the .ajaxComplete() method should only be attached to document.

    All ajaxComplete handlers are invoked, regardless of what Ajax request was completed. If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, you can restrict the callback to only handling events dealing with a particular URL:

    -
    $(document).ajaxComplete(function(event, xhr, settings) {
    +    
    
    +$( document ).on( "ajaxComplete", function( event, xhr, settings ) {
       if ( settings.url === "ajax/test.html" ) {
         $( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
    -                     xhr.responseHTML );
    +      xhr.responseText );
       }
    -});
    -

    Note: You can get the returned ajax contents by looking at xhr.responseXML or xhr.responseHTML for xml and html respectively.

    +} ); +
    +

    Note: You can get the returned Ajax contents by looking at xhr.responseText.

    - + + Show a message when an Ajax request completes. - + +
    diff --git a/entries/ajaxError-shorthand.xml b/entries/ajaxError-shorthand.xml new file mode 100644 index 000000000..f36ac54a8 --- /dev/null +++ b/entries/ajaxError-shorthand.xml @@ -0,0 +1,19 @@ + + + .ajaxError() + Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + + 1.0 + + The function to be invoked. + + + +
    +

    This API is deprecated. Use .on( "ajaxError", handler ) instead.

    +
    +
    + + + +
    diff --git a/entries/ajaxError.xml b/entries/ajaxError.xml index c0e3c5c7a..d18cf9775 100644 --- a/entries/ajaxError.xml +++ b/entries/ajaxError.xml @@ -1,43 +1,64 @@ - - .ajaxError() + + ajaxError event + Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. - 1.0 - + 1.7 + + The string "ajaxError". + + The function to be invoked. + + + + - Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. -

    Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.

    +
    +

    This page describes the ajaxError event. For the deprecated .ajaxError() method, see .ajaxError().

    +
    +

    Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all registered ajaxError handlers are executed at this time. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

    To observe this method in action, set up a basic Ajax load request.

    -
    <button class="trigger">Trigger</button>
    +    
    
    +<button class="trigger">Trigger</button>
     <div class="result"></div>
    -<div class="log"></div>
    +<div class="log"></div> +

    Attach the event handler to the document:

    -
    $(document).ajaxError(function() {
    -  $( "div.log" ).text( "Triggered ajaxError handler." );
    -});
    +
    
    +$( document ).on( "ajaxError", function() {
    +  $( ".log" ).text( "Triggered ajaxError handler." );
    +} );
    +    

    Now, make an Ajax request using any jQuery method:

    -
    $( "button.trigger" ).click(function() {
    +    
    
    +$( "button.trigger" ).on( "click", function() {
       $( "div.result" ).load( "ajax/missing.html" );
    -});
    +} ); +

    When the user clicks the button and the Ajax request fails, because the requested file is missing, the log message is displayed.

    -

    Note: Because .ajaxError() is implemented as a method of jQuery object instances, you can use the this keyword within the callback function to refer to the selected elements. As of jQuery 1.8, however, the .ajaxError() method should only be attached to document.

    -

    All ajaxError handlers are invoked, regardless of what Ajax request was completed. To differentiate between the requests, use the parameters passed to the handler. Each time an ajaxError handler is executed, it is passed the event object, the jqXHR object (prior to jQuery 1.5, the XHR object), and the settings object that was used in the creation of the request. If the request failed because JavaScript raised an exception, the exception object is passed to the handler as a fourth parameter. For example, to restrict the error callback to only handling events dealing with a particular URL:

    -
    $( document ).ajaxError(function(event, jqxhr, settings, exception) {
    +    

    All ajaxError handlers are invoked, regardless of what Ajax request was completed. To differentiate between the requests, use the parameters passed to the handler. Each time an ajaxError handler is executed, it is passed the event object, the jqXHR object (prior to jQuery 1.5, the XHR object), and the settings object that was used in the creation of the request. When an HTTP error occurs, the fourth argument (thrownError) receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." For example, to restrict the error callback to only handling events dealing with a particular URL:

    +
    
    +$( document ).on( "ajaxError", function( event, jqxhr, settings, thrownError ) {
       if ( settings.url == "ajax/missing.html" ) {
         $( "div.log" ).text( "Triggered ajaxError handler." );
       }
    -});
    +} ); +
    - + + Show a message when an Ajax request fails. - +} ); +]]> +
    diff --git a/entries/ajaxSend-shorthand.xml b/entries/ajaxSend-shorthand.xml new file mode 100644 index 000000000..a9ae031e7 --- /dev/null +++ b/entries/ajaxSend-shorthand.xml @@ -0,0 +1,19 @@ + + + .ajaxSend() + Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + + 1.0 + + The function to be invoked. + + + +
    +

    This API is deprecated. Use .on( "ajaxSend", handler ) instead.

    +
    +
    + + + +
    diff --git a/entries/ajaxSend.xml b/entries/ajaxSend.xml index 3639b44fd..cbd1641cd 100644 --- a/entries/ajaxSend.xml +++ b/entries/ajaxSend.xml @@ -1,43 +1,63 @@ - - .ajaxSend() + + ajaxSend event + Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. - 1.0 - + 1.7 + + The string "ajaxSend". + + The function to be invoked. + + + - Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. -

    Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.

    +
    +

    This page describes the ajaxSend event. For the deprecated .ajaxSend() method, see .ajaxSend().

    +
    +

    Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all registerd ajaxSend handlers are executed at this time.

    To observe this method in action, set up a basic Ajax load request:

    -
    <div class="trigger">Trigger</div>
    +    
    
    +<div class="trigger">Trigger</div>
     <div class="result"></div>
    -<div class="log"></div>
    +<div class="log"></div> +

    Attach the event handler to the document:

    -
    $(document).ajaxSend(function() {
    +    
    
    +$( document ).on( "ajaxSend", function() {
       $( ".log" ).text( "Triggered ajaxSend handler." );
    -});
    +} ); +

    Now, make an Ajax request using any jQuery method:

    -
    $( ".trigger" ).click(function() {
    +    
    
    +$( ".trigger" ).on( "click", function() {
       $( ".result" ).load( "ajax/test.html" );
    -});
    +} ); +

    When the user clicks the element with class trigger and the Ajax request is about to begin, the log message is displayed.

    -

    Note: Because .ajaxSend() is implemented as a method of jQuery instances, you can use the this keyword to refer to the selected elements within the callback function. As of jQuery 1.8, however, the .ajaxSend() method should only be attached to document.

    -

    All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent. If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxSend handler is executed, it is passed the event object, the jqXHR object (in version 1.4, XMLHttpRequestobject), and the settings object that was used in the creation of the Ajax request. For example, you can restrict the callback to only handling events dealing with a particular URL:

    -
    $(document).ajaxSend(function(event, jqxhr, settings) {
    +    

    All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent. If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxSend handler is executed, it is passed the event object, the jqXHR object (in version 1.4, XMLHttpRequestobject), and the settings object that was used in the creation of the Ajax request. For example, you can restrict the callback to only handling events dealing with a particular URL:

    +
    
    +$( document ).on( "ajaxSend", function( event, jqxhr, settings ) {
       if ( settings.url == "ajax/test.html" ) {
         $( ".log" ).text( "Triggered ajaxSend handler." );
       }
    -});
    +} ); +
    - + + Show a message before an Ajax request is sent. - + +
    diff --git a/entries/ajaxStart-shorthand.xml b/entries/ajaxStart-shorthand.xml new file mode 100644 index 000000000..51b2fc9e3 --- /dev/null +++ b/entries/ajaxStart-shorthand.xml @@ -0,0 +1,19 @@ + + + .ajaxStart() + Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + + 1.0 + + The function to be invoked. + + + +
    +

    This API is deprecated. Use .on( "ajaxStart", handler ) instead.

    +
    +
    + + + +
    diff --git a/entries/ajaxStart.xml b/entries/ajaxStart.xml index 5097dcec3..3d8f4df4f 100644 --- a/entries/ajaxStart.xml +++ b/entries/ajaxStart.xml @@ -1,37 +1,52 @@ - - .ajaxStart() + + ajaxStart event + Register a handler to be called when the first Ajax request begins. This is an Ajax Event. - 1.0 - + 1.7 + + The string "ajaxStart". + + The function to be invoked. - Register a handler to be called when the first Ajax request begins. This is an Ajax Event. -

    Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with the .ajaxStart() method are executed at this time.

    +
    +

    This page describes the ajaxStart event. For the deprecated .ajaxStart() method, see .ajaxStart().

    +
    +

    Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with .on( "ajaxStart", ... ) are executed at this time.

    To observe this method in action, set up a basic Ajax load request:

    -
    <div class="trigger">Trigger</div>
    +    
    
    +<div class="trigger">Trigger</div>
     <div class="result"></div>
    -<div class="log"></div>
    +<div class="log"></div> +

    Attach the event handler to any element:

    -
    $(document).ajaxStart(function() {
    +    
    
    +$( document ).on( "ajaxStart", function() {
       $( ".log" ).text( "Triggered ajaxStart handler." );
    -});
    +} ); +

    Now, make an Ajax request using any jQuery method:

    -
    $( ".trigger" ).click(function() {
    -  $( ".result" ).load("ajax/test.html");
    -});
    +
    
    +$( ".trigger" ).on( "click", function() {
    +  $( ".result" ).load( "ajax/test.html" );
    +} );
    +    

    When the user clicks the element with class trigger and the Ajax request is sent, the log message is displayed.

    -

    Note: Because .ajaxStart() is implemented as a method of jQuery object instances, you can use the this keyword to refer to the selected elements within the callback function. As of jQuery 1.8, however, the .ajaxStart() method should only be attached to document.

    - + + Show a loading message whenever an Ajax request starts (and none is already active). - + +
    diff --git a/entries/ajaxStop-shorthand.xml b/entries/ajaxStop-shorthand.xml new file mode 100644 index 000000000..781216575 --- /dev/null +++ b/entries/ajaxStop-shorthand.xml @@ -0,0 +1,19 @@ + + + .ajaxStop() + Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + + 1.0 + + The function to be invoked. + + + +
    +

    This API is deprecated. Use .on( "ajaxStop", handler ) instead.

    +
    +
    + + + +
    diff --git a/entries/ajaxStop.xml b/entries/ajaxStop.xml index e8e947de5..f42c74448 100644 --- a/entries/ajaxStop.xml +++ b/entries/ajaxStop.xml @@ -1,37 +1,52 @@ - - .ajaxStop() - Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + + ajaxStop event + Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - 1.0 - + 1.7 + + The string "ajaxStop". + + The function to be invoked. -

    Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event. Any and all handlers that have been registered with the .ajaxStop() method are executed at this time. The ajaxStop event is also triggered if the last outstanding Ajax request is cancelled by returning false within the beforeSend callback function.

    +
    +

    This page describes the ajaxStop event. For the deprecated .ajaxStop() method, see .ajaxStop().

    +
    +

    Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event. Any and all registered ajaxStop handlers are executed at this time. The ajaxStop event is also triggered if the last outstanding Ajax request is cancelled by returning false within the beforeSend callback function.

    To observe this method in action, set up a basic Ajax load request:

    -
    <div class="trigger">Trigger</div>
    +    
    
    +<div class="trigger">Trigger</div>
     <div class="result"></div>
    -<div class="log"></div>
    +<div class="log"></div> +

    Attach the event handler to the document:

    -
    $( ".log" ).ajaxStop(function() {
    -  $(this).text( "Triggered ajaxStop handler." );
    -});
    +
    
    +$( document ).on( "ajaxStop", function() {
    +  $( ".log" ).text( "Triggered ajaxStop handler." );
    +} );
    +    

    Now, make an Ajax request using any jQuery method:

    -
    $( ".trigger" ).click(function() {
    +    
    
    +$( ".trigger" ).on( "click", function() {
       $( ".result" ).load( "ajax/test.html" );
    -});
    +} ); +

    When the user clicks the element with class trigger and the Ajax request completes, the log message is displayed.

    -

    Because .ajaxStop() is implemented as a method of jQuery object instances, you can use the this keyword to refer to the selected elements within the callback function. As of jQuery 1.8, however, the .ajaxStop() method should only be attached to document.

    - + + Hide a loading message after all the Ajax requests have stopped. - + +
    diff --git a/entries/ajaxSuccess-shorthand.xml b/entries/ajaxSuccess-shorthand.xml new file mode 100644 index 000000000..a9e543350 --- /dev/null +++ b/entries/ajaxSuccess-shorthand.xml @@ -0,0 +1,19 @@ + + + .ajaxSuccess() + Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + + 1.0 + + The function to be invoked. + + + +
    +

    This API is deprecated. Use .on( "ajaxSuccess", handler ) instead.

    +
    +
    + + + +
    diff --git a/entries/ajaxSuccess.xml b/entries/ajaxSuccess.xml index 9a9d7eedf..8824a6212 100644 --- a/entries/ajaxSuccess.xml +++ b/entries/ajaxSuccess.xml @@ -1,45 +1,66 @@ - - .ajaxSuccess() + + ajaxSuccess event + Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - 1.0 - + 1.7 + + The string "ajaxSuccess". + + The function to be invoked. + + + + - Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. -

    Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.

    +
    +

    This page describes the ajaxSuccess event. For the deprecated .ajaxSuccess() method, see .ajaxSuccess().

    +
    +

    Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all registered ajaxSuccess handlers are executed at this time.

    To observe this method in action, set up a basic Ajax load request:

    -
    <div class="trigger">Trigger</div>
    +    
    
    +<div class="trigger">Trigger</div>
     <div class="result"></div>
    -<div class="log"></div>
    +<div class="log"></div> +

    Attach the event handler to any element:

    -
    $(document).ajaxSuccess(function() {
    +    
    
    +$( document ).on( "ajaxSuccess", function() {
       $( ".log" ).text( "Triggered ajaxSuccess handler." );
    -});
    +} ); +

    Now, make an Ajax request using any jQuery method:

    -
    $( ".trigger" ).on("click", function() {
    +    
    
    +$( ".trigger" ).on( "click", function() {
       $( ".result" ).load( "ajax/test.html" );
    -});
    +} ); +

    When the user clicks the element with class trigger and the Ajax request completes successfully, the log message is displayed.

    -

    Note: Because .ajaxSuccess() is implemented as a method of jQuery object instances, use the this keyword to refer to the selected elements within the callback function. As of jQuery 1.8, however, the .ajaxSuccess() method should only be attached to document.

    All ajaxSuccess handlers are invoked, regardless of what Ajax request was completed. If you must differentiate between the requests, you can use the parameters passed to the handler. Each time an ajaxSuccess handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, you can restrict the callback to only handling events dealing with a particular URL:

    -
    $(document).ajaxSuccess(function(event, xhr, settings) {
    +    
    
    +$( document ).on( "ajaxSuccess", function( event, xhr, settings ) {
       if ( settings.url == "ajax/test.html" ) {
    -    $( ".log" ).text( "Triggered ajaxSuccess handler. The ajax response was: " +
    -                      xhr.responseText );
    +    $( ".log" ).text( "Triggered ajaxSuccess handler. The Ajax response was: " +
    +      xhr.responseText );
       }
    -});
    -

    Note: You can get the returned ajax contents by looking at xhr.responseXML or xhr.responseText for xml and html respectively.

    +} ); +
    +

    Note: You can get the returned Ajax contents by looking at xhr.responseXML or xhr.responseText for xml and html respectively.

    - + + Show a message when an Ajax request completes successfully. - + +
    diff --git a/entries/all-selector.xml b/entries/all-selector.xml index 3f549950b..43e45295d 100644 --- a/entries/all-selector.xml +++ b/entries/all-selector.xml @@ -11,48 +11,60 @@ Find every element (including head, body, etc) in the document. Note that if your browser has an extension/add-on enabled that inserts a <script> or <link> element into the DOM, that element will be counted as well. - - + + +]]> Find all elements within document.body so elements like head, script, etc. are excluded. - + + +]]> +]]> diff --git a/entries/andSelf.xml b/entries/andSelf.xml index d85b2e885..967c72ef5 100644 --- a/entries/andSelf.xml +++ b/entries/andSelf.xml @@ -1,64 +1,17 @@ - + .andSelf() 1.2 Add the previous set of elements on the stack to the current set. -

    Note: This function has been deprecated and is now an alias for .addBack(), which should be used with jQuery 1.8 and later.

    -

    As described in the discussion for .end(), jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .andSelf() can help.

    -

    Consider a page with a simple list on it:

    -
    
    -<ul>
    -   <li>list item 1</li>
    -   <li>list item 2</li>
    -   <li class="third-item">list item 3</li>
    -   <li>list item 4</li>
    -   <li>list item 5</li>
    -</ul>
    -
    -

    The result of the following code is a red background behind items 3, 4 and 5:

    -
    $('li.third-item').nextAll().andSelf()
    -  .css('background-color', 'red');
    -
    -

    First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to .nextAll() then pushes the set of items 4 and 5 onto the stack. Finally, the .andSelf() invocation merges these two sets together, creating a jQuery object that points to all three items in document order: {[<li.third-item>,<li>,<li> ]}.

    +
    +

    Note: This API has been removed in jQuery 3.0; use .addBack() instead, which should work identically.

    +
    - - The .andSelf() method causes the previous set of DOM elements in the traversal stack to be added to the current set. In the first example, the top stack contains the set resulting from .find("p"). In the second example, .andSelf() adds the previous set of elements on the stack — in this case $("div.after-andself") — to the current set, selecting both the div and its enclosed paragraphs. - - - - + +
    diff --git a/entries/animate.xml b/entries/animate.xml index e67347ff5..c4ac9e70f 100644 --- a/entries/animate.xml +++ b/entries/animate.xml @@ -22,111 +22,123 @@

    The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a plain object of CSS properties. This object is similar to the one that can be sent to the .css() method, except that the range of properties is more restrictive.

    Animation Properties and Values

    -

    All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

    +

    All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

    In addition to style properties, some non-style properties such as scrollTop and scrollLeft, as well as custom properties, can be animated.

    Shorthand CSS properties (e.g. font, background, border) are not fully supported. For example, if you want to animate the rendered border width, at least a border style and border width other than "auto" must be set in advance. Or, if you want to animate font size, you would use fontSize or the CSS equivalent 'font-size' rather than simply 'font'.

    -

    In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element.

    +

    In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element. In order to use jQuery's built-in toggle state tracking, the 'toggle' keyword must be consistently given as the value of the property being animated.

    Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

    -
    -

    Note: Unlike shorthand animation methods such as .slideDown() and .fadeIn(), the .animate() method does not make hidden elements visible as part of the effect. For example, given $('someElement').hide().animate({height:'20px'}, 500), the animation will run, but the element will remain hidden.

    -
    +
    +

    Note: Unlike shorthand animation methods such as .slideDown() and .fadeIn(), the .animate() method does not make hidden elements visible as part of the effect. For example, given $( "someElement" ).hide().animate({height: "20px"}, 500), the animation will run, but the element will remain hidden.

    +

    Duration

    Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

    -

    Complete Function

    -

    If supplied, the complete callback function is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, the callback is executed once per matched element, not once for the animation as a whole.

    +

    Callback Functions

    +

    If supplied, the start, step, progress, complete, done, fail, and always callbacks are called on a per-element basis; this is set to the DOM element being animated. If no elements are in the set, no callbacks are called. If multiple elements are animated, the callback is executed once per matched element, not once for the animation as a whole. Use the .promise() method to obtain a promise to which you can attach callbacks that fire once for an animated set of any size, including zero elements.

    Basic Usage

    To animate any element, such as a simple image:

    -
    <div id="clickme">
    +    
    
    +<div id="clickme">
       Click here
     </div>
     <img id="book" src="book.png" alt="" width="100" height="123"
    -  style="position: relative; left: 10px;" />
    + style="position: relative; left: 10px;"> +

    To animate the opacity, left offset, and height of the image simultaneously:

    -
    $('#clickme').click(function() {
    -  $('#book').animate({
    +    
    
    +$( "#clickme" ).on( "click", function() {
    +  $( "#book" ).animate({
         opacity: 0.25,
    -    left: '+=50',
    -    height: 'toggle'
    +    left: "+=50",
    +    height: "toggle"
       }, 5000, function() {
         // Animation complete.
       });
     });
    -
    +

    - +

    + +
    Figure 1 - Illustration of the specified animation effect
    +

    Note that the target value of the height property is 'toggle'. Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition: -

    +

    - +

    + +
    Figure 2 - Illustration of the specified animation effect
    +

    The opacity of the image is already at its target value, so this property is not animated by the second click. Since the target value for left is a relative value, the image moves even farther to the right during this second animation.

    Directional properties (top, right, bottom, left) have no discernible effect on elements if their position style property is static, which it is by default.

    -
    -

    Note: The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.

    -
    -
    -

    Note: if attempting to animate an element with a height or width of 0px, where contents of the element are visible due to overflow, jQuery may clip this overflow during animation. By fixing the dimensions of the original element being hidden however, it is possible to ensure that the animation runs smoothly. A clearfix can be used to automatically fix the dimensions of your main element without the need to set this manually.

    -
    +
    +

    Note: The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.

    +
    +
    +

    Note: if attempting to animate an element with a height or width of 0px, where contents of the element are visible due to overflow, jQuery may clip this overflow during animation. By fixing the dimensions of the original element being hidden however, it is possible to ensure that the animation runs smoothly. A clearfix can be used to automatically fix the dimensions of your main element without the need to set this manually.

    +

    Step Function

    -

    The second version of .animate() provides a step option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set to the DOM element being animated. -

    +

    The second version of .animate() provides a step option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set to the DOM element being animated.

    • now: the numeric value of the property being animated at each step
    • fx: a reference to the jQuery.fx prototype object, which contains a number of properties such as elem for the animated element, start and end for the first and last value of the animated property, respectively, and prop for the property being animated.

    Note that the step function is called for each animated property on each animated element. For example, given two list items, the step function fires four times at each step of the animation:

    -
    $('li').animate({
    +    
    
    +$( "li" ).animate({
       opacity: .5,
    -  height: '50%'
    -},
    -{
    -  step: function(now, fx) {
    -    var data = fx.elem.id + ' ' + fx.prop + ': ' + now;
    -    $('body').append('<div>' + data + '</div>');
    +  height: "50%"
    +}, {
    +  step: function( now, fx ) {
    +    var data = fx.elem.id + " " + fx.prop + ": " + now;
    +    $( "body" ).append( "<div>" + data + "</div>" );
       }
    -});
    +}); +

    Easing

    -

    The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

    +

    The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

    Per-property Easing

    As of jQuery version 1.4, you can set per-property easing functions within a single .animate() call. In the first version of .animate(), each property can take an array as its value: The first member of the array is the CSS property and the second member is an easing function. If a per-property easing function is not defined for a particular property, it uses the value of the .animate() method's optional easing argument. If the easing argument is not defined, the default swing function is used.

    For example, to simultaneously animate the width and height with the swing easing function and the opacity with the linear easing function:

    -
    $('#clickme').click(function() {
    -  $('#book').animate({
    -    width: ['toggle', 'swing'],
    -    height: ['toggle', 'swing'],
    -    opacity: 'toggle'
    -  }, 5000, 'linear', function() {
    -      $(this).after('<div>Animation complete.</div>');
    +    
    
    +$( "#clickme" ).on( "click", function() {
    +  $( "#book" ).animate({
    +    width: [ "toggle", "swing" ],
    +    height: [ "toggle", "swing" ],
    +    opacity: "toggle"
    +  }, 5000, "linear", function() {
    +    $( this ).after( "<div>Animation complete.</div>" );
       });
    -});
    +}); +

    In the second version of .animate(), the options object can include the specialEasing property, which is itself an object of CSS properties and their corresponding easing functions. For example, to simultaneously animate the width using the linear easing function and the height using the easeOutBounce easing function:

    -
    $('#clickme').click(function() {
    -  $('#book').animate({
    -    width: 'toggle',
    -    height: 'toggle'
    +    
    
    +$( "#clickme" ).on( "click", function() {
    +  $( "#book" ).animate({
    +    width: "toggle",
    +    height: "toggle"
       }, {
         duration: 5000,
         specialEasing: {
    -      width: 'linear',
    -      height: 'easeOutBounce'
    +      width: "linear",
    +      height: "easeOutBounce"
         },
         complete: function() {
    -      $(this).after('<div>Animation complete.</div>');
    +      $( this ).after( "<div>Animation complete.</div>" );
         }
       });
    -});
    +}); +

    As previously noted, a plugin is required for the easeOutBounce function.

    Click the button to animate the div with a number of different properties. - + Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up. - @@ -177,124 +191,163 @@ div { The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed.
    - +
    Block2
    +]]> Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation. Animate all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. - + Animate all paragraphs to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. - Animate the left and opacity style properties of all paragraphs; run the animation outside the queue, so that it will automatically start without waiting for its turn. - + An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden. - +}, "slow", "easein" ); +]]> Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. - + Use an easing function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. - +}, { + duration: "slow", + easing: "easein" +}); +]]> Animate all paragraphs and execute a callback function when the animation is complete. The first argument is an object of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function. - diff --git a/entries/animated-selector.xml b/entries/animated-selector.xml index 1bc6e082f..9a68868e3 100644 --- a/entries/animated-selector.xml +++ b/entries/animated-selector.xml @@ -13,24 +13,36 @@ Change the color of any div that is animated. - +
    +
    +
    +]]> + div { + background: yellow; + border: 1px solid #AAA; + width: 80px; + height: 80px; + margin: 0 5px; + float: left; + } + div.colored { + background: green; + } +]]>
    diff --git a/entries/append.xml b/entries/append.xml index 5f5aa08be..b45c50eaf 100644 --- a/entries/append.xml +++ b/entries/append.xml @@ -4,42 +4,55 @@ 1.0 - DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + + - One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + 1.4 - - A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - + + A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + + + + + + + + Insert content, specified by the parameter, to the end of each element in the set of matched elements. -

    The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

    -

    The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

    +

    The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

    +

    The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

    Consider the following HTML:

    -
    <h2>Greetings</h2>
    +    
    
    +<h2>Greetings</h2>
     <div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
     </div>
    -
    +

    You can create content and insert it into several elements at once:

    -
    $('.inner').append('<p>Test</p>');
    -
    +
    
    +$( ".inner" ).append( "<p>Test</p>" );
    +    

    Each inner <div> element gets this new content:

    -
    <h2>Greetings</h2>
    +    
    
    +<h2>Greetings</h2>
     <div class="container">
       <div class="inner">
         Hello
    @@ -50,59 +63,76 @@
         <p>Test</p>
       </div>
     </div>
    -
    +

    You can also select an element on the page and insert it into another:

    -
    $('.container').append($('h2'));
    -
    +
    
    +$( ".container" ).append( $( "h2" ) );
    +    

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):

    -
    <div class="container">
    +    
    
    +<div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
       <h2>Greetings</h2>
     </div>
    -
    -

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

    +
    +

    Important: If there is more than one target element, however, cloned copies of the inserted element will be created for each target except for the last one.

    Additional Arguments

    -

    Similar to other content-adding methods such as .prepend() and .before(), .append() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

    +

    Similar to other content-adding methods such as .prepend() and .before(), .append() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

    For example, the following will insert two new <div>s and an existing <div> as the last three child nodes of the body:

    -
    var $newdiv1 = $('<div id="object1"/>'),
    -    newdiv2 = document.createElement('div'),
    -    existingdiv1 = document.getElementById('foo');
    +    
    
    +var $newdiv1 = $( "<div id='object1'></div>" ),
    +  newdiv2 = document.createElement( "div" ),
    +  existingdiv1 = document.getElementById( "foo" );
     
    -$('body').append($newdiv1, [newdiv2, existingdiv1]);
    -
    -

    Since .append() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $('body').append($newdiv1, newdiv2, existingdiv1). The type and number of arguments will largely depend on how you collect the elements in your code.

    +$( "body" ).append( $newdiv1, [ newdiv2, existingdiv1 ] ); +
    +

    Since .append() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $('body').append( $newdiv1, newdiv2, existingdiv1 ). The type and number of arguments will largely depend on how you collect the elements in your code.

    + + Appends some HTML to all paragraphs. - + Appends an Element to all paragraphs. - Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. - + diff --git a/entries/appendTo.xml b/entries/appendTo.xml index 602f72049..7221b2e09 100644 --- a/entries/appendTo.xml +++ b/entries/appendTo.xml @@ -4,28 +4,32 @@ 1.0 - A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + Insert every element in the set of matched elements to the end of the target. -

    The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

    +

    The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

    Consider the following HTML:

    -
    <h2>Greetings</h2>
    +    
    
    +<h2>Greetings</h2>
     <div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
     </div>
    -
    +

    We can create content and insert it into several elements at once:

    -
    $('<p>Test</p>').appendTo('.inner');
    -
    +
    
    +$( "<p>Test</p>" ).appendTo( ".inner" );
    +    

    Each inner <div> element gets this new content:

    -
    <h2>Greetings</h2>
    +    
    
    +<h2>Greetings</h2>
     <div class="container">
       <div class="inner">
         Hello
    @@ -36,28 +40,39 @@
         <p>Test</p>
       </div>
     </div>
    -
    +

    We can also select an element on the page and insert it into another:

    -
    $('h2').appendTo($('.container'));
    -
    -

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):

    -
    <div class="container">
    +    
    
    +$( "h2" ).appendTo( $( ".container" ) );
    +    
    +

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned) and a new set consisting of the inserted element is returned:

    +
    
    +<div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
       <h2>Greetings</h2>
     </div>
    -
    -

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

    +
    +

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last, and that new set (the original element plus clones) is returned.

    +

    Before jQuery 1.9, the append-to-single-element case did not create a new set, but instead returned the original set which made it difficult to use the .end() method reliably when being used with an unknown number of elements.

    + + Append all spans to the element with the ID "foo" (Check append() documentation for more examples) - - + +
    FOO!
    +]]>
    diff --git a/entries/attr.xml b/entries/attr.xml index 5d5f22860..ac3e5a1bb 100644 --- a/entries/attr.xml +++ b/entries/attr.xml @@ -12,32 +12,125 @@ Get the value of an attribute for the first element in the set of matched elements.

    The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

    -

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

    Using jQuery's .attr() method to get the value of an element's attribute has two main benefits:

    1. Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
    2. Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.
    -
    +

    Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

    -
    + +

    As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

    + + +

    Attributes vs. Properties

    +

    The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

    +

    For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

    +

    Concerning boolean attributes, consider a DOM element defined by the HTML markup <input type="checkbox" checked="" />, and assume it is in a JavaScript variable named elem:

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + elem.checked + true (Boolean) Will change with checkbox state
    + $( elem ).prop( "checked" ) + true (Boolean) Will change with checkbox state
    + elem.getAttribute( "checked" ) + "" (String) Initial state of the checkbox; does not change
    + $( elem ).attr( "checked" ) + (4.0+) + "" (String) Initial state of the checkbox; does not change
    + $( elem ).attr( "checked" ) + (1.6-3.x) + "checked" (String) Initial state of the checkbox; does not change
    + $( elem ).attr( "checked" ) + (pre-1.6) + true (Boolean) Changed with checkbox state
    +
    +

    According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false". This is true of all boolean attributes.

    +

    Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:

    +
      +
    • + if ( elem.checked ) +
    • +
    • + if ( $( elem ).prop( "checked" ) ) +
    • +
    • + if ( $( elem ).is( ":checked" ) ) +
    • +
    +

    The same is true for other dynamic attributes, such as selected and value.

    + + + Display the checked attribute and property of a checkbox as it changes. + + + + +
    Find the title attribute of the first <em> in the page. @@ -45,6 +138,7 @@ var title = $("em").attr("title"); + @@ -55,7 +149,9 @@ var title = $("em").attr("title"); - A value to set for the attribute. + + + A value to set for the attribute. If null, the specified attribute will be removed (as in .removeAttr()). Non-ARIA attributes can also be removed by passing false. @@ -69,89 +165,121 @@ var title = $("em").attr("title"); The name of the attribute to set. - + A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + + + + + + Set one or more attributes for the set of matched elements.

    The .attr() method is a convenient way to set the value of attributes—especially when setting multiple attributes or using values returned by a function. Consider the following image:

    -
    <img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />
    +
    <img id="greatphoto" src="brush-seller.jpg" alt="brush seller">

    Setting a simple attribute

    To change the alt attribute, simply pass the name of the attribute and its new value to the .attr() method:

    -
    $('#greatphoto').attr('alt', 'Beijing Brush Seller');
    +
    
    +$( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );
    +      

    Add an attribute the same way:

    -
    $('#greatphoto')
    -.attr('title', 'Photo by Kelly Clark');
    +
    
    +$( "#greatphoto" ).attr( "title", "Photo by Kelly Clark" );
    +      

    Setting several attributes at once

    To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a plain JavaScript object. Each key-value pair in the object adds or modifies an attribute:

    -
    $('#greatphoto').attr({
    -  alt: 'Beijing Brush Seller',
    -  title: 'photo by Kelly Clark'
    -});
    +
    
    +$( "#greatphoto" ).attr({
    +  alt: "Beijing Brush Seller",
    +  title: "photo by Kelly Clark"
    +});
    +      

    When setting multiple attributes, the quotes around attribute names are optional.

    +

    Removing an attribute

    +

    To remove an attribute, either call .attr( name, null ) or use .removeAttr( name ). For non-ARIA attributes, in jQuery 4.0+ you can also call .attr( name, false ).

    +
    +

    Note: Because ARIA attributes frequently associate behavior with "false" values that differs from attribute absence, passing false as the value for an attribute whose name starts with "aria-…" will stringify that value to "false" rather than remove the attribute. To guarantee removal of an attribute, use the .removeAttr() method or provide null as the value to the .attr() setter.

    +

    WARNING: When setting the 'class' attribute, you must always use quotes!

    -

    Note: jQuery prohibits changing the type attribute on an <input> or <button> element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer.

    +
    +

    Note: Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

    +

    Computed attribute values

    By using a function to set attributes, you can compute the value based on other properties of the element. For example, to concatenate a new value with an existing value:

    -
    $('#greatphoto').attr('title', function(i, val) {
    -  return val + ' - photo by Kelly Clark'
    -});
    +
    
    +$( "#greatphoto" ).attr( "title", function( i, val ) {
    +  return val + " - photo by Kelly Clark";
    +});
    +      

    This use of a function to compute attribute values can be particularly useful when modifying the attributes of multiple elements at once.

    -

    Note: If nothing is returned in the setter function (ie. function(index, attr){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

    +

    Note: If nothing is returned in the setter function (ie. function(index, attr){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

    Set some attributes for all <img>s in the page. Set the id for divs based on the position in the page. + div { + color: blue; + } + span { + color: red; + } + b { + font-weight: bolder; + } +]]> Set the src attribute from title attribute on the image. @@ -159,5 +287,6 @@ $("img").attr("src", function() { +
    diff --git a/entries/attribute-contains-prefix-selector.xml b/entries/attribute-contains-prefix-selector.xml index 8b4ffd1ea..3465e6c29 100644 --- a/entries/attribute-contains-prefix-selector.xml +++ b/entries/attribute-contains-prefix-selector.xml @@ -8,7 +8,7 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-). @@ -18,19 +18,19 @@ Finds all links with an hreflang attribute that is english. +Some text +Some other text +will not be outlined +]]> + a { + display: inline-block; + } +]]> - \ No newline at end of file + diff --git a/entries/attribute-contains-selector.xml b/entries/attribute-contains-selector.xml index aad840658..15e7778d4 100644 --- a/entries/attribute-contains-selector.xml +++ b/entries/attribute-contains-selector.xml @@ -8,22 +8,25 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. - Selects elements that have the specified attribute with a value containing the a given substring. + Selects elements that have the specified attribute with a value containing a given substring.

    This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~="word"]), which is more appropriate in many cases.

    Finds all inputs with a name attribute that contains 'man' and sets the value with some text. - - + + - \ No newline at end of file + diff --git a/entries/attribute-contains-word-selector.xml b/entries/attribute-contains-word-selector.xml index 0a177c0f5..8a71f37b0 100644 --- a/entries/attribute-contains-word-selector.xml +++ b/entries/attribute-contains-word-selector.xml @@ -8,7 +8,7 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. Selects elements that have the specified attribute with a value containing a given word, delimited by spaces. @@ -17,13 +17,16 @@ Finds all inputs with a name attribute that contains the word 'man' and sets the value with some text. - - + + - \ No newline at end of file + diff --git a/entries/attribute-ends-with-selector.xml b/entries/attribute-ends-with-selector.xml index 390ef4435..cbdfe8089 100644 --- a/entries/attribute-ends-with-selector.xml +++ b/entries/attribute-ends-with-selector.xml @@ -8,19 +8,22 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive. Finds all inputs with an attribute name that ends with 'letter' and puts text in them. - - + + - \ No newline at end of file + diff --git a/entries/attribute-equals-selector.xml b/entries/attribute-equals-selector.xml index a5ab5ef9f..faa6e513f 100644 --- a/entries/attribute-equals-selector.xml +++ b/entries/attribute-equals-selector.xml @@ -8,33 +8,37 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. Selects elements that have the specified attribute with a value exactly equal to a certain value. Finds all inputs with a value of "Hot Fuzz" and changes the text of the next sibling span. - - + + - \ No newline at end of file + diff --git a/entries/attribute-not-equal-selector.xml b/entries/attribute-not-equal-selector.xml index 96b3b7820..38531ffcf 100644 --- a/entries/attribute-not-equal-selector.xml +++ b/entries/attribute-not-equal-selector.xml @@ -8,35 +8,35 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value. -

    This selector is equivalent to :not([attr="value"]).

    +

    This selector is equivalent to :not([attr='value']).

    - + Finds all inputs that don't have the name 'newsletter' and appends text to the span next to it. - ; not newsletter');]]> - + ; not newsletter" ); +]]> + - \ No newline at end of file + diff --git a/entries/attribute-starts-with-selector.xml b/entries/attribute-starts-with-selector.xml index 5c0a7dec7..540676525 100644 --- a/entries/attribute-starts-with-selector.xml +++ b/entries/attribute-starts-with-selector.xml @@ -8,7 +8,7 @@ An attribute name. - An attribute value. Can be either an unquoted single word or a quoted string. + An attribute value. Can be either a valid identifier or a quoted string. Selects elements that have the specified attribute with a value beginning exactly with a given string. @@ -17,12 +17,15 @@
    Finds all inputs with an attribute name that starts with 'news' and puts text in them. - - + + - \ No newline at end of file + diff --git a/entries/before.xml b/entries/before.xml index 2f1f8bdf0..577f588b0 100644 --- a/entries/before.xml +++ b/entries/before.xml @@ -4,15 +4,18 @@ 1.0 - HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements. + HTML string, DOM element, text node, array of elements and text nodes, or jQuery object to insert before each element in the set of matched elements. + + - One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + @@ -20,69 +23,125 @@ 1.4 - A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + + + + + + + + A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + + + + + 1.10-and-2.0 + + + + + + + + + + A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. Insert content, specified by the parameter, before each element in the set of matched elements. -

    The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .before(), the selector expression preceding the method is the container before which the content is inserted. With .insertBefore(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

    +

    The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .before(), the content to be inserted comes from the method's argument: $(target).before(contentToBeInserted). With .insertBefore(), on the other hand, the content precedes the method and is inserted before the target, which in turn is passed as the .insertBefore() method's argument: $(contentToBeInserted).insertBefore(target).

    Consider the following HTML:

    -
    <div class="container">
    +    
    
    +<div class="container">
       <h2>Greetings</h2>
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
    -</div>
    +</div> +

    You can create content and insert it before several elements at once:

    -
    $('.inner').before('<p>Test</p>');
    +
    
    +$( ".inner" ).before( "<p>Test</p>" );
    +    

    Each inner <div> element gets this new content:

    -
    <div class="container">
    +    
    
    +<div class="container">
       <h2>Greetings</h2>
       <p>Test</p>
       <div class="inner">Hello</div>
       <p>Test</p>
       <div class="inner">Goodbye</div>
    -</div>
    +</div> +

    You can also select an element on the page and insert it before another:

    -
    $('.container').before($('h2'));
    +
    
    +$( ".container" ).before( $( "h2" ) );
    +    

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned):

    -
    <h2>Greetings</h2>
    +    
    
    +<h2>Greetings</h2>
     <div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
    -</div>
    -

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

    -

    In jQuery 1.4, .before() and .after() will also work on disconnected DOM nodes:

    -
    $("<div/>").before("<p></p>");
    -

    The result is a jQuery set that contains a paragraph and a div (in that order).

    +</div> +
    +

    Important: If there is more than one target element, however, cloned copies of the inserted element will be created for each target except for the last one.

    Additional Arguments

    -

    Similar to other content-adding methods such as .prepend() and .after(), .before() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

    +

    Similar to other content-adding methods such as .prepend() and .after(), .before() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.

    For example, the following will insert two new <div>s and an existing <div> before the first paragraph:

    -
    var $newdiv1 = $('<div id="object1"/>'),
    -    newdiv2 = document.createElement('div'),
    -    existingdiv1 = document.getElementById('foo');
    +    
    
    +var newdiv1 = $( "<div id='object1'></div>" ),
    +  newdiv2 = document.createElement( "div" ),
    +  existingdiv1 = document.getElementById( "foo" );
     
    -$('p').first().before($newdiv1, [newdiv2, existingdiv1]);
    -
    -

    Since .before() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $('p').first().before($newdiv1, newdiv2, existingdiv1). The type and number of arguments will largely depend on how you collect the elements in your code.

    +$( "p" ).first().before( newdiv1, [ newdiv2, existingdiv1 ] ); +
    +

    Since .before() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $( "p" ).first().before( $newdiv1, newdiv2, existingdiv1 ). The type and number of arguments will largely depend on how you collect the elements in your code.

    + + Inserts some HTML before all paragraphs. - - - + + + Inserts a DOM element before all paragraphs. - - - + + + Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs. - - - + + + diff --git a/entries/bind.xml b/entries/bind.xml index c209799fd..aa45c4551 100644 --- a/entries/bind.xml +++ b/entries/bind.xml @@ -1,16 +1,17 @@ - + .bind() 1.0 A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + @@ -18,10 +19,10 @@ A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - + An object containing data that will be passed to the event handler. - + Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. @@ -33,188 +34,230 @@
    Attach a handler to an event for the elements. -

    As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

    +

    As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on().

    Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().

    -

    If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind('click.name', handler), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of .unbind() for more information.

    -

    There are shorthand methods for some standard browser events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

    +

    If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind( "click.name", handler ), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of .unbind() for more information.

    +

    Some events have dedicated pages, describing specifics of their usage. For a complete list of those events, see the events category.

    When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

    A basic usage of .bind() is:

    
    -$('#foo').bind('click', function() {
    -  alert('User clicked on "foo."');
    +$( "#foo" ).bind( "click", function() {
    +  alert( "User clicked on 'foo.'" );
     });
    -
    +

    This code will cause the element with an ID of foo to respond to the click event. When a user clicks inside this element thereafter, the alert will be shown.

    Multiple Events

    Multiple event types can be bound at once by including each one separated by a space:

    
    -$('#foo').bind('mouseenter mouseleave', function() {
    -  $(this).toggleClass('entered');
    +$( "#foo" ).bind( "mouseenter mouseleave", function() {
    +  $( this ).toggleClass( "entered" );
     });
    -
    +

    The effect of this on <div id="foo"> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the <div> and remove the class when the mouse leaves.

    As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing an object of event type/handler pairs:

    
    -$('#foo').bind({
    +$( "#foo" ).bind({
       click: function() {
    -    // do something on click
    +    // Do something on click
       },
       mouseenter: function() {
    -    // do something on mouseenter
    +    // Do something on mouseenter
       }
     });
    -
    +

    Event Handlers

    The handler parameter takes a callback function, as shown above. Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function. For example:

    -
    $('#foo').bind('click', function() {
    -  alert($(this).text());
    +    
    
    +$( "#foo" ).bind( "click", function() {
    +  alert( $( this ).text() );
     });
    -
    +

    After this code is executed, when the user clicks inside the element with an ID of foo, its text contents will be shown as an alert.

    As of jQuery 1.4.2 duplicate event handlers can be bound to an element instead of being discarded. This is useful when the event data feature is being used, or when other unique data resides in a closure around the event handler function.

    In jQuery 1.4.3 you can now pass in false in place of an event handler. This will bind an event handler equivalent to: function(){ return false; }. This function can be removed at a later time by calling: .unbind( eventName, false ).

    - The Event object + The Event object

    The handler callback function can also take parameters. When the function is called, the event object will be passed to the first parameter.

    -

    The event object is often unnecessary and the parameter omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. View the full Event Object.

    +

    The event object is often unnecessary and the parameter omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. View the full Event Object.

    Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

    Using the event object in a handler looks like this:

    -
    $(document).ready(function() {
    -  $('#foo').bind('click', function(event) {
    -    alert('The mouse cursor is at ('
    -      + event.pageX + ', ' + event.pageY + ')');
    +    
    
    +$( document ).ready(function() {
    +  $( "#foo" ).bind( "click", function( event ) {
    +    alert( "The mouse cursor is at (" +
    +      event.pageX + ", " + event.pageY +
    +      ")" );
       });
     });
    -
    +

    Note the parameter added to the anonymous function. This code will cause a click on the element with ID foo to report the page coordinates of the mouse cursor at the time of the click.

    Passing Event Data

    The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:

    -
    var message = 'Spoon!';
    -$('#foo').bind('click', function() {
    -  alert(message);
    +    
    
    +var message = "Spoon!";
    +$( "#foo" ).bind( "click", function() {
    +  alert( message );
     });
    -message = 'Not in the face!';
    -$('#bar').bind('click', function() {
    -  alert(message);
    +message = "Not in the face!";
    +$( "#bar" ).bind( "click", function() {
    +  alert( message );
     });
    -
    -

    Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in using eventData: +

    +

    Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in using eventData:

    -
    var message = 'Spoon!';
    -$('#foo').bind('click', {msg: message}, function(event) {
    -  alert(event.data.msg);
    +    
    
    +var message = "Spoon!";
    +$( "#foo" ).bind( "click", {
    +  msg: message
    +}, function( event ) {
    +  alert( event.data.msg );
     });
    -message = 'Not in the face!';
    -$('#bar').bind('click', {msg: message}, function(event) {
    -  alert(event.data.msg);
    +message = "Not in the face!";
    +$( "#bar" ).bind( "click", {
    +  msg: message
    +}, function( event ) {
    +  alert( event.data.msg );
     });
    -
    -

    This time the variable is not referred to directly within the handlers; instead, the variable is passed in by value through eventData, which fixes the value at the time the event is bound. The first handler will now display Spoon! while the second will alert Not in the face! +

    +

    This time the variable is not referred to directly within the handlers; instead, the variable is passed in by value through eventData, which fixes the value at the time the event is bound. The first handler will now display Spoon! while the second will alert Not in the face!

    -
    +

    Note that objects are passed to functions by reference, which further complicates this scenario.

    -
    +

    If eventData is present, it is the second argument to the .bind() method; if no additional data needs to be sent to the handler, then the callback is passed as the second and final argument.

    -
    +

    See the .trigger() method reference for a way to pass data to a handler at the time the event happens rather than when the handler is bound.

    -
    +

    As of jQuery 1.4 we can no longer attach data (and thus, events) to object, embed, or applet elements because critical errors occur when attaching data to Java applets.

    Note: Although demonstrated in the next example, it is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

    Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe. - + To display each paragraph's text in an alert box whenever it is clicked: - + You can pass some extra data before the event handler: - +$( "p" ).bind( "click", { + foo: "bar" +}, handler ); +]]> Cancel a default action and prevent it from bubbling up by returning false: - + Cancel only the default action by using the .preventDefault() method. - + Stop an event from bubbling without preventing the default action by using the .stopPropagation() method. - +}); +]]> Bind custom events. - + +]]> Bind multiple events simultaneously. - +}); +]]> + diff --git a/entries/blur-shorthand.xml b/entries/blur-shorthand.xml new file mode 100644 index 000000000..589a1cebb --- /dev/null +++ b/entries/blur-shorthand.xml @@ -0,0 +1,37 @@ + + + .blur() + Bind an event handler to the "blur" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
    +

    This API is deprecated.

    +

    Instead of .blur( handler ) or .blur( eventData, handler ), use .on( "blur", handler ) or .on( "blur", eventData, handler ), respectively.

    +

    Instead of .blur(), use .trigger( "blur" ).

    +
    +
    + + + + + +
    diff --git a/entries/blur.xml b/entries/blur.xml index a5a8eb6d7..68636a0ce 100644 --- a/entries/blur.xml +++ b/entries/blur.xml @@ -1,57 +1,86 @@ - - .blur() - Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. + + +Bind an event handler to the "blur" event, or trigger that event on an element. + + blur event + Bind an event handler to the "blur" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "blur". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

    This method is a shortcut for .on('blur', handler) in the first two variations, and .trigger('blur') in the third.

    +
    +

    This page describes the blur event. For the deprecated .blur() method, see .blur().

    +

    The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

    For example, consider the HTML:

    -
    <form>
    -  <input id="target" type="text" value="Field 1" />
    -  <input type="text" value="Field 2" />
    +    
    
    +<form>
    +  <input id="target" type="text" value="Field 1">
    +  <input type="text" value="Field 2">
     </form>
     <div id="other">
       Trigger the handler
     </div>
    -The event handler can be bound to the first input field:
    -$('#target').blur(function() {
    -  alert('Handler for .blur() called.');
    -});
    +
    +

    The event handler can be bound to the first input field:

    +
    
    +$( "#target" ).on( "blur", function() {
    +  alert( "Handler for `blur` called." );
    +} );
    +    

    Now if the first field has the focus, clicking elsewhere or tabbing away from it displays the alert:

    - Handler for .blur() called. + Handler for `blur` called.

    -

    To trigger the event programmatically, apply .blur() without an argument:

    -
    $('#other').click(function() {
    -  $('#target').blur();
    -});
    -

    After this code executes, clicks on Trigger the handler will also alert the message.

    -

    The blur event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the blur event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping blur to the focusout event in its event delegation methods, .live() and .delegate().

    +

    To trigger the event programmatically, call .trigger( "blur" ):

    +
    
    +$( "#other" ).on( "click", function() {
    +  $( "#target" ).trigger( "blur" );
    +} );
    +    
    +

    After this code executes, clicks on Trigger the handler will also alert the message.

    +

    The blur event does not bubble. As of version 1.4.2, jQuery works around this limitation by mapping blur to the focusout event in its event delegation methods.

    +

    The native blur event is asynchronous in all versions of IE, contrary to other browsers. To avoid issues related to this discrepancy, as of jQuery 3.7.0, jQuery uses focusout as the native backing event for blur in IE.

    To trigger the blur event on all paragraphs: - + - + + +
    + + + blur event + Trigger the "blur" event on an element. + + 1.0 + + The string "blur". + + + +

    See the description for .on( "blur", ... ).

    +
    + + +
    + +
    diff --git a/entries/button-selector.xml b/entries/button-selector.xml index 1c66a46e4..12c8471cd 100644 --- a/entries/button-selector.xml +++ b/entries/button-selector.xml @@ -7,48 +7,65 @@ Selects all button elements and elements of type button. -

    An equivalent selector to $(":button") using valid CSS is $("button, input[type='button']").

    +

    An equivalent selector to $( ":button" ) using valid CSS is $( "button, input[type='button']" ).

    Find all button inputs and mark them. - +
    +]]>
    -
    \ No newline at end of file + diff --git a/entries/callbacks.add.xml b/entries/callbacks.add.xml index 97188e817..2a94a0c9c 100644 --- a/entries/callbacks.add.xml +++ b/entries/callbacks.add.xml @@ -11,40 +11,41 @@ Add a callback or a collection of callbacks to a callback list. -

    This method returns the Callbacks object onto which it is attached (this).

    -

    Example

    -

    Use callbacks.add() to add new callbacks to a callback list:

    -
    
    -
    -
    + diff --git a/entries/callbacks.disable.xml b/entries/callbacks.disable.xml index e0f9a365f..5ee0eb1b3 100644 --- a/entries/callbacks.disable.xml +++ b/entries/callbacks.disable.xml @@ -6,31 +6,33 @@ Disable a callback list from doing anything more. -

    This method returns the Callbacks object onto which it is attached (this).

    -

    Example

    -

    Use callbacks.disable() to disable further calls to a callback list:

    -
    -
    +]]> + diff --git a/entries/callbacks.disabled.xml b/entries/callbacks.disabled.xml index 6584756df..97f9a7f52 100644 --- a/entries/callbacks.disabled.xml +++ b/entries/callbacks.disabled.xml @@ -8,27 +8,28 @@ Use callbacks.disabled() to determine if the callbacks list has been disabled: - +// Test the disabled state of the list +console.log ( callbacks.disabled() ); +// Outputs: true +]]> diff --git a/entries/callbacks.empty.xml b/entries/callbacks.empty.xml index 332da0dda..4817656e2 100644 --- a/entries/callbacks.empty.xml +++ b/entries/callbacks.empty.xml @@ -6,35 +6,37 @@ Remove all of the callbacks from a list. -

    This method returns the Callbacks object onto which it is attached (this).

    -

    Example

    -

    Use callbacks.empty() to empty a list of callbacks:

    -
    -
    +]]> + diff --git a/entries/callbacks.fire.xml b/entries/callbacks.fire.xml index 7ed045145..daae9b1f2 100644 --- a/entries/callbacks.fire.xml +++ b/entries/callbacks.fire.xml @@ -7,41 +7,42 @@ The argument or list of arguments to pass back to the callback list. - Call all of the callbacks with the given arguments + Call all of the callbacks with the given arguments. -

    This method returns the Callbacks object onto which it is attached (this).

    -

    Example

    -

    Use callbacks.fire() to invoke the callbacks in a list with any arguments that have been passed:

    -
    -
    +]]> + diff --git a/entries/callbacks.fireWith.xml b/entries/callbacks.fireWith.xml index d9585749c..7527e1822 100644 --- a/entries/callbacks.fireWith.xml +++ b/entries/callbacks.fireWith.xml @@ -3,36 +3,37 @@ callbacks.fireWith() 1.7 - + A reference to the context in which the callbacks in the list should be fired. - - An argument, or array of arguments, to pass to the callbacks in the list. + + An array or array-like object of arguments to pass to the callbacks in the list. If omitted or undefined, no arguments will be passed. Call all callbacks in a list with the given context and arguments. -

    This method returns the Callbacks object onto which it is attached (this).

    -

    Example

    -

    Use callbacks.fireWith() to fire a list of callbacks with a specific context and an array of arguments:

    -
    -
    +callbacks.fireWith( window, [ "foo","bar" ] ); +// Outputs: "Received: foo, bar" +]]> + diff --git a/entries/callbacks.fired.xml b/entries/callbacks.fired.xml index 6a2680abc..f16fc87fd 100644 --- a/entries/callbacks.fired.xml +++ b/entries/callbacks.fired.xml @@ -5,27 +5,28 @@ 1.7 Determine if the callbacks have already been called at least once. - -

    Example

    -

    Use callbacks.fired() to determine if the callbacks in a list have been called at least once:

    -
    -
    +]]> + diff --git a/entries/callbacks.has.xml b/entries/callbacks.has.xml index 71637bf5c..401c9d853 100644 --- a/entries/callbacks.has.xml +++ b/entries/callbacks.has.xml @@ -3,31 +3,31 @@ callbacks.has() 1.7 - + The callback to search for. - Determine whether a supplied callback is in a list + Determine whether or not the list has any callbacks attached. If a callback is provided as an argument, determine whether it is in a list. Use callbacks.has() to check if a callback list contains a specific callback: - Use callbacks.lock() to lock a callback list with "memory," and then resume using the list: - - + - diff --git a/entries/callbacks.locked.xml b/entries/callbacks.locked.xml index ea1c2b2a5..601826da8 100644 --- a/entries/callbacks.locked.xml +++ b/entries/callbacks.locked.xml @@ -8,24 +8,25 @@ Use callbacks.locked() to determine the lock-state of a callback list: - diff --git a/entries/callbacks.remove.xml b/entries/callbacks.remove.xml index a6fbb8766..2046fc408 100644 --- a/entries/callbacks.remove.xml +++ b/entries/callbacks.remove.xml @@ -11,31 +11,32 @@ Remove a callback or a collection of callbacks from a callback list. -

    This method returns the Callbacks object onto which it is attached (this).

    +

    This method returns the Callbacks object onto which it is attached (this).

    Use callbacks.remove() to remove callbacks from a callback list: - diff --git a/entries/change-shorthand.xml b/entries/change-shorthand.xml new file mode 100644 index 000000000..98d9509a2 --- /dev/null +++ b/entries/change-shorthand.xml @@ -0,0 +1,36 @@ + + + .change() + Bind an event handler to the "change" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
    +

    This API is deprecated.

    +

    Instead of .change( handler ) or .change( eventData, handler ), use .on( "change", handler ) or .on( "change", eventData, handler ), respectively.

    +

    Instead of .change(), use .trigger( "change" ).

    +
    +
    + + + + +
    diff --git a/entries/change.xml b/entries/change.xml index 37b9d361a..e179c5061 100644 --- a/entries/change.xml +++ b/entries/change.xml @@ -1,31 +1,32 @@ - - .change() - Bind an event handler to the "change" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "change" event, or trigger that event on an element. + + + change event + Bind an event handler to the "change" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "change". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

    This method is a shortcut for .on('change', handler) in the first two variations, and .trigger('change') in the third.

    +
    +

    This page describes the change event. For the deprecated .change() method, see .change().

    +

    The change event is sent to an element when its value changes. This event is limited to <input> elements, <textarea> boxes and <select> elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

    For example, consider the HTML:

    -
    <form>
    -  <input class="target" type="text" value="Field 1" />
    +    
    
    +<form>
    +  <input class="target" type="text" value="Field 1">
       <select class="target">
         <option value="option1" selected="selected">Option 1</option>
         <option value="option2">Option 2</option>
    @@ -33,53 +34,84 @@
     </form>
     <div id="other">
       Trigger the handler
    -</div>
    +</div> +

    The event handler can be bound to the text input and the select box:

    -
    $('.target').change(function() {
    -  alert('Handler for .change() called.');
    -});
    -

    Now when the second option is selected from the dropdown, the alert is displayed. It is also displayed if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered. To trigger the event manually, apply .change() without arguments:

    -
    $('#other').click(function() {
    -  $('.target').change();
    -});
    -

    After this code executes, clicks on Trigger the handler will also alert the message. The message will display twice, because the handler has been bound to the change event on both of the form elements.

    +
    
    +$( ".target" ).on( "change", function() {
    +  alert( "Handler for `change` called." );
    +} );
    +    
    +

    Now when the second option is selected from the dropdown, the alert is displayed. It is also displayed if you change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered. To trigger the event manually, use .trigger( "change" ):

    +
    
    +$( "#other" ).on( "click", function() {
    +  $( ".target" ).trigger( "change" );
    +} );
    +    
    +

    After this code executes, clicks on Trigger the handler will also alert the message. The message will display twice, because the handler has been bound to the change event on both of the form elements.

    As of jQuery 1.4, the change event bubbles in Internet Explorer, behaving consistently with the event in other modern browsers.

    +
    +

    Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.

    +
    Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw. - + div { + color: red; + } +]]> + To add a validity test to all text input elements: - + - +
    + + + change event + Trigger the "change" event on an element. + + 1.0 + + The string "change". + + + +

    See the description for .on( "change", ... ).

    +
    + + +
    + +
    diff --git a/entries/checkbox-selector.xml b/entries/checkbox-selector.xml index 8efc5a130..ba0fd815d 100644 --- a/entries/checkbox-selector.xml +++ b/entries/checkbox-selector.xml @@ -7,47 +7,63 @@ Selects all elements of type checkbox. -

    $(':checkbox') is equivalent to $('[type=checkbox]'). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':checkbox') is equivalent to $('*:checkbox'), so $('input:checkbox') should be used instead.

    +

    $( ":checkbox" ) is equivalent to $( "[type=checkbox]" ). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':checkbox') is equivalent to $( "*:checkbox" ), so $( "input:checkbox" ) should be used instead.

    Finds all checkbox inputs. - + textarea { + height: 25px; + } +]]> + -
    \ No newline at end of file + diff --git a/entries/checked-selector.xml b/entries/checked-selector.xml index 2e1870b6d..5d49ebcd7 100644 --- a/entries/checked-selector.xml +++ b/entries/checked-selector.xml @@ -5,9 +5,10 @@ 1.0 - Matches all elements that are checked. + Matches all elements that are checked or selected. -

    The :checked selector works for checkboxes and radio buttons. For select elements, use the :selected selector.

    +

    The :checked selector works for checkboxes, radio buttons, and options of select elements.

    +

    To retrieve only the selected options of select elements, use the :selected selector.

    Determine how many input elements are checked. @@ -21,8 +22,10 @@ countChecked(); $( "input[type=checkbox]" ).on( "click", countChecked ); ]]>
    + div { + color: red; + } +]]> Identify the checked radio input.
    + + body { + font-size: 14px; + } + ]]> - + +

    + the morning. + Found 0 children in TAG. +

    + +]]> Find all children of each div. - + - + +
    And One Last Time (most text directly in a div)
    +]]>
    Find all children with a class "selected" of each div. - + - + body { + font-size: 16px; + font-weight: bolder; + } + p { + margin: 5px 0; + } +]]> + - \ No newline at end of file + diff --git a/entries/class-selector.xml b/entries/class-selector.xml index 34dca2a96..9db9370bb 100644 --- a/entries/class-selector.xml +++ b/entries/class-selector.xml @@ -14,40 +14,46 @@ Finds the element with the class "myClass". - - + + +]]> Finds the element with both "myclass" and "otherclass" classes. - - + + +]]> - \ No newline at end of file + diff --git a/entries/clearQueue.xml b/entries/clearQueue.xml index 1dc02bd08..19c2f0088 100644 --- a/entries/clearQueue.xml +++ b/entries/clearQueue.xml @@ -14,44 +14,59 @@ Empty the queue. +}); +]]> - +
    +]]>
    - \ No newline at end of file + diff --git a/entries/click-shorthand.xml b/entries/click-shorthand.xml new file mode 100644 index 000000000..374e9f74b --- /dev/null +++ b/entries/click-shorthand.xml @@ -0,0 +1,36 @@ + + + .click() + Bind an event handler to the "click" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
    +

    This API is deprecated.

    +

    Instead of .click( handler ) or .click( eventData, handler ), use .on( "click", handler ) or .on( "click", eventData, handler ), respectively.

    +

    Instead of .click(), use .trigger( "click" ).

    +
    +
    + + + + +
    diff --git a/entries/click.xml b/entries/click.xml index bc7ff79e1..c5f9deb2b 100644 --- a/entries/click.xml +++ b/entries/click.xml @@ -1,51 +1,58 @@ - - .click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element. + + +Bind an event handler to the "click" event, or trigger that event on an element. + + click event + Bind an event handler to the "click" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "click". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

    This method is a shortcut for .on('click', handler) in the first two variations, and .trigger('click') in the third. - The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. +

    +

    This page describes the click event. For the deprecated .click() method, see .click().

    +
    +

    The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. For example, consider the HTML:

    -
    <div id="target">
    +    
    
    +<div id="target">
       Click here
     </div>
     <div id="other">
       Trigger the handler
    -</div>
    -

    +</div> +

    +
    -

    +
    Figure 1 - Illustration of the rendered HTML
    +

    The event handler can be bound to any <div>:

    -
    $("#target").click(function() {
    -  alert("Handler for .click() called.");
    -});
    +
    
    +$( "#target" ).on( "click", function() {
    +  alert( "Handler for `click` called." );
    +} );
    +    

    Now if we click on this element, the alert is displayed:

    - Handler for .click() called. + Handler for `click` called.

    We can also trigger the event when a different element is clicked:

    -
    $("#other").click(function() {
    -  $("#target").click();
    -});
    -

    After this code executes, clicks on Trigger the handler will also alert the message.

    +
    
    +$( "#other" ).on( "click", function() {
    +  $( "#target" ).trigger( "click" );
    +} );
    +    
    +

    After this code executes, clicking on Trigger the handler will also alert the message.

    The click event is only triggered after this exact series of events:

    • The mouse button is depressed while the pointer is inside the element.
    • @@ -56,24 +63,51 @@ Hide paragraphs on a page when they are clicked: - + p { + color: red; + margin: 5px; + cursor: pointer; + } + p:hover { + background: yellow; + } +]]> + - Trigger the click event on all of the paragraphs on the page: - + Trigger the click event on all the paragraphs on the page: + - + + + + + click event + Trigger the "click" event on an element. + + 1.0 + + The string "click". + + + +

      See the description for .on( "click", ... ).

      +
      + +
      + + diff --git a/entries/clone.xml b/entries/clone.xml index 1ce4883de..764b66686 100644 --- a/entries/clone.xml +++ b/entries/clone.xml @@ -18,91 +18,71 @@ Create a deep copy of the set of matched elements. -

      The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes. When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page. Consider the following HTML:

      -
      <div class="container">
      +    

      The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

      +
      +

      Note: For performance reasons, the dynamic state of certain form elements (e.g., user data typed into textarea and user selections made to a select) is not copied to the cloned elements. When cloning input elements, the dynamic state of the element (e.g., user data typed into text inputs and user selections made to a checkbox) is retained in the cloned elements.

      +
      +

      When used in conjunction with one of the insertion methods, .clone() is a convenient way to duplicate elements on a page. Consider the following HTML:

      +
      
      +<div class="container">
         <div class="hello">Hello</div>
         <div class="goodbye">Goodbye</div>
      -</div>
      -

      As shown in the discussion for .append(), normally when an element is inserted somewhere in the DOM, it is moved from its old location. So, given the code:

      -
      $('.hello').appendTo('.goodbye');
      +</div> +
      +

      As shown in the discussion for .append(), normally when an element is inserted somewhere in the DOM, it is moved from its old location. So, given the code:

      +
      
      +$( ".hello" ).appendTo( ".goodbye" );
      +    

      The resulting DOM structure would be:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="goodbye">
           Goodbye
           <div class="hello">Hello</div>
         </div>
      -</div>
      +</div> +

      To prevent this and instead create a copy of the element, you could write the following:

      -
      $('.hello').clone().appendTo('.goodbye');
      +
      
      +$( ".hello" ).clone().appendTo( ".goodbye" );
      +    

      This would produce:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="hello">Hello</div>
         <div class="goodbye">
           Goodbye
           <div class="hello">Hello</div>
         </div>
      -</div>
      -
      +</div> +
      +

      Note: When using the .clone() method, you can modify the cloned elements or their contents before (re-)inserting them into the document.

      - +

      Normally, any event handlers bound to the original element are not copied to the clone. The optional withDataAndEvents parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the .data() method) is also copied to the new copy.

      However, objects and arrays within element data are not copied and will continue to be shared between the cloned element and the original element. To deep copy all data, copy each one manually:

      -
      var $elem = $('#elem').data( "arr": [ 1 ] ), // Original element with attached data
      +    
      
      +// Original element with attached data
      +var $elem = $( "#elem" ).data( "arr", [ 1 ] ),
           $clone = $elem.clone( true )
      -    .data( "arr", $.extend( [], $elem.data("arr") ) ); // Deep copy to prevent data sharing
      -
      + // Deep copy to prevent data sharing + .data( "arr", $.extend( [], $elem.data( "arr" ) ) ); +

      As of jQuery 1.5, withDataAndEvents can be optionally enhanced with deepWithDataAndEvents to copy the events and data for all children of the cloned element.

      -
      +

      Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

      -
      +
      Clones all b elements (and selects the clones) and prepends them to all paragraphs. - - - When using .clone() to clone a collection of elements that are not attached to the DOM, their order when inserted into the DOM is not guaranteed. However, it may be possible to preserve sort order with a workaround, as demonstrated: - - - - \ No newline at end of file + diff --git a/entries/closest.xml b/entries/closest.xml index da43786b6..903ba1a74 100644 --- a/entries/closest.xml +++ b/entries/closest.xml @@ -14,12 +14,12 @@ A string containing a selector expression to match elements against. - A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + A DOM element within which a matching element may be found. 1.6 - + A jQuery object to match elements against. @@ -55,8 +55,8 @@ Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied - The returned jQuery object contains zero or one element for each element in the original set - The returned jQuery object contains zero or more elements for each element in the original set + The returned jQuery object contains zero or one element for each element in the original set, in document order + The returned jQuery object contains zero or more elements for each element in the original set, in reverse document order @@ -64,72 +64,95 @@ <ul id="one" class="level-1"> <li class="item-i">I</li> <li id="ii" class="item-ii">II - <ul class="level-2"> - <li class="item-a">A</li> - <li class="item-b">B - <ul class="level-3"> - <li class="item-1">1</li> - <li class="item-2">2</li> - <li class="item-3">3</li> - </ul> - </li> - <li class="item-c">C</li> - </ul> + <ul class="level-2"> + <li class="item-a">A</li> + <li class="item-b">B + <ul class="level-3"> + <li class="item-1">1</li> + <li class="item-2">2</li> + <li class="item-3">3</li> + </ul> + </li> + <li class="item-c">C</li> + </ul> </li> <li class="item-iii">III</li> </ul> - +

      Suppose we perform a search for <ul> elements starting at item A:

      
      -$('li.item-a').closest('ul')
      -  .css('background-color', 'red');
      -
      +$( "li.item-a" ) + .closest( "ul" ) + .css( "background-color", "red" ); +

      This will change the color of the level-2 <ul>, since it is the first encountered when traveling up the DOM tree.

      Suppose we search for an <li> element instead:

      -
      $('li.item-a').closest('li')
      -  .css('background-color', 'red');
      -
      +
      
      +$( "li.item-a" )
      +  .closest( "li" )
      +  .css( "background-color", "red" );
      +      

      This will change the color of list item A. The .closest() method begins its search with the element itself before progressing up the DOM tree, and stops when item A matches the selector.

      We can pass in a DOM element as the context within which to search for the closest element.

      -
      var listItemII = document.getElementById('ii');
      -$('li.item-a').closest('ul', listItemII)
      -  .css('background-color', 'red');
      -$('li.item-a').closest('#one', listItemII)
      -  .css('background-color', 'green');
      +
      
      +var listItemII = document.getElementById( "ii" );
      +$( "li.item-a" )
      +  .closest( "ul", listItemII )
      +  .css( "background-color", "red" );
      +$( "li.item-a" )
      +  .closest( "#one", listItemII )
      +  .css( "background-color", "green" );
      +      

      This will change the color of the level-2 <ul>, because it is both the first <ul> ancestor of list item A and a descendant of list item II. It will not change the color of the level-1 <ul>, however, because it is not a descendant of list item II.

      Show how event delegation can be done with closest. The closest list element toggles a yellow background when it or its descendent is clicked. - + li { + margin: 3px; + padding: 3px; + background: #EEEEEE; + } + li.highlight { + background: yellow; + } +]]> + Pass a jQuery object to closest. The closest list element toggles a yellow background when it or its descendent is clicked. - + li { + margin: 3px; + padding: 3px; + background: #EEEEEE; + } + li.highlight { + background: yellow; + } +]]> + @@ -143,12 +166,12 @@ $('li.item-a').closest('#one', listItemII) An array or string containing a selector expression to match elements against (can also be a jQuery object). - A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + A DOM element within which a matching element may be found. Get an array of all the elements and selectors matched against the current element up through the DOM tree. -

      This signature (only!) is deprecated as of jQuery 1.7 and removed in jQuery 1.8. It was primarily meant to be used internally or by plugin authors.

      +
      This signature (only!) is deprecated as of jQuery 1.7 and removed in jQuery 1.8. It was primarily meant to be used internally or by plugin authors.
      diff --git a/entries/contains-selector.xml b/entries/contains-selector.xml index 005a05595..c471083f8 100644 --- a/entries/contains-selector.xml +++ b/entries/contains-selector.xml @@ -15,15 +15,16 @@ Finds all divs containing "John" and underlines them. +$( "div:contains('John')" ).css( "text-decoration", "underline" ); +]]> +]]> + - \ No newline at end of file + diff --git a/entries/contents.xml b/entries/contents.xml index fb0bebdca..6cfa73bae 100644 --- a/entries/contents.xml +++ b/entries/contents.xml @@ -6,42 +6,60 @@ Get the children of each element in the set of matched elements, including text and comment nodes. -

      Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search throughthe immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents() and .children() methods are similar, except that the former includes text nodes as well as HTML elements in the resulting jQuery object.

      +

      Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .contents() and .children() methods are similar, except that the former includes text nodes and comment nodes as well as HTML elements in the resulting jQuery object. Please note that most jQuery operations don't support text nodes and comment nodes. The few that do will have an explicit note on their API documentation page.

      The .contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.

      -

      Consider a simple <div> with a number of text nodes, each of which is separated by two line break elements (<br />):

      -
      <div class="container">
      -  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed 
      -  do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
      -  <br /><br />
      -  Ut enim ad minim veniam, quis nostrud exercitation ullamco 
      +    

      As of jQuery 3.2, .contents() returns contents of <template> elements as well.

      +

      Consider a simple <div> with a number of text nodes, each of which is separated by two line break elements (<br>):

      +
      
      +<div class="container">
      +  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
      +  do eiusmod tempor incididunt ut labore et dolore magna aliqua.
      +  <br><br>
      +  Ut enim ad minim veniam, quis nostrud exercitation ullamco
         laboris nisi ut aliquip ex ea commodo consequat.
      -  <br /> <br />
      -  Duis aute irure dolor in reprehenderit in voluptate velit 
      +  <br><br>
      +  Duis aute irure dolor in reprehenderit in voluptate velit
         esse cillum dolore eu fugiat nulla pariatur.
       </div>
      -
      +

      We can employ the .contents() method to help convert this blob of text into three well-formed paragraphs:

      
      -$('.container').contents().filter(function() {
      -  return this.nodeType == 3;
      -})
      -  .wrap('<p></p>')
      -.end()
      -.filter('br')
      -  .remove();
      -
      -

      This code first retrieves the contents of <div class="container"> and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the .nodeType property of the element. This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this time for <br /> elements, and these elements are removed.

      +$( ".container" ) + .contents() + .filter(function() { + return this.nodeType === 3; + }) + .wrap( "<p></p>" ) + .end() + .filter( "br" ) + .remove(); + +

      This code first retrieves the contents of <div class="container"> and then filters it for text nodes, which are wrapped in paragraph tags. This is accomplished by testing the .nodeType property of the element. This DOM property holds a numeric code indicating the node's type; text nodes use the code 3. The contents are again filtered, this time for <br /> elements, and these elements are removed.

      Find all the text nodes inside a paragraph and wrap them with a bold tag. - - + + - Change the background colour of links inside of an iframe. - - + Change the background color of links inside of an iframe. + + - \ No newline at end of file + + diff --git a/entries/context.xml b/entries/context.xml index bbebdb1b6..cd9c3cc41 100644 --- a/entries/context.xml +++ b/entries/context.xml @@ -1,31 +1,29 @@ - + .context 1.3 The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. +
      +

      Note: This API has been removed in jQuery 3.0.

      +

      The .live() method for binding event handlers uses this property to determine the root element to use for its event delegation needs.

      The value of this property is typically equal to document, as this is the default context for jQuery objects if none is supplied. The context may differ if, for example, the object was created by searching within an <iframe> or XML document.

      Note that the context property may only apply to the elements originally selected by jQuery(), as it is possible for the user to add elements to the collection via methods such as .add() and these may have a different context.

      Determine the exact context used. - - - + +
      diff --git a/entries/contextmenu-shorthand.xml b/entries/contextmenu-shorthand.xml new file mode 100644 index 000000000..9b1f48736 --- /dev/null +++ b/entries/contextmenu-shorthand.xml @@ -0,0 +1,36 @@ + + + .contextmenu() + Bind an event handler to the "contextmenu" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
      +

      This API is deprecated.

      +

      Instead of .contextmenu( handler ) or .contextmenu( eventData, handler ), use .on( "contextmenu", handler ) or .on( "contextmenu", eventData, handler ), respectively.

      +

      Instead of .contextmenu(), use .trigger( "contextmenu" ).

      +
      +
      + + + + +
      diff --git a/entries/contextmenu.xml b/entries/contextmenu.xml new file mode 100644 index 000000000..63d9c179c --- /dev/null +++ b/entries/contextmenu.xml @@ -0,0 +1,105 @@ + + +Bind an event handler to the "contextmenu" event, or trigger that event on an element. + + + contextmenu event + Bind an event handler to the "contextmenu" event. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + +
      +

      This page describes the contextmenu event. For the deprecated .contextmenu() method, see .contextmenu().

      +
      +

      The contextmenu event is sent to an element when the right button of the mouse is clicked on it, but before the context menu is displayed. In case the context menu key is pressed, the event is triggered on the html element or the currently focused element. Any HTML element can receive this event. + For example, consider the HTML:

      +
      
      +<div id="target">
      +  Right-click here
      +</div>
      +    
      +

      The event handler can be bound to the <div> as follows:

      +
      
      +$( "#target" ).on( "contextmenu", function() {
      +  alert( "Handler for `contextmenu` called." );
      +} );
      +    
      +

      Now right-clicking on this element displays the alert:

      +

      + Handler for `contextmenu` called. +

      +

      To trigger the event manually, use .trigger( "contextmenu" ):

      +
      
      +$( "#target" ).trigger( "contextmenu" );
      +    
      +
      + + To show a "Hello World!" alert box when the contextmenu event is triggered on a paragraph on the page: + + + + Right click to toggle background color. + + + + + + + +
      + + + contextmenu event + Trigger the "contextmenu" event on an element. + + 1.0 + + The string "contextmenu". + + + +

      See the description for .on( "contextmenu", ... ).

      +
      + + +
      + +
      diff --git a/entries/css.xml b/entries/css.xml index 79f874d4c..85a304e82 100644 --- a/entries/css.xml +++ b/entries/css.xml @@ -1,6 +1,6 @@ - Get the value of a style property for the first element in the set of matched elements or set one or more CSS properties for every matched element. + Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element. .css() @@ -15,70 +15,100 @@ An array of one or more CSS properties. - Get the value of style properties for the first element in the set of matched elements. + Get the computed style properties for the first element in the set of matched elements. -

      The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties. For example, Internet Explorer's DOM implementation refers to the float property as styleFloat, while W3C standards-compliant browsers refer to it as cssFloat. For consistency, you can simply use "float", and jQuery will translate it to the correct value for each browser.

      -

      Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor'). Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

      -

      Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

      -

      As of jQuery 1.9, passing an array of style properties to .css() will result in an object of property-value pairs.

      +

      The .css() method is a convenient way to get a computed style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer prior to version 9) and the different terms browsers use for certain properties. For example, Internet Explorer's DOM implementation refers to the float property as styleFloat, while W3C standards-compliant browsers refer to it as cssFloat. For consistency, you can simply use "float", and jQuery will translate it to the correct value for each browser.

      +

      Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css( "background-color" ) and .css( "backgroundColor" ). This means mixed case has a special meaning, .css( "WiDtH" ) won't do the same as .css( "width" ), for example.

      +

      Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as em, ex, px or % in a style sheet. Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

      +

      Retrieval of shorthand CSS properties (e.g., margin, background, border), although functional with some browsers, is not guaranteed. For example, if you want to retrieve the rendered border-width, use: $( elem ).css( "borderTopWidth" ), $( elem ).css( "borderBottomWidth" ), and so on.

      +

      An element should be connected to the DOM when calling .css() on it. If it isn't, jQuery may throw an error.

      +

      As of jQuery 1.9, passing an array of style properties to .css() will result in an object of property-value pairs. For example, to retrieve all four rendered border-width values, you could use $( elem ).css([ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth" ]).

      +

      As of jQuery 3.2, CSS Custom Properties (also called CSS Variables) are supported: $( "p" ).css( "--custom-property" ). Note that you need to provide the property name as-is, camelCasing it won't work as it does for regular CSS properties.

      Get the background color of a clicked div. + div { + width: 60px; + height: 60px; + margin: 5px; + float: left; + } +]]> +
      +]]>
      Get the width, height, text color, and background color of a clicked div. " ) ); }); - ]]> +
      4
      +]]>
      + +
      @@ -97,8 +127,14 @@ div { height: 50px; margin: 5px; padding: 5px; float: left; } A CSS property name. - + A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + + + + + + @@ -110,60 +146,86 @@ div { height: 50px; margin: 5px; padding: 5px; float: left; } Set one or more CSS properties for the set of matched elements.

      As with the .prop() method, the .css() method makes setting properties of elements quick and easy. This method can take either a property name and value as separate parameters, or a single object of key-value pairs.

      -

      Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css({'background-color': '#ffe', 'border-left': '5px solid #ccc'}) and .css({backgroundColor: '#ffe', borderLeft: '5px solid #ccc'}). Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

      -

      When using .css() as a setter, jQuery modifies the element's style property. For example, $('#mydiv').css('color', 'green') is equivalent to document.getElementById('mydiv').style.color = 'green'. Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background> will remove that style entirely from the element, regardless of what is set in a stylesheet or <style> element.

      +

      Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css({ "background-color": "#ffe", "border-left": "5px solid #ccc" }) and .css({backgroundColor: "#ffe", borderLeft: "5px solid #ccc" }). Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

      +

      In jQuery 3.x or older, when a number is passed as the value, jQuery will convert it to a string and add px to the end of that string. However, there are exceptions. px is not added to keys of jQuery.cssNumber If the property requires units other than px, convert the value to a string and add the appropriate units before calling the method.

      +

      In jQuery 4.0 or newer, when a number is passed as the value, jQuery will only convert it to a string and add px to the end of that string for a limited set of properties - mostly related to width, height, border, margin & padding; the full list:

      +
        +
      • setting the element position: top, right, bottom, left
      • +
      • setting the element dimensions: width, height, min-width, min-height, max-width, max-height
      • +
      • padding-related: padding, padding-top, padding-right, padding-bottom, padding-left
      • +
      • margin-related: margin, margin-top, margin-right, margin-bottom, margin-left
      • +
      • border-related: border, border-width, border-top, border-top-width, border-right, border-right-width, border-bottom, border-bottom-width, border-left, border-left-width
      • +
      +

      When using .css() as a setter, jQuery modifies the element's style property. For example, $( "#mydiv" ).css( "color", "green" ) is equivalent to document.getElementById( "mydiv" ).style.color = "green". Setting the value of a style property to an empty string — e.g. $( "#mydiv" ).css( "color", "" ) — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. As a consequence, the element's style for that property will be restored to whatever value was applied. So, this method can be used to cancel any style modification you have previously performed. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background will remove that style entirely from the element, regardless of what is set in a stylesheet or <style> element.

      +

      Note: .css() doesn't support !important declarations. So, the statement $( "p" ).css( "color", "red !important" ) does not turn the color of all paragraphs in the page to red as of jQuery 3.6.0. Do not depend on that not working, though, as a future version of jQuery may add support for such declarations. It's strongly advised to use classes instead; otherwise use a jQuery plugin.

      +

      As of jQuery 1.8, the .css() setter will automatically take care of prefixing the property name. For example, take .css( "user-select", "none" ) in Chrome/Safari will set it as -webkit-user-select, Firefox will use -moz-user-select, and IE10 will use -ms-user-select.

      As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

      As of jQuery 1.4, .css() allows us to pass a function as the property value:

      -
      $('div.example').css('width', function(index) {
      +      
      
      +$( "div.example" ).css( "width", function( index ) {
         return index * 50;
      -});
      +}); +

      This example sets the widths of the matched elements to incrementally larger values.

      -

      Note: If nothing is returned in the setter function (ie. function(index, style){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

      +

      Note: If nothing is returned in the setter function (ie. function( index, style ){} ), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

      +

      As of jQuery 3.2, CSS Custom Properties (also called CSS Variables) are supported: $( "p" ).css( "--custom-property", "value" ). Note that you need to provide the property name as-is, camelCasing it won't work as it does for regular CSS properties.

      Change the color of any paragraph to red on mouseover event. + p { + color: blue; + width: 200px; + font-size: 14px; + } +]]> +]]> Increase the width of #box by 200 pixels the first time it is clicked. + #box { + background: black; + color: snow; + width: 100px; + padding: 10px; + } +]]> +
      Click me to grow
      +]]>
      Highlight a clicked word in the paragraph. + p { + color: blue; + font-weight: bold; + cursor: pointer; + } +]]> +

      +]]>
      Change the font weight and background color on mouseenter and mouseleave. Increase the size of a div when you click it. + div { + width: 20px; + height: 15px; + background-color: #f33; + } +]]> + +
      diff --git a/entries/data.xml b/entries/data.xml index 21d5fc278..d998d38c7 100644 --- a/entries/data.xml +++ b/entries/data.xml @@ -8,8 +8,8 @@ A string naming the piece of data to set. - - The new data value; it can be any Javascript type including Array or Object. + + The new data value; this can be any Javascript type except undefined. @@ -21,36 +21,44 @@ Store arbitrary data associated with the matched elements.

      The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

      -

      We can set several distinct values for a single element and retrieve them later:

      +

      We can set several distinct values for a single element and retrieve them later:

      
      -$('body').data('foo', 52);
      -$('body').data('bar', { myType: 'test', count: 40 });
      -
      -$('body').data('foo'); // 52
      -$('body').data(); // {foo: 52, bar: { myType: 'test', count: 40 }}
      -
      -

      In jQuery 1.4.3 setting an element's data object with .data(obj) extends the data previously stored with that element. jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

      -

      Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.

      +$( "body" ).data( "foo", 52 ); +$( "body" ).data( "bar", { isManual: true } ); +$( "body" ).data( { baz: [ 1, 2, 3 ] } ); +$( "body" ).data( "foo" ); // 52 +$( "body" ).data(); // { foo: 52, bar: { isManual: true }, baz: [ 1, 2, 3 ] } + +

      Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.

      +

      Prior to jQuery 1.4.3, .data( obj ) completely replaced all data. Since jQuery 1.4.3, data is instead extended by shallow merge.

      +

      Since jQuery 3, every two-character sequence of "-" (U+002D) followed by a lowercase ASCII letter in a key is replaced by the uppercase version of the letter, in alignment with the HTML dataset API. A statement like $( "body" ).data( { "my-name": "aValue" } ).data(); will return { myName: "aValue" }.

      Due to the way browsers interact with plugins and external code, the .data() method cannot be used on <object> (unless it's a Flash plugin), <applet> or <embed> elements.

      + Store then retrieve a value from the div element. - + div { + color: blue; + } + span { + color: red; + } +]]> + @@ -68,82 +76,90 @@ $("span:last").text($("div").data("test").last); 1.4 - Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + Return arbitrary data associated with the first element in the jQuery collection, as set by data() or by an HTML5 data-* attribute. -

      The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:

      +

      The .data() method allows us to read data previously associated with DOM elements. We can retrieve several distinct values for a single element one at a time, or as a set:

      
      -alert($('body').data('foo'));
      -alert($('body').data());
      -
      -

      The above lines alert the data values that were set on the body element. If no data at all was set on that element, undefined is returned.

      -
      
      -alert( $("body").data("foo")); //undefined
      -$("body").data("bar", "foobar");
      -alert( $("body").data("bar")); //foobar
      -
      +var elem = document.createElement( "span" ); +$( elem ).data( "foo" ); // undefined +$( elem ).data(); // {} + +$( elem ).data( "foo", 42 ); +$( elem ).data( "foo" ); // 42 +$( elem ).data(); // { foo: 42 } + +

      Calling .data() with no parameters returns a JavaScript object containing each stored value as a property. The object can be used directly to get data values (but note that property names originally containing dashes will have been modified as described below).

      +

      Since jQuery 3, every two-character sequence of "-" (U+002D) followed by a lowercase ASCII letter in a key is replaced by the uppercase version of the letter, in alignment with the HTML dataset API. A statement like $( "body" ).data( { "my-name": "aValue" } ).data(); will return { myName: "aValue" }.

      - HTML5 data-* Attributes + HTML5 data-* Attributes

      -

      As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

      +

      Since jQuery 1.4.3, data-* attributes are used to initialize jQuery data. An element's data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated (all values are stored internally by jQuery).

      +

      Every attempt is made to convert the attribute's string value to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A string is only converted to a number if doing so doesn't change its representation (for example, the string "100" is converted to the number 100, but "1E02" and "100.000" are left as strings because their numeric value of 100 serializes to "100"). When a string starts with '{' or '[', then jQuery.parseJSON is used to parse it; it must follow valid JSON syntax including quoted property names. A string not parseable as a JavaScript value is not converted.

      +

      To retrieve a data-* attribute value as an unconverted string, use the attr() method.

      +

      Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API.

      For example, given the following HTML:

      <div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>
      -

      All of the following jQuery code will work.

      -
      $("div").data("role") === "page";
      -$("div").data("lastValue") === 43;
      -$("div").data("hidden") === true;
      -$("div").data("options").name === "John";
      -

      Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

      -

      Calling .data() with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with .data(obj). Using the object directly to get or set values is faster than making individual calls to .data() to get or set each value:

      +

      The following comparisons are all true:

      
      -var mydata = $("#mydiv").data();
      -if ( mydata.count < 9 ) {
      -    mydata.count = 43;
      -    mydata.status = "embiggened";
      -}
      -
      +$( "div" ).data( "role" ) === "page"; +$( "div" ).data( "lastValue" ) === 43; +$( "div" ).data( "hidden" ) === true; +$( "div" ).data( "options" ).name === "John"; +
      Get the data named "blah" stored at for an element. - + div { + margin: 5px; + background: yellow; + } + button { + margin: 5px; + font-size: 14px; + } + p { + margin: 5px; + color: blue; + } + span { + color: red; + } +]]> + diff --git a/entries/dblclick-shorthand.xml b/entries/dblclick-shorthand.xml new file mode 100644 index 000000000..ad4c1887b --- /dev/null +++ b/entries/dblclick-shorthand.xml @@ -0,0 +1,36 @@ + + + .dblclick() + Bind an event handler to the "dblclick" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
      +

      This API is deprecated.

      +

      Instead of .dblclick( handler ) or .dblclick( eventData, handler ), use .on( "dblclick", handler ) or .on( "dblclick", eventData, handler ), respectively.

      +

      Instead of .dblclick(), use .trigger( "dblclick" ).

      +
      +
      + + + + +
      diff --git a/entries/dblclick.xml b/entries/dblclick.xml index c0c05a1a1..9c4cf59a0 100644 --- a/entries/dblclick.xml +++ b/entries/dblclick.xml @@ -1,51 +1,58 @@ - - .dblclick() - Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. + + +Bind an event handler to the "dblclick" event, or trigger that event on an element. + + dblclick event + Bind an event handler to the "dblclick" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "dblclick". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

      This method is a shortcut for .on('dblclick', handler) in the first two variations, and .trigger('dblclick') in the third. - The dblclick event is sent to an element when the element is double-clicked. Any HTML element can receive this event. +

      +

      This page describes the dblclick event. For the deprecated .dblclick() method, see .dblclick().

      +
      +

      The dblclick event is sent to an element when the element is double-clicked. Any HTML element can receive this event. For example, consider the HTML:

      -
      <div id="target">
      +    
      
      +<div id="target">
         Double-click here
       </div>
       <div id="other">
         Trigger the handler
      -</div>
      -

      +</div> +

      +
      -

      +
      Figure 1 - Illustration of the rendered HTML
      +

      The event handler can be bound to any <div>:

      -
      $('#target').dblclick(function() {
      -  alert('Handler for .dblclick() called.');
      -});
      +
      
      +$( "#target" ).on( "dblclick", function() {
      +  alert( "Handler for `dblclick` called." );
      +} );
      +    

      Now double-clicking on this element displays the alert:

      - Handler for .dblclick() called. + Handler for `dblclick` called.

      -

      To trigger the event manually, apply .dblclick() without an argument:

      -
      $('#other').click(function() {
      -  $('#target').dblclick();
      -});
      -

      After this code executes, (single) clicks on Trigger the handler will also alert the message.

      +

      To trigger the event manually, call .trigger( "dblclick" ):

      +
      
      +$( "#other" ).on( "click", function() {
      +  $( "#target" ).trigger( "dblclick" );
      +} );
      +    
      +

      After this code executes, (single) clicks on Trigger the handler will also alert the message.

      The dblclick event is only triggered after this exact series of events:

      • The mouse button is depressed while the pointer is inside the element.
      • @@ -57,28 +64,57 @@

        - To bind a "Hello World!" alert box the dblclick event on every paragraph on the page: - + To bind a "Hello World!" alert box to the dblclick event on every paragraph on the page: + Double click to toggle background color. - + div.dbl { + background: yellow; + color: black; + } +]]> + - + + + + + dblclick event + Trigger the "dblclick" event on an element. + + 1.0 + + The string "dblclick". + + + +

        See the description for .on( "dblclick", ... ).

        +
        + +
        + + diff --git a/entries/deferred.always.xml b/entries/deferred.always.xml index a7269094c..30e921936 100644 --- a/entries/deferred.always.xml +++ b/entries/deferred.always.xml @@ -17,15 +17,16 @@ Add handlers to be called when the Deferred object is either resolved or rejected.

        The argument can be either a single function or an array of functions. When the Deferred is resolved or rejected, the alwaysCallbacks are called. Since deferred.always() returns the Deferred object, other methods of the Deferred object can be chained to this one, including additional .always() methods. When the Deferred is resolved or rejected, callbacks are executed in the order they were added, using the arguments provided to the resolve, reject, resolveWith or rejectWith method calls. For more information, see the documentation for Deferred object.

        +

        Note: The deferred.always() method receives the arguments that were used to .resolve() or .reject() the Deferred object, which are often very different. For this reason, it's best to use it only for actions that do not require inspecting the arguments. In all other cases, use explicit .done() or .fail() handlers since the arguments will have well-known orders.

        - Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method. + Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method. - \ No newline at end of file + diff --git a/entries/deferred.catch.xml b/entries/deferred.catch.xml new file mode 100644 index 000000000..e6e3d95aa --- /dev/null +++ b/entries/deferred.catch.xml @@ -0,0 +1,31 @@ + + + deferred.catch() + + 3.0 + + + A function that is called when the Deferred is rejected. + + + + Add handlers to be called when the Deferred object is rejected. + + +

        deferred.catch( fn ) is an alias to deferred.then( null, fn ). Read its page for more information.

        +
        + + Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can add rejection handlers using the .catch method. + + + + +
        diff --git a/entries/deferred.done.xml b/entries/deferred.done.xml index 9592c8ba5..be4787a08 100644 --- a/entries/deferred.done.xml +++ b/entries/deferred.done.xml @@ -19,47 +19,47 @@

        The deferred.done() method accepts one or more arguments, all of which can be either a single function or an array of functions. When the Deferred is resolved, the doneCallbacks are called. Callbacks are executed in the order they were added. Since deferred.done() returns the deferred object, other methods of the deferred object can be chained to this one, including additional .done() methods. When the Deferred is resolved, doneCallbacks are executed using the arguments provided to the resolve or resolveWith method call in the order they were added. For more information, see the documentation for Deferred object.

        - Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. + Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. Resolve a Deferred object when the user clicks a button, triggering a number of callback functions: diff --git a/entries/deferred.fail.xml b/entries/deferred.fail.xml index 61d30d597..6af2ec2b9 100644 --- a/entries/deferred.fail.xml +++ b/entries/deferred.fail.xml @@ -16,16 +16,20 @@ Add handlers to be called when the Deferred object is rejected. -

        The deferred.fail() method accepts one or more arguments, all of which can be either a single function or an array of functions. When the Deferred is rejected, the failCallbacks are called. Callbacks are executed in the order they were added. Since deferred.fail() returns the deferred object, other methods of the deferred object can be chained to this one, including additional deferred.fail() methods. The failCallbacks are executed using the arguments provided to the deferred.reject() or deferred.rejectWith() method call in the order they were added. For more information, see the documentation for Deferred object.

        +

        The deferred.fail() method accepts one or more arguments, all of which can be either a single function or an array of functions. When the Deferred is rejected, the failCallbacks are called. Callbacks are executed in the order they were added. Since deferred.fail() returns the deferred object, other methods of the deferred object can be chained to this one, including additional deferred.fail() methods. The failCallbacks are executed using the arguments provided to the deferred.reject() or deferred.rejectWith() method call in the order they were added. For more information, see the documentation for Deferred object.

        - Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods. + Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods. - \ No newline at end of file + diff --git a/entries/deferred.isRejected.xml b/entries/deferred.isRejected.xml index 45f956d3b..a391f7795 100644 --- a/entries/deferred.isRejected.xml +++ b/entries/deferred.isRejected.xml @@ -6,10 +6,14 @@ Determine whether a Deferred object has been rejected. -

        As of jQuery 1.7 this API has been deprecated; please use deferred.state() instead.

        -

        Returns true if the Deferred object is in the rejected state, meaning that either deferred.reject() or deferred.rejectWith() has been called for the object and the failCallbacks have been called (or are in the process of being called).

        -

        Note that a Deferred object can be in one of three states: pending, resolved, or rejected; use deferred.isResolved() to determine whether the Deferred object is in the resolved state. These methods are primarily useful for debugging, for example to determine whether a Deferred has already been resolved even though you are inside code that intended to reject it.

        +
        +

        Note: This API has been removed in jQuery 1.8; please use deferred.state() instead.

        +
        +

        Returns true if the Deferred object is in the rejected state, meaning that either deferred.reject() or deferred.rejectWith() has been called for the object and the failCallbacks have been called (or are in the process of being called).

        +

        Note that a Deferred object can be in one of three states: pending, resolved, or rejected; use deferred.isResolved() to determine whether the Deferred object is in the resolved state. These methods are primarily useful for debugging, for example to determine whether a Deferred has already been resolved even though you are inside code that intended to reject it.

        + + diff --git a/entries/deferred.isResolved.xml b/entries/deferred.isResolved.xml index fa58afe2b..9c046e5ae 100644 --- a/entries/deferred.isResolved.xml +++ b/entries/deferred.isResolved.xml @@ -6,10 +6,14 @@ Determine whether a Deferred object has been resolved. -

        This API is deprecated as of jQuery 1.7 and removed as of jQuery 1.8; please use deferred.state() instead.

        -

        Returns true if the Deferred object is in the resolved state, meaning that either deferred.resolve() or deferred.resolveWith() has been called for the object and the doneCallbacks have been called (or are in the process of being called).

        -

        Note that a Deferred object can be in one of three states: pending, resolved, or rejected; use deferred.isRejected() to determine whether the Deferred object is in the rejected state. These methods are primarily useful for debugging, for example to determine whether a Deferred has already been resolved even though you are inside code that intended to reject it.

        +
        +

        Note: This API has been removed in jQuery 1.8; please use deferred.state() instead.

        +
        +

        Returns true if the Deferred object is in the resolved state, meaning that either deferred.resolve() or deferred.resolveWith() has been called for the object and the doneCallbacks have been called (or are in the process of being called).

        +

        Note that a Deferred object can be in one of three states: pending, resolved, or rejected; use deferred.isRejected() to determine whether the Deferred object is in the rejected state. These methods are primarily useful for debugging, for example to determine whether a Deferred has already been resolved even though you are inside code that intended to reject it.

        + + diff --git a/entries/deferred.notify.xml b/entries/deferred.notify.xml index cbaf291cb..1af2435d1 100644 --- a/entries/deferred.notify.xml +++ b/entries/deferred.notify.xml @@ -12,7 +12,7 @@ Call the progressCallbacks on a Deferred object with the given args.

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state or reporting status by returning a restricted Promise object through deferred.promise().

        -

        When deferred.notify is called, any progressCallbacks added by deferred.then or deferred.progress are called. Callbacks are executed in the order they were added. Each callback is passed the args from the .notify(). Any calls to .notify() after a Deferred is resolved or rejected (or any progressCallbacks added after that) are ignored. For more information, see the documentation for Deferred object.

        +

        When deferred.notify is called, any progressCallbacks added by deferred.then or deferred.progress are called. Callbacks are executed in the order they were added. Each callback is passed the args from the .notify(). Any calls to .notify() after a Deferred is resolved or rejected (or any progressCallbacks added after that) are ignored. For more information, see the documentation for Deferred object.

        diff --git a/entries/deferred.notifyWith.xml b/entries/deferred.notifyWith.xml index 84799f4bf..add312b8a 100644 --- a/entries/deferred.notifyWith.xml +++ b/entries/deferred.notifyWith.xml @@ -8,16 +8,16 @@ Context passed to the progressCallbacks as the this object. - + - Optional arguments that are passed to the progressCallbacks. + An optional array of arguments that are passed to the progressCallbacks. Call the progressCallbacks on a Deferred object with the given context and args.

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state or reporting status by returning a restricted Promise object through deferred.promise().

        -

        When deferred.notifyWith is called, any progressCallbacks added by deferred.then or deferred.progress are called. Callbacks are executed in the order they were added. Each callback is passed the args from the .notifyWith(). Any calls to .notifyWith() after a Deferred is resolved or rejected (or any progressCallbacks added after that) are ignored. For more information, see the documentation for Deferred object.

        +

        When deferred.notifyWith is called, any progressCallbacks added by deferred.then or deferred.progress are called. Callbacks are executed in the order they were added. Each callback is passed the args from the .notifyWith(). Any calls to .notifyWith() after a Deferred is resolved or rejected (or any progressCallbacks added after that) are ignored. For more information, see the documentation for Deferred object.

        diff --git a/entries/deferred.pipe.xml b/entries/deferred.pipe.xml index 32857ec63..a74f9dac6 100644 --- a/entries/deferred.pipe.xml +++ b/entries/deferred.pipe.xml @@ -34,16 +34,18 @@ Utility method to filter and/or chain Deferreds. -

        Deprecation Notice:As of jQuery 1.8, the deferred.pipe() method is deprecated. The deferred.then() method, which replaces it, should be used instead.

        +
        +

        Deprecation Notice:As of jQuery 1.8, the deferred.pipe() method is deprecated. The deferred.then() method, which replaces it, should be used instead.

        +

        The deferred.pipe() method returns a new promise that filters the status and values of a deferred through a function. The doneFilter and failFilter functions filter the original deferred's resolved / rejected status and values. As of jQuery 1.7, the method also accepts a progressFilter function to filter any calls to the original deferred's notify or notifyWith methods. These filter functions can return a new value to be passed along to the piped promise's done() or fail() callbacks, or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the piped promise's callbacks. If the filter function used is null, or not specified, the piped promise will be resolved or rejected with the same values as the original.

        Filter resolve value: + diff --git a/entries/deferred.progress.xml b/entries/deferred.progress.xml index ce956eefa..87189af93 100644 --- a/entries/deferred.progress.xml +++ b/entries/deferred.progress.xml @@ -3,15 +3,24 @@ deferred.progress() 1.7 - + + + - A function, or array of functions, that is called when the Deferred generates progress notifications. + A function, or array of functions, to be called when the Deferred generates progress notifications. + + + + + + + Optional additional functions, or arrays of functions, to be called when the Deferred generates progress notifications. Add handlers to be called when the Deferred object generates progress notifications. -

        The argument can be either a single function or an array of functions. When the Deferred generates progress notifications by calling notify or notifyWith, the progressCallbacks are called. Since deferred.progress() returns the Deferred object, other methods of the Deferred object can be chained to this one. When the Deferred is resolved or rejected, progress callbacks will no longer be called, with the exception that any progressCallbacks added after the Deferred enters the resolved or rejected state are executed immediately when they are added, using the arguments that were passed to the .notify() or notifyWith() call. For more information, see the documentation jQuery.Deferred().

        +

        The deferred.progress() method accepts one or more arguments, all of which can be either a single function or an array of functions. When the Deferred generates progress notifications by calling notify or notifyWith, the progressCallbacks are called. Since deferred.progress() returns the Deferred object, other methods of the Deferred object can be chained to this one. When the Deferred is resolved or rejected, progress callbacks will no longer be called, with the exception that any progressCallbacks added after the Deferred enters the resolved or rejected state are executed immediately when they are added, using the arguments that were passed to the .notify() or notifyWith() call. For more information, see the documentation for jQuery.Deferred().

        diff --git a/entries/deferred.promise.xml b/entries/deferred.promise.xml index bb49dd239..db6550bd9 100644 --- a/entries/deferred.promise.xml +++ b/entries/deferred.promise.xml @@ -9,7 +9,7 @@ Return a Deferred's Promise object. -

        The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, and state), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).

        +

        The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).

        If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

        If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.

        For more information, see the documentation for Deferred object.

        @@ -17,42 +17,42 @@ Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. @@ -61,12 +61,12 @@ $.when( asyncEvent() ).then( - \ No newline at end of file + diff --git a/entries/deferred.reject.xml b/entries/deferred.reject.xml index 0c458dc50..25e27e625 100644 --- a/entries/deferred.reject.xml +++ b/entries/deferred.reject.xml @@ -3,7 +3,7 @@ deferred.reject() 1.5 - + Optional arguments that are passed to the failCallbacks. @@ -11,8 +11,8 @@ Reject a Deferred object and call any failCallbacks with the given args. -

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        -

        When the Deferred is rejected, any failCallbacks added by deferred.then or deferred.fail are called. Callbacks are executed in the order they were added. Each callback is passed the args from the deferred.reject() call. Any failCallbacks added after the Deferred enters the rejected state are executed immediately when they are added, using the arguments that were passed to the .reject() call. For more information, see the documentation for Deferred object.

        +

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        +

        When the Deferred is rejected, any failCallbacks added by deferred.then() or deferred.fail() are called. Callbacks are executed in the order they were added. Each callback is passed the args from the deferred.reject() call. Any failCallbacks added after the Deferred enters the rejected state are executed immediately when they are added, using the arguments that were passed to the deferred.reject() call. For more information, see the documentation for jQuery.Deferred().

        diff --git a/entries/deferred.rejectWith.xml b/entries/deferred.rejectWith.xml index 0b94ccacc..31e272d6e 100644 --- a/entries/deferred.rejectWith.xml +++ b/entries/deferred.rejectWith.xml @@ -16,7 +16,7 @@ Reject a Deferred object and call any failCallbacks with the given context and args. -

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        +

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        When the Deferred is rejected, any failCallbacks added by deferred.then or deferred.fail are called. Callbacks are executed in the order they were added. Each callback is passed the args from the deferred.reject() call. Any failCallbacks added after the Deferred enters the rejected state are executed immediately when they are added, using the arguments that were passed to the .reject() call. For more information, see the documentation for Deferred object.

        diff --git a/entries/deferred.resolve.xml b/entries/deferred.resolve.xml index edeb418c1..3aea35994 100644 --- a/entries/deferred.resolve.xml +++ b/entries/deferred.resolve.xml @@ -3,7 +3,7 @@ deferred.resolve() 1.5 - + Optional arguments that are passed to the doneCallbacks. @@ -11,7 +11,8 @@ Resolve a Deferred object and call any doneCallbacks with the given args. -

        When the Deferred is resolved, any doneCallbacks added by deferred.then or deferred.done are called. Callbacks are executed in the order they were added. Each callback is passed the args from the .resolve(). Any doneCallbacks added after the Deferred enters the resolved state are executed immediately when they are added, using the arguments that were passed to the .resolve() call. For more information, see the documentation for Deferred object.

        +

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        +

        When the Deferred is resolved, any doneCallbacks added by deferred.then() or deferred.done() are called. Callbacks are executed in the order they were added. Each callback is passed the args from the deferred.resolve(). Any doneCallbacks added after the Deferred enters the resolved state are executed immediately when they are added, using the arguments that were passed to the deferred.resolve() call. For more information, see the documentation for jQuery.Deferred().

        diff --git a/entries/deferred.resolveWith.xml b/entries/deferred.resolveWith.xml index da3e456d4..a6daf6ca2 100644 --- a/entries/deferred.resolveWith.xml +++ b/entries/deferred.resolveWith.xml @@ -16,7 +16,7 @@ Resolve a Deferred object and call any doneCallbacks with the given context and args. -

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        +

        Normally, only the creator of a Deferred should call this method; you can prevent other code from changing the Deferred's state by returning a restricted Promise object through deferred.promise().

        When the Deferred is resolved, any doneCallbacks added by deferred.then or deferred.done are called. Callbacks are executed in the order they were added. Each callback is passed the args from the .resolve(). Any doneCallbacks added after the Deferred enters the resolved state are executed immediately when they are added, using the arguments that were passed to the .resolve() call. For more information, see the documentation for Deferred object.

        diff --git a/entries/deferred.state.xml b/entries/deferred.state.xml index 8a2350f6f..be9cde062 100644 --- a/entries/deferred.state.xml +++ b/entries/deferred.state.xml @@ -9,11 +9,11 @@

        The deferred.state() method returns a string representing the current state of the Deferred object. The Deferred object can be in one of three states:

        • "pending": The Deferred object is not yet in a completed state (neither "rejected" nor "resolved").
        • -
        • "resolved": The Deferred object is in the resolved state, meaning that either deferred.resolve() or deferred.resolveWith() has been called for the object and the doneCallbacks have been called (or are in the process of being called).
        • -
        • "rejected": The Deferred object is in the rejected state, meaning that either deferred.reject() or deferred.rejectWith() has been called for the object and the failCallbacks have been called (or are in the process of being called).
        • +
        • "resolved": The Deferred object is in the resolved state, meaning that either deferred.resolve() or deferred.resolveWith() has been called for the object and the doneCallbacks have been called (or are in the process of being called).
        • +
        • "rejected": The Deferred object is in the rejected state, meaning that either deferred.reject() or deferred.rejectWith() has been called for the object and the failCallbacks have been called (or are in the process of being called).

        This method is primarily useful for debugging to determine, for example, whether a Deferred has already been resolved even though you are inside code that intended to reject it.

        - \ No newline at end of file + diff --git a/entries/deferred.then.xml b/entries/deferred.then.xml index 08a08d898..ec8b2b051 100644 --- a/entries/deferred.then.xml +++ b/entries/deferred.then.xml @@ -67,11 +67,14 @@

        - Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. + Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. @@ -83,11 +86,10 @@ $.get("test.php").then( ]]> - Filter reject value: diff --git a/entries/delay.xml b/entries/delay.xml index 7562a0bdf..b2066217d 100644 --- a/entries/delay.xml +++ b/entries/delay.xml @@ -15,31 +15,46 @@

        Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

        Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

        Using the standard effects queue, we can, for example, set an 800-millisecond delay between the .slideUp() and .fadeIn() of <div id="foo">:

        -
        $('#foo').slideUp(300).delay(800).fadeIn(400);
        +
        
        +$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );
        +    

        When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.

        -
        +

        - The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases. + The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

        -
        + Animate the hiding and showing of two divs, delaying the first before showing it. +$( "button" ).on( "click", function() { + $( "div.first" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 ); + $( "div.second" ).slideUp( 300 ).fadeIn( 400 ); +}); +]]> +
        +]]>
        - \ No newline at end of file + diff --git a/entries/delegate.xml b/entries/delegate.xml index ee144ca9d..c0c0dac72 100644 --- a/entries/delegate.xml +++ b/entries/delegate.xml @@ -1,5 +1,5 @@ - + .delegate() Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. @@ -10,8 +10,9 @@ A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names. - + A function to execute at the time the event is triggered. + @@ -22,11 +23,12 @@ A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names. - + An object containing data that will be passed to the event handler. - + A function to execute at the time the event is triggered. + @@ -39,82 +41,112 @@
        -

        As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method. In general, these are the equivalent templates for the two methods:

        +

        As of jQuery 3.0, .delegate() has been deprecated. It was superseded by the .on() method since jQuery 1.7, so its use was already discouraged. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method. In general, these are the equivalent templates for the two methods:

        
         // jQuery 1.4.3+
        -$(elements).delegate( selector, events, data, handler );
        +$( elements ).delegate( selector, events, data, handler );
         // jQuery 1.7+
        -$(elements).on( events, selector, data, handler );
        - 
        +$( elements ).on( events, selector, data, handler ); +

        For example, the following .delegate() code:

        -
        $("table").delegate("td", "click", function() {
        -  $(this).toggleClass("chosen");
        -});
        +
        
        +$( "table" ).delegate( "td", "click", function() {
        +  $( this ).toggleClass( "chosen" );
        +});
        +    

        is equivalent to the following code written using .on():

        -
        $("table").on("click", "td", function() {
        -  $(this).toggleClass("chosen");
        -});
        -

        To remove events attached with delegate(), see the .undelegate() method.

        +
        
        +$( "table" ).on( "click", "td", function() {
        +  $( this ).toggleClass( "chosen" );
        +});
        +    
        +

        To remove events attached with delegate(), see the .undelegate() method.

        Passing and handling event data works the same way as it does for .on().

        Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones. - + + +]]> To display each paragraph's text in an alert box whenever it is clicked: - + To cancel a default action and prevent it from bubbling up, return false: - + To cancel only the default action by using the preventDefault method. - +}); +]]> Can bind custom events too. - + p { + color: red; + } + span { + color: blue; + } +]]> + + diff --git a/entries/dequeue.xml b/entries/dequeue.xml index d0d74e49a..c54401c78 100644 --- a/entries/dequeue.xml +++ b/entries/dequeue.xml @@ -14,27 +14,37 @@ Use dequeue to end a custom queue function which allows the queue to keep going. - + - \ No newline at end of file + diff --git a/entries/descendant-selector.xml b/entries/descendant-selector.xml index 3d3d62926..5792b612a 100644 --- a/entries/descendant-selector.xml +++ b/entries/descendant-selector.xml @@ -16,29 +16,41 @@

        A descendant of an element could be a child, grandchild, great-grandchild, and so on, of that element.

        - Finds all input descendants of forms. - + Mark all inputs that are descendants of a form with a dotted blue border. Give a yellow background to inputs that are descendants of a fieldset that is a descendant of a form. + + - +
        + + +
        + +Sibling to form: +]]>
        - \ No newline at end of file + diff --git a/entries/detach.xml b/entries/detach.xml index 301ad74d5..bc6b32c77 100644 --- a/entries/detach.xml +++ b/entries/detach.xml @@ -9,29 +9,40 @@ Remove the set of matched elements from the DOM. -

        The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

        +

        The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

        Detach all paragraphs from the DOM - - +$( "p" ).on( "click", function() { + $( this ).toggleClass( "off" ); +}); +var p; +$( "button" ).on( "click", function() { + if ( p ) { + p.appendTo( "body" ); + p = null; + } else { + p = $( "p" ).detach(); + } +}); +]]> + + - \ No newline at end of file + diff --git a/entries/die.xml b/entries/die.xml index f0f6e6d59..efe2e6145 100644 --- a/entries/die.xml +++ b/entries/die.xml @@ -21,33 +21,45 @@ +
        +

        Note: This API has been removed in jQuery 1.9; please use on() instead.

        +

        Any handler that has been attached with .live() can be removed with .die(). This method is analogous to calling .off() with no arguments, which is used to remove all handlers attached with .on(). See the discussions of .live() and .off() for further details.

        If used without an argument, .die() removes all event handlers previously attached using .live() from the elements.

        -

        As of jQuery 1.7, use of .die() (and its complementary method, .live()) is not recommended. Instead, use .off() to remove event handlers bound with .on()

        +

        As of jQuery 1.7, use of .die() (and its complementary method, .live()) is not recommended. Instead, use .off() to remove event handlers bound with .on()

        Note: In order for .die() to function correctly, the selector used with it must match exactly the selector initially used with .live().

        To unbind all live events from all paragraphs, write: - + To unbind all live click events from all paragraphs, write: - + To unbind just one previously bound handler, pass the function in as the second argument: - +// Now foo will no longer be called +$( "p" ).die( "click", foo ); +]]> + + - diff --git a/entries/disabled-selector.xml b/entries/disabled-selector.xml index 8e601b34a..812c8f572 100644 --- a/entries/disabled-selector.xml +++ b/entries/disabled-selector.xml @@ -9,19 +9,22 @@

        As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':disabled') is equivalent to $('*:disabled'), so $('input:disabled') or similar should be used instead.

        -

        Although their resulting selections are usually the same, the :disabled selector is subtly different from the [disabled] attribute selector; :disabled checks the boolean (true/false) value of the element's disabled property while [disabled] checks for the existence of the disabled attribute.

        +

        Although their resulting selections are usually the same, the :disabled selector is subtly different from the [disabled] attribute selector;:disabled matches elements that are actually disabled while [disabled] only checks for the existence of the disabled attribute.

        -

        The :disabled selector should only be used for selecting HTML elements that support the disabled attribute (<button>, <input>, <optgroup>, <option>, <select>, and <textarea>).

        +

        The :disabled selector should only be used for selecting HTML elements that support the disabled attribute (<button>, <input>, <optgroup>, <option>, <select>, <textarea>, <menuitem>, and <fieldset>).

        Finds all input elements that are disabled. - - + + diff --git a/entries/each.xml b/entries/each.xml index a5de051a9..fd2db6483 100644 --- a/entries/each.xml +++ b/entries/each.xml @@ -3,117 +3,145 @@ .each() 1.0 - + A function to execute for each matched element. + + Iterate over a jQuery object, executing a function for each matched element.

        The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

        Suppose you have a simple unordered list on the page:

        -
        <ul>
        -    <li>foo</li>
        -    <li>bar</li>
        +    
        
        +<ul>
        +  <li>foo</li>
        +  <li>bar</li>
         </ul>
             

        You can select the list items and iterate across them:

        -
        $( "li" ).each(function( index ) {
        -  console.log( index + ": " + $(this).text() );
        +    
        
        +$( "li" ).each(function( index ) {
        +  console.log( index + ": " + $( this ).text() );
         });
        -  
        +

        A message is thus logged for each item in the list:

        - 0: foo + 0: foo
        - 1: bar + 1: bar

        You can stop the loop from within the callback function by returning false.

        Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known as implicit iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each() method:

        -
        // The .each() method is unnecessary here:
        +    
        
        +// The .each() method is unnecessary here:
         $( "li" ).each(function() {
        -  $(this).addClass( "foo" );
        +  $( this ).addClass( "foo" );
         });
         
         // Instead, you should rely on implicit iteration:
         $( "li" ).addClass( "bar" );
        -
        +
        Iterate over three divs and sets their color property. - + div { + color: red; + text-align: center; + cursor: pointer; + font-weight: bolder; + width: 300px; + } +]]> + - To access a jQuery object instead of the regular DOM element, use $(this). For example: + To access a jQuery object instead of the regular DOM element, use $( this ). For example: - + ul { + font-size: 18px; + margin: 0; + } + span { + color: blue; + text-decoration: underline; + cursor: pointer; + } + .example { + font-style: italic; + } +]]> + - Use "return" to break out of each() loops early. + Use return false to break out of each() loops early. - + div { + width: 40px; + height: 40px; + margin: 5px; + float: left; + border: 2px blue solid; + text-align: center; + } + span { + color: red; + } +]]> + diff --git a/entries/element-selector.xml b/entries/element-selector.xml index 8061f3402..a26a9109e 100644 --- a/entries/element-selector.xml +++ b/entries/element-selector.xml @@ -14,22 +14,25 @@ Finds every DIV element. - - + + +]]> - \ No newline at end of file + diff --git a/entries/empty-selector.xml b/entries/empty-selector.xml index 05e13b67e..165e21121 100644 --- a/entries/empty-selector.xml +++ b/entries/empty-selector.xml @@ -9,22 +9,28 @@

        This is the inverse of :parent.

        One important thing to note with :empty (and :parent) is that child elements include text nodes.

        -

        The W3C recommends that the <p> element have at least one child node, even if that child is merely text (see http://www.w3.org/TR/html401/struct/text.html#edef-P). Some other elements, on the other hand, are empty (i.e. have no children) by definition: <input>, <img>, <br>, and <hr>, for example.

        +

        The W3C recommends that the <p> element have at least one child node, even if that child is merely text (see https://www.w3.org/TR/html401/struct/text.html#edef-P). Some other elements, on the other hand, are empty (i.e. have no children) by definition: <input>, <img>, <br>, and <hr>, for example.

        Finds all elements that are empty - they don't have child elements or text. - + - + td { + text-align: center; + } +]]> + - \ No newline at end of file + diff --git a/entries/empty.xml b/entries/empty.xml index 0a1fe9ba3..097ad9c66 100644 --- a/entries/empty.xml +++ b/entries/empty.xml @@ -7,37 +7,47 @@ Remove all child nodes of the set of matched elements from the DOM.

        This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. Consider the following HTML:

        -
        <div class="container">
        +    
        
        +<div class="container">
           <div class="hello">Hello</div>
           <div class="goodbye">Goodbye</div>
        -</div>
        +</div> +

        We can target any element for removal:

        -
        $('.hello').empty();
        +
        
        +$( ".hello" ).empty();
        +    

        This will result in a DOM structure with the Hello text deleted:

        -
        <div class="container">
        +    
        
        +<div class="container">
           <div class="hello"></div>
           <div class="goodbye">Goodbye</div>
        -</div>
        -

        If we had any number of nested elements inside <div class="hello">, they would be removed, too.

        +</div> +
        +

        If we had any number of nested elements inside <div class="hello">, they would be removed, too.

        To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

        If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.

        Removes all child nodes (including text nodes) from all paragraphs - + +]]> - \ No newline at end of file + diff --git a/entries/enabled-selector.xml b/entries/enabled-selector.xml index 7b40f5d60..177680e3f 100644 --- a/entries/enabled-selector.xml +++ b/entries/enabled-selector.xml @@ -7,7 +7,7 @@ Selects all elements that are enabled. -

        As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':enabled') is equivalent to $('*:enabled'), so $('input:enabled') or similar should be used instead.

        +

        As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ( "*" ) is implied. In other words, the bare $( ":enabled" ) is equivalent to $( "*:enabled" ), so $( "input:enabled" ) or similar should be used instead.

        Although their resulting selections are usually the same, :enabled selector is subtly different from :not([disabled]); :enabled selects elements that have their boolean disabled property strictly equal to false, while :not([disabled]) selects elements that do not have a disabled attribute set (regardless of its value).

        @@ -16,12 +16,15 @@
        Find all input elements that are enabled. - - + + diff --git a/entries/end.xml b/entries/end.xml index eb1fbbb1c..7f85ea1aa 100644 --- a/entries/end.xml +++ b/entries/end.xml @@ -6,90 +6,120 @@ End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. -

        Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use end() to pop the sets back off of the stack.

        +

        Most of jQuery's DOM traversal methods operate on a jQuery object instance and produce a new one, matching a different set of DOM elements. When this happens, it is as if the new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use end() to pop the sets back off of the stack.

        Suppose we have a couple short lists on a page:

        
         <ul class="first">
        -   <li class="foo">list item 1</li>
        -   <li>list item 2</li>
        -   <li class="bar">list item 3</li>
        +  <li class="foo">list item 1</li>
        +  <li>list item 2</li>
        +  <li class="bar">list item 3</li>
         </ul>
         <ul class="second">
        -   <li class="foo">list item 1</li>
        -   <li>list item 2</li>
        -   <li class="bar">list item 3</li>
        +  <li class="foo">list item 1</li>
        +  <li>list item 2</li>
        +  <li class="bar">list item 3</li>
         </ul>
        -
        +

        The end() method is useful primarily when exploiting jQuery's chaining properties. When not using chaining, we can usually just call up a previous object by variable name, so we don't need to manipulate the stack. With end(), though, we can string all the method calls together:

        
        -$('ul.first').find('.foo').css('background-color', 'red')
        -  .end().find('.bar').css('background-color', 'green');
        -
        +$( "ul.first" ) + .find( ".foo" ) + .css( "background-color", "red" ) + .end() + .find( ".bar" ) + .css( "background-color", "green" ); +

        This chain searches for items with the class foo within the first list only and turns their backgrounds red. Then end() returns the object to its state before the call to find(), so the second find() looks for '.bar' inside <ul class="first">, not just inside that list's <li class="foo">, and turns the matching elements' backgrounds green. The net result is that items 1 and 3 of the first list have a colored background, and none of the items from the second list do.

        A long jQuery chain can be visualized as a structured code block, with filtering methods providing the openings of nested blocks and end() methods closing them:

        
        -$('ul.first').find('.foo')
        -  .css('background-color', 'red')
        -.end().find('.bar')
        -  .css('background-color', 'green')
        -.end();
        -
        +$( "ul.first" ) + .find( ".foo" ) + .css( "background-color", "red" ) + .end() + .find( ".bar" ) + .css( "background-color", "green" ) + .end(); +

        The last end() is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form, the end() provides visual symmetry and a sense of completion —making the program, at least to the eyes of some developers, more readable, at the cost of a slight hit to performance as it is an additional function call.

        Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs. - + +
        + Tags in jQuery object after end: +
        +]]>
        Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs. - - - + + + - \ No newline at end of file + diff --git a/entries/eq-selector.xml b/entries/eq-selector.xml index 06f56f4fa..a191d31be 100644 --- a/entries/eq-selector.xml +++ b/entries/eq-selector.xml @@ -1,5 +1,5 @@ - + :eq() Selector :eq(index) @@ -11,46 +11,54 @@ :eq(-index) 1.8 - + Zero-based index of the element to match, counting backwards from the last element. Select the element at index n within the matched set. +
        +

        As of jQuery 3.4, the :eq pseudo-class is deprecated. Remove it from your selectors and filter the results later using .eq().

        +

        The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

        -

        Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $('.myclass:eq(1)') selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

        +

        Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $( ".myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

        Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the .eq(index) method did).

        - Finds the third td. - - + + +]]> 160 Apply three different styles to list items to demonstrate that :eq() is designed to select a single element while :nth-child() or :eq() within a looping construct such as .each() can select multiple elements. - - + - + div { + width: 60px; + height: 60px; + margin: 10px; + float: left; + border: 2px solid blue; + } + .blue { + background: blue; + } +]]> + -
        \ No newline at end of file +
        diff --git a/entries/error-shorthand.xml b/entries/error-shorthand.xml new file mode 100644 index 000000000..b40d9b755 --- /dev/null +++ b/entries/error-shorthand.xml @@ -0,0 +1,37 @@ + + + .error() + Bind an event handler to the "error" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
        +

        This API has been removed in jQuery 3.0.

        +

        Instead of .error( handler ) or .error( eventData, handler ), use .on( "error", handler ) or .on( "error", eventData, handler ), respectively.

        +

        Instead of .error(), use .trigger( "error" ).

        +
        +
        + + + + + +
        diff --git a/entries/error.xml b/entries/error.xml index a1477172a..d1f9493ea 100644 --- a/entries/error.xml +++ b/entries/error.xml @@ -1,52 +1,79 @@ - - .error() - Bind an event handler to the "error" JavaScript event. + +Bind an event handler to the "error" event, or trigger that event on an element. + + + error event + Bind an event handler to the "error" event. - 1.0 - - A function to execute when the event is triggered. + 1.7 + + The string "error". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + -

        This method is a shortcut for .on('error', handler).

        +
        +

        This page describes the error event. For the .error() method removed in jQuery 3.0, see .error().

        +

        The error event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

        For example, consider a page with a simple image element:

        -
        <img alt="Book" id="book" />
        +
        
        +<img alt="Book" id="book">
        +    

        The event handler can be bound to the image:

        -
        $('#book')
        -  .error(function() {
        -    alert('Handler for .error() called.')
        -  })
        -  .attr("src", "missing.png");
        +    
        
        +$( "#book" )
        +  .on( "error", function() {
        +    alert( "Handler for `error` called." )
        +  } )
        +  .attr( "src", "missing.png" );
             
        -

        If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

        +

        If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

        - Handler for .error() called. + Handler for `error` called.

        -
        -

        The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

        -
        -

        Note: A jQuery error event handler should not be attached to the window object. The browser fires the window's error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror instead.

        +
        +

        The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler. Also, the error event may not be correctly fired when the page is served locally; error relies on HTTP status codes and will generally not be triggered if the URL uses the file: protocol.

        +
        +

        Note: A jQuery error event handler should not be attached to the window object. The browser fires the window's error event when a script error occurs. However, the window error event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror instead.

        - To hide the "broken image" icons for IE users, you can try: - + To replace all the missing images with another, you can update the src attribute inside the error handler. Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely. + - + + + + + error event + Trigger the "error" event on an element. + + 1.0 + + The string "error". + + + +

        See the description for .on( "error", ... ).

        +
        + +
        + + diff --git a/entries/even-selector.xml b/entries/even-selector.xml index 42210e419..bfc8038a3 100644 --- a/entries/even-selector.xml +++ b/entries/even-selector.xml @@ -1,33 +1,40 @@ - + :even Selector :even 1.0 - Selects even elements, zero-indexed. See also odd. + Selects even elements, zero-indexed. See also :odd. +
        +

        As of jQuery 3.4, the :even pseudo-class is deprecated. Remove it from your selectors and filter the results later using .even() (available in jQuery 3.5.0 or newer).

        +

        In particular, note that the 0-based indexing means that, counter-intuitively, :even selects the first element, third element, and so on within the matched set.

        Finds even table rows, matching the first, third and so on (index 0, 2, 4 etc.). - + - +]]> + +
        diff --git a/entries/even.xml b/entries/even.xml new file mode 100644 index 000000000..cecff9e42 --- /dev/null +++ b/entries/even.xml @@ -0,0 +1,47 @@ + + + .even() + + 3.5 + + Reduce the set of matched elements to the even ones in the set, numbered from zero. + +

        Given a jQuery object that represents a set of DOM elements, the .even() method constructs a new jQuery object from the even elements in that set. Counting starts from zero!

        +

        Consider a page with a simple list on it:

        +
        
        +<ul>
        +  <li>list item 1</li>
        +  <li>list item 2</li>
        +  <li>list item 3</li>
        +  <li>list item 4</li>
        +  <li>list item 5</li>
        +</ul>
        +    
        +

        We can apply this method to the set of list items:

        +
        
        +$( "li" ).even().css( "background-color", "red" );
        +    
        +

        The result of this call is a red background for the first, third & 5th items.

        +
        + + Highlight the even items in a list. + + + + + + +
        diff --git a/entries/event.currentTarget.xml b/entries/event.currentTarget.xml index d25c6f7bd..859cb8d41 100644 --- a/entries/event.currentTarget.xml +++ b/entries/event.currentTarget.xml @@ -8,15 +8,17 @@

        This property will typically be equal to the this of the function.

        - If you are using jQuery.proxy or another form of scope manipulation, this will be equal to whatever context you have provided, not event.currentTarget + If you are using jQuery.proxy or another form of scope manipulation, this will be equal to whatever context you have provided, not event.currentTarget

        Alert that currentTarget matches the `this` keyword. - +}); +]]>
        - \ No newline at end of file + diff --git a/entries/event.data.xml b/entries/event.data.xml index 93155fefe..c1e249325 100644 --- a/entries/event.data.xml +++ b/entries/event.data.xml @@ -18,17 +18,16 @@
        ]]> " ); + logDiv.append( msgs.join( ", " ) + "
        " ); }); } ]]>
        diff --git a/entries/event.delegateTarget.xml b/entries/event.delegateTarget.xml index a0c450896..af9b55bad 100644 --- a/entries/event.delegateTarget.xml +++ b/entries/event.delegateTarget.xml @@ -6,16 +6,18 @@ The element where the currently-called jQuery event handler was attached. -

        This property is most often useful in delegated events attached by .delegate() or .on(), where the event handler is attached at an ancestor of the element being processed. It can be used, for example, to identify and remove event handlers at the delegation point.

        +

        This property is most often useful in delegated events attached by .delegate() or .on(), where the event handler is attached at an ancestor of the element being processed. It can be used, for example, to identify and remove event handlers at the delegation point.

        For non-delegated event handlers attached directly to an element, event.delegateTarget will always be equal to event.currentTarget.

        When a button in any box class is clicked, change the box's background color to red. - + - \ No newline at end of file + diff --git a/entries/event.isDefaultPrevented.xml b/entries/event.isDefaultPrevented.xml index 0b660e1e2..d9ada3149 100644 --- a/entries/event.isDefaultPrevented.xml +++ b/entries/event.isDefaultPrevented.xml @@ -4,15 +4,17 @@ 1.3 - Returns whether event.preventDefault() was ever called on this event object. + Returns whether event.preventDefault() was ever called on this event object. Checks whether event.preventDefault() was called. - +}); +]]> diff --git a/entries/event.isImmediatePropagationStopped.xml b/entries/event.isImmediatePropagationStopped.xml index 8f6e63d51..433cd4912 100644 --- a/entries/event.isImmediatePropagationStopped.xml +++ b/entries/event.isImmediatePropagationStopped.xml @@ -6,33 +6,32 @@ Returns whether event.stopImmediatePropagation() was ever called on this event object. -

        This property was introduced in DOM level 3.

        +

        This property was introduced in DOM level 3.

        Checks whether event.stopImmediatePropagation() was called. - \ No newline at end of file + diff --git a/entries/event.isPropagationStopped.xml b/entries/event.isPropagationStopped.xml index dbf08286d..c6c270b4d 100644 --- a/entries/event.isPropagationStopped.xml +++ b/entries/event.isPropagationStopped.xml @@ -4,33 +4,32 @@ 1.3 - Returns whether event.stopPropagation() was ever called on this event object. + Returns whether event.stopPropagation() was ever called on this event object. -

        This event method is described in the W3C DOM Level 3 specification.

        +

        This event method is described in the W3C DOM Level 3 specification.

        Checks whether event.stopPropagation() was called diff --git a/entries/event.metaKey.xml b/entries/event.metaKey.xml index a35597ac3..0c00d6b9b 100644 --- a/entries/event.metaKey.xml +++ b/entries/event.metaKey.xml @@ -4,21 +4,30 @@ 1.0.4 - Indicates whether the META key was pressed when the event fired. - + Indicates whether the META key was pressed when the event fired. +

        Returns a boolean value (true or false) that indicates whether or not the META key was pressed at the time the event fired. This key might map to an alternative key name on some platforms.

        -
        +

        On Macintosh keyboards, the META key maps to the Command key (⌘).

        +

        On Windows keyboards, the META key maps to the Windows key.

        +
        Determine whether the META key was pressed when the event fired. - body {background-color: #eef; } - div { padding: 20px; } - + - + diff --git a/entries/event.namespace.xml b/entries/event.namespace.xml index 096fd57aa..bbebcda4d 100644 --- a/entries/event.namespace.xml +++ b/entries/event.namespace.xml @@ -11,11 +11,11 @@ Determine the event namespace used. - + Show the mouse position relative to the left and top edges of the document (within this iframe). + + + - \ No newline at end of file + diff --git a/entries/event.pageY.xml b/entries/event.pageY.xml index a1aaf7b22..8815db947 100644 --- a/entries/event.pageY.xml +++ b/entries/event.pageY.xml @@ -4,20 +4,27 @@ 1.0.4 - The mouse position relative to the top edge of the document. + The mouse position relative to the top edge of the document. Show the mouse position relative to the left and top edges of the document (within this iframe). - body {background-color: #eef; } - div { padding: 20px; } - - + + +]]> - \ No newline at end of file + diff --git a/entries/event.preventDefault.xml b/entries/event.preventDefault.xml index 397b066c2..82b4e1047 100644 --- a/entries/event.preventDefault.xml +++ b/entries/event.preventDefault.xml @@ -4,25 +4,25 @@ 1.0 - If this method is called, the default action of the event will not be triggered. + If this method is called, the default action of the event will not be triggered. -

        For example, clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

        +

        For example, clicked anchors will not take the browser to a new URL. We can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event.

        Cancel the default action (navigation) of the click. - \ No newline at end of file + diff --git a/entries/event.relatedTarget.xml b/entries/event.relatedTarget.xml index 0a03e3277..e4ee9eafa 100644 --- a/entries/event.relatedTarget.xml +++ b/entries/event.relatedTarget.xml @@ -4,16 +4,18 @@ 1.1.4 - The other DOM element involved in the event, if any. + The other DOM element involved in the event, if any.

        For mouseout, indicates the element being entered; for mouseover, indicates the element being exited.

        On mouseout of anchors, alert the element type being entered. - + - \ No newline at end of file + diff --git a/entries/event.result.xml b/entries/event.result.xml index e6823b2c6..40bd18724 100644 --- a/entries/event.result.xml +++ b/entries/event.result.xml @@ -11,11 +11,11 @@ Display previous handler's return value - + $( this ).css( "background-color", "#f00" ); +}); +]]> + - \ No newline at end of file + diff --git a/entries/event.stopPropagation.xml b/entries/event.stopPropagation.xml index 69c5ee728..de93b6e68 100644 --- a/entries/event.stopPropagation.xml +++ b/entries/event.stopPropagation.xml @@ -1,23 +1,25 @@ - + event.stopPropagation() 1.0 - Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. + Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. -

        We can use event.isPropagationStopped() to determine if this method was ever called (on that event object).

        -

        This method works for custom events triggered with trigger(), as well.

        +

        We can use event.isPropagationStopped() to determine if this method was ever called (on that event object).

        +

        This method works for custom events triggered with trigger() as well.

        Note that this will not prevent other handlers on the same element from running.

        Kill the bubbling on the click event. - + // Do something +}); +]]> -
        \ No newline at end of file +
        diff --git a/entries/event.target.xml b/entries/event.target.xml index cd1346244..82c701778 100644 --- a/entries/event.target.xml +++ b/entries/event.target.xml @@ -10,30 +10,38 @@ Display the tag's name on click - - -span, strong, p { - padding: 8px; display: block; border: 1px solid #999; } - + + + +]]> Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children. - +$( "ul" ).on( "click", handler ).find( "ul" ).hide(); +]]>
      • sub item 2-b
      -
    ]]> +
+]]> - \ No newline at end of file + diff --git a/entries/event.timeStamp.xml b/entries/event.timeStamp.xml index e3d349937..089997ba7 100644 --- a/entries/event.timeStamp.xml +++ b/entries/event.timeStamp.xml @@ -12,24 +12,30 @@ Display the time since the click handler last executed. +
Click.
+]]>
- \ No newline at end of file + diff --git a/entries/event.type.xml b/entries/event.type.xml index 17193dcf9..a51cc1c85 100644 --- a/entries/event.type.xml +++ b/entries/event.type.xml @@ -4,14 +4,16 @@ 1.0 - Describes the nature of the event. + Describes the nature of the event. On all anchor clicks, alert the event type. - + - \ No newline at end of file + diff --git a/entries/event.which.xml b/entries/event.which.xml index 3926be565..e8e6aa28b 100644 --- a/entries/event.which.xml +++ b/entries/event.which.xml @@ -4,31 +4,35 @@ 1.1.3 - For key or mouse events, this property indicates the specific key or button that was pressed. + For key or mouse events, this property indicates the specific key or button that was pressed. -

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input. For more detail, read about event.charCode on the MDC.

+

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input. For more detail, read about event.charCode on the MDN.

event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button.

Log which key was depressed. - + +
+]]>
Log which mouse button was depressed. + +
+]]>
- \ No newline at end of file + diff --git a/entries/fadeIn.xml b/entries/fadeIn.xml index f65f9f5be..1975c039c 100644 --- a/entries/fadeIn.xml +++ b/entries/fadeIn.xml @@ -19,82 +19,116 @@ -

The .fadeIn() method animates the opacity of the matched elements.

+

The .fadeIn() method animates the opacity of the matched elements. It is similar to the .fadeTo() method but that method does not unhide the element and can specify the final opacity level.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.

We can animate any element, such as a simple image:

-
<div id="clickme">
-      Click here
-    </div>
-    <img id="book" src="book.png" alt="" width="100" height="123" />
-    With the element initially hidden, we can show it slowly:
-    $('#clickme').click(function() {
-      $('#book').fadeIn('slow', function() {
-        // Animation complete
-      });
-    });
-

- - - - -

+

+<div id="clickme">
+  Click here
+</div>
+<img id="book" src="book.png" alt="" width="100" height="123">
+
+// With the element initially hidden, we can show it slowly:
+$( "#clickme" ).on( "click", function() {
+  $( "#book" ).fadeIn( "slow", function() {
+    // Animation complete
+  });
+});
+    
+
+ + + + +
Figure 1 - Illustration of the fadeIn() effect
+

Easing

-

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

+

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

Callback Function

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

-

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

+

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds. +$( document.body ).on( "click", function() { + $( "div:hidden" ).first().fadeIn( "slow" ); +} ); +]]> - + Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top. - + p { + position: relative; + width: 400px; + height: 90px; + } + div { + position: absolute; + width: 400px; + height: 65px; + font-size: 36px; + text-align: center; + color: yellow; + background: red; + padding-top: 25px; + top: 0; + left: 0; + display: none; + } + span { + display: none; + } +]]> + - \ No newline at end of file + diff --git a/entries/fadeOut.xml b/entries/fadeOut.xml index 814213f29..5050e1a57 100644 --- a/entries/fadeOut.xml +++ b/entries/fadeOut.xml @@ -22,101 +22,124 @@

The .fadeOut() method animates the opacity of the matched elements. Once the opacity reaches 0, the display style property is set to none, so the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.

We can animate any element, such as a simple image:

-
<div id="clickme">
+    

+<div id="clickme">
   Click here
 </div>
-<img id="book" src="book.png" alt="" width="100" height="123" />
+<img id="book" src="book.png" alt="" width="100" height="123"> +

With the element initially shown, we can hide it slowly:

-
$('#clickme').click(function() {
-  $('#book').fadeOut('slow', function() {
+    

+$( "#clickme" ).on( "click", function() {
+  $( "#book" ).fadeOut( "slow", function() {
     // Animation complete.
   });
-});
-

- - - - -

-
-

Note: To avoid unnecessary DOM manipulation, .fadeOut() will not hide an element that is already considered hidden. For information on which elements jQuery considers hidden, see :hidden Selector.

-
+}); +
+
+ + + + +
Figure 1 - Illustration of the fadeOut() effect
+
+
+

Note: To avoid unnecessary DOM manipulation, .fadeOut() will not hide an element that is already considered hidden. For information on which elements jQuery considers hidden, see :hidden Selector.

+

Easing

-

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

+

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

Callback Function

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

-

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

+

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

Animates all paragraphs to fade out, completing the animation within 600 milliseconds. +$( "p" ).on( "click", function() { + $( "p" ).fadeOut( "slow" ); +}); +]]> - + +

+]]>
Fades out spans in one section that you click on. +}); +$( "span" ).hover(function() { + $( this ).addClass( "hilite" ); +}, function() { + $( this ).removeClass( "hilite" ); +}); +]]> - + +

+]]>
Fades out two divs, one with a "linear" easing and one with the default, "swing," easing. - +

+]]>
Fade div to a random opacity on each click, completing the animation within 200 milliseconds. - +
+]]>
- Find the right answer! The fade will take 250 milliseconds and change various styles when it completes. + Find the right answer! The fade will take 250 milliseconds and change various styles when it completes. - +
+]]>
diff --git a/entries/fadeToggle.xml b/entries/fadeToggle.xml index 34141424f..22e246ee4 100644 --- a/entries/fadeToggle.xml +++ b/entries/fadeToggle.xml @@ -17,29 +17,28 @@

The .fadeToggle() method animates the opacity of the matched elements. When called on a visible element, the element's display style property is set to none once the opacity reaches 0, so the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

Easing

-

The string representing an easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

+

The string representing an easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

Callback Function

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

-

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

+

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion. @@ -47,4 +46,4 @@ $("button:last").click(function () { - \ No newline at end of file + diff --git a/entries/file-selector.xml b/entries/file-selector.xml index 18ce5e368..c5295eca0 100644 --- a/entries/file-selector.xml +++ b/entries/file-selector.xml @@ -7,45 +7,48 @@ Selects all elements of type file. -

:file is equivalent to [type="file"]. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':file') is equivalent to $('*:file'), so $('input:file') should be used instead.

+

:file is equivalent to [type="file"]. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $( ":file" ) is equivalent to $("*:file" ), so $( "input:file" ) should be used instead.

Finds all file inputs. - + textarea { + height: 45px; + } +]]> + - \ No newline at end of file + diff --git a/entries/filter.xml b/entries/filter.xml index 889e3d590..ed92d385c 100644 --- a/entries/filter.xml +++ b/entries/filter.xml @@ -9,25 +9,28 @@ 1.0 - + A function used as a test for each element in the set. this is the current DOM element. + + + 1.4 - - An element to match the current set of elements against. + + One or more DOM elements to match the current set of elements against. 1.4 - + An existing jQuery object to match the current set of elements against. Reduce the set of matched elements to those that match the selector or pass the function's test.

Given a jQuery object that represents a set of DOM elements, the .filter() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.

Consider a page with a simple list on it:

-

+    

 <ul>
   <li>list item 1</li>
   <li>list item 2</li>
@@ -36,18 +39,17 @@
   <li>list item 5</li>
   <li>list item 6</li>
 </ul>
-
-

We can apply this method to the set of list items:

-

-  $('li').filter(':even').css('background-color', 'red');
-
-

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that :even and :odd use 0-based indexing).

-

Using a Filter Function

-

The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns true (or a "truthy" value), the element will be included in the filtered set; otherwise, it will be excluded. Suppose we have a somewhat more involved HTML snippet:

-

+    
+

We can apply this method to the set of list items:

+

+$( "li" ).filter( ":nth-child(2n)" ).css( "background-color", "red" );
+    
+

The result of this call is a red background for items 2, 4, and 6, as they match the selector.

+

Using a Filter Function

+

The second form of this method allows us to filter elements against a function rather than a selector. For each element, if the function returns true (or a "truthy" value), the element will be included in the filtered set; otherwise, it will be excluded. Suppose we have a somewhat more involved HTML snippet:

+

 <ul>
-  <li><strong>list</strong> item 1 -
-    one strong tag</li>
+  <li><strong>list</strong> item 1 - one strong tag</li>
   <li><strong>list</strong> item <strong>2</strong> -
     two <span>strong tags</span></li>
   <li>list item 3</li>
@@ -55,76 +57,95 @@
   <li>list item 5</li>
   <li>list item 6</li>
 </ul>
-
-

We can select the list items, then filter them based on their contents:

-

-$('li').filter(function(index) {
-  return $('strong', this).length == 1;
-}).css('background-color', 'red');
-
-

This code will alter the first list item only, as it contains exactly one <strong> tag. Within the filter function, this refers to each DOM element in turn. The parameter passed to the function tells us the index of that DOM element within the set matched by the jQuery object.

-

We can also take advantage of the index passed through the function, which indicates the 0-based position of the element within the unfiltered set of matched elements:

-

-$('li').filter(function(index) {
-  return index % 3 == 2;
-}).css('background-color', 'red');
-
-

This alteration to the code will cause the third and sixth list items to be highlighted, as it uses the modulus operator (%) to select every item with an index value that, when divided by 3, has a remainder of 2.

- +
+

We can select the list items, then filter them based on their contents:

+

+$( "li" )
+  .filter(function( index ) {
+    return $( "strong", this ).length === 1;
+  })
+    .css( "background-color", "red" );
+    
+

This code will alter the first list item only, as it contains exactly one <strong> tag. Within the filter function, this refers to each DOM element in turn. The parameter passed to the function tells us the index of that DOM element within the set matched by the jQuery object.

+

We can also take advantage of the index passed through the function, which indicates the 0-based position of the element within the unfiltered set of matched elements:

+

+$( "li" )
+  .filter(function( index ) {
+    return index % 3 === 2;
+  })
+    .css( "background-color", "red" );
+    
+

This alteration to the code will cause the third and sixth list items to be highlighted, as it uses the modulus operator (%) to select every item with an index value that, when divided by 3, has a remainder of 2.

+

Note: When a CSS selector string is passed to .filter(), text and comment nodes will always be removed from the resulting jQuery object during the filtering process. When a specific node or array of nodes are provided, a text or comment node will be included in the resulting jQuery object only if it matches one of the nodes in the filtering array.

+ +
Change the color of all divs; then add a border to those with a "middle" class. - + div { + width: 60px; + height: 60px; + margin: 5px; + float: left; + border: 2px white solid; + } +]]> + Change the color of all divs; then add a border to the second one (index == 1) and the div with an id of "fourth." + div { + width: 60px; + height: 60px; + margin: 5px; + float: left; + border: 3px white solid; + } +]]> +
+
+
+
+
+
+]]>
Select all divs and filter the selection with a DOM element, keeping only the one with an id of "unique". - + Select all divs and filter the selection with a jQuery object, keeping only the one with an id of "unique". +$( "div" ).filter( $( "#unique" ) ); +]]> - \ No newline at end of file + diff --git a/entries/find.xml b/entries/find.xml index 28d4228ad..fc10241bd 100644 --- a/entries/find.xml +++ b/entries/find.xml @@ -9,20 +9,16 @@ 1.6 - - A jQuery object to match elements against. - - - - 1.6 - - An element to match elements against. + + An element or a jQuery object to match elements against. + + Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

-

The first signature for the .find()method accepts a selector expression of the same type that we can pass to the $() function. The elements will be filtered by testing whether they match this selector.

+

The first signature for the .find()method accepts a selector expression of the same type that we can pass to the $() function. The elements will be filtered by testing whether they match this selector; all parts of the selector must lie inside of an element on which .find() is called. The expressions allowed include selectors like > p which will find all the paragraphs that are children of the elements in the jQuery object.

Consider a page with a basic nested list on it:


 <ul class="level-1">
@@ -42,77 +38,102 @@
   </li>
   <li class="item-iii">III</li>
 </ul>
-
+

If we begin at item II, we can find list items within it:

-
$('li.item-ii').find('li').css('background-color', 'red');
+

+$( "li.item-ii" ).find( "li" ).css( "background-color", "red" );
+    

The result of this call is a red background on items A, B, 1, 2, 3, and C. Even though item II matches the selector expression, it is not included in the results; only descendants are considered candidates for the match.

-
-

Unlike in the rest of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

-
-

Selector context is implemented with the .find() method; therefore, $('li.item-ii').find('li') is equivalent to $('li', 'li.item-ii').

+
+

Unlike most of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

+
+

Selector context is implemented with the .find() method; therefore, $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).

As of jQuery 1.6, we can also filter the selection with a given jQuery collection or element. With the same nested list as above, if we start with:

-
var $allListElements = $('li');
+

+var allListElements = $( "li" );
+    

And then pass this jQuery object to find:

-
$('li.item-ii').find( $allListElements );
+

+$( "li.item-ii" ).find( allListElements );
+    

This will return a jQuery collection which contains only the list elements that are descendants of item II.

Similarly, an element may also be passed to find:


-var item1 = $('li.item-1')[0];
-$('li.item-ii').find( item1 ).css('background-color', 'red');
-
+var item1 = $( "li.item-1" )[ 0 ]; +$( "li.item-ii" ).find( item1 ).css( "background-color", "red" ); +

The result of this call would be a red background on item 1.

+
- Starts with all paragraphs and searches for descendant span elements, same as $("p span") + Starts with all paragraphs and searches for descendant span elements, same as $( "p span" ) - + A selection using a jQuery collection of all span tags. Only spans within p tags are changed to red while others are left blue. + span { + color: blue; + } +]]> - + Add spans around each word then add a hover and italicize words with the letter t. - + +

+]]>
- \ No newline at end of file + diff --git a/entries/finish.xml b/entries/finish.xml index bb6ed7e53..506d53f2b 100644 --- a/entries/finish.xml +++ b/entries/finish.xml @@ -4,7 +4,7 @@ Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. 1.9 - + The name of the queue in which to stop animations. @@ -12,106 +12,107 @@

When .finish() is called on an element, the currently-running animation and all queued animations (if any) immediately stop and their CSS properties set to their target values. All queued animations are removed.

If the first argument is provided, only the animations in the queue represented by that string will be stopped.

The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

-
+

Animations may be stopped globally by setting the property $.fx.off to true. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

-
+ Click the Go button once to start the animation, and then click the other buttons to see how they affect the current and queued animations. - - diff --git a/entries/first-child-selector.xml b/entries/first-child-selector.xml index e11498e69..d91a50b8b 100644 --- a/entries/first-child-selector.xml +++ b/entries/first-child-selector.xml @@ -7,36 +7,41 @@ Selects all elements that are the first child of their parent. -

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

+

While .first() matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

Finds the first span in each matched div to underline and add a hover state. - + span { + color: #008; + } + span.sogreen { + color: green; + font-weight: bolder; + } +]]> + - \ No newline at end of file + diff --git a/entries/first-of-type-selector.xml b/entries/first-of-type-selector.xml index 08220642e..e63d05013 100644 --- a/entries/first-of-type-selector.xml +++ b/entries/first-of-type-selector.xml @@ -12,23 +12,29 @@ Find the first span in each matched div and add a class to it. - + span.fot { + color: red; + font-size: 120%; + font-style: italic; + } +]]> + diff --git a/entries/first-selector.xml b/entries/first-selector.xml index bd6bee032..1308ff5ec 100644 --- a/entries/first-selector.xml +++ b/entries/first-selector.xml @@ -1,31 +1,40 @@ - + :first Selector :first 1.0 - Selects the first matched element. + Selects the first matched DOM element. -

The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.

+
+

As of jQuery 3.4, the :first pseudo-class is deprecated. Remove it from your selectors and filter the results later using .first().

+
+

The :first pseudo-class is equivalent to :eq( 0 ). It could also be written as :lt( 1 ). While this matches only a single element, :first-child can match more than one: One for each parent.

Finds the first table row. - + - + td { + color: blue; + font-weight: bold; + } +]]> + -
\ No newline at end of file + +
diff --git a/entries/first.xml b/entries/first.xml index 1921362b4..90ac489c7 100644 --- a/entries/first.xml +++ b/entries/first.xml @@ -5,9 +5,10 @@ 1.4 Reduce the set of matched elements to the first in the set. -

Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first element in that set.

-

Consider a page with a simple list on it:

-

+  
+    

Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first element in that set.

+

Consider a page with a simple list on it:

+

 <ul>
   <li>list item 1</li>
   <li>list item 2</li>
@@ -15,15 +16,31 @@
   <li>list item 4</li>
   <li>list item 5</li>
 </ul>
-
-

We can apply this method to the set of list items:

-
$('li').first().css('background-color', 'red');
-

The result of this call is a red background for the first item.

+
+

We can apply this method to the set of list items:

+

+$( "li" ).first().css( "background-color", "red" );
+    
+

The result of this call is a red background for the first item.

+
- Highlight the first span in a paragraph. - - - + Highlight the first item in a list. + + + diff --git a/entries/focus-selector.xml b/entries/focus-selector.xml index eb12615f9..0d3f1e23e 100644 --- a/entries/focus-selector.xml +++ b/entries/focus-selector.xml @@ -7,37 +7,37 @@ Selects element if it is currently focused. -

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':focus') is equivalent to $('*:focus'). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

+

As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ( "*" ) is implied. In other words, the bare $( ":focus" ) is equivalent to $( "*:focus" ). If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.

Adds the focused class to whatever element has focus - \ No newline at end of file + diff --git a/entries/focus-shorthand.xml b/entries/focus-shorthand.xml new file mode 100644 index 000000000..a38f4c280 --- /dev/null +++ b/entries/focus-shorthand.xml @@ -0,0 +1,37 @@ + + + .focus() + Bind an event handler to the "focus" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
+

This API is deprecated.

+

Instead of .focus( handler ) or .focus( eventData, handler ), use .on( "focus", handler ) or .on( "focus", eventData, handler ), respectively.

+

Instead of .focus(), use .trigger( "focus" ).

+
+
+ + + + + +
diff --git a/entries/focus.xml b/entries/focus.xml index 208cc4aac..c9736a295 100644 --- a/entries/focus.xml +++ b/entries/focus.xml @@ -1,83 +1,119 @@ - - .focus() - Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. + + +Bind an event handler to the "focus" event, or trigger that event on an element. + + focus event + Bind an event handler to the "focus" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "focus". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - +
+

This page describes the focus event. For the deprecated .focus() method, see .focus().

+
    -
  • This method is a shortcut for .on('focus', handler) in the first and second variations, and .trigger('focus') in the third.
  • The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
  • Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element. The focus is used to determine which element is the first to receive keyboard-related events.
-
-

Attempting to set focus to a hidden element causes an error in Internet Explorer. Take care to only use .focus() on elements that are visible. To run an element's focus event handlers without setting focus to the element, use .triggerHandler("focus") instead of .focus().

-
+
+

Attempting to set focus to a hidden element causes an error in Internet Explorer. Take care to only use .trigger( "focus" ) on elements that are visible. To run an element's focus event handlers without setting focus to the element, use .triggerHandler( "focus" ) instead of .trigger( "focus" ).

+

For example, consider the HTML:

-
<form>
-  <input id="target" type="text" value="Field 1" />
-  <input type="text" value="Field 2" />
+    

+<form>
+  <input id="target" type="text" value="Field 1">
+  <input type="text" value="Field 2">
 </form>
 <div id="other">
   Trigger the handler
 </div>
-
+

The event handler can be bound to the first input field:

-
$('#target').focus(function() {
-  alert('Handler for .focus() called.');
-});
+

+$( "#target" ).on( "focus", function() {
+  alert( "Handler for `focus` called." );
+} );
+    

Now clicking on the first field, or tabbing to it from another field, displays the alert:

- Handler for .focus() called. + Handler for `focus` called.

We can trigger the event when another element is clicked:

-
$('#other').click(function() {
-  $('#target').focus();
-});
-

After this code executes, clicks on Trigger the handler will also alert the message.

-

The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods, .live() and .delegate().

+

+$( "#other" ).on( "click", function() {
+  $( "#target" ).trigger( "focus" );
+} );
+    
+

After this code executes, clicks on Trigger the handler will also alert the message.

+

The focus event does not bubble. As of version 1.4.2, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods.

+

The native focus event is asynchronous in all versions of IE, contrary to other browsers. To avoid issues related to this discrepancy, as of jQuery 3.7.0, jQuery uses focusin as the native backing event for focus in IE.

Fire focus. - + - + To stop people from writing in text input boxes, try: - + To focus on a login input box with id 'login' on page startup, try: - + - + + +
+ + + focus event + Trigger the "focus" event on an element. + + 1.0 + + The string "focus". + + + +

See the description for .on( "focus", ... ).

+
+ + +
+ +
diff --git a/entries/focusin-shorthand.xml b/entries/focusin-shorthand.xml new file mode 100644 index 000000000..ff8f548ed --- /dev/null +++ b/entries/focusin-shorthand.xml @@ -0,0 +1,37 @@ + + + .focusin() + Bind an event handler to the "focusin" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
+

This API is deprecated.

+

Instead of .focusin( handler ) or .focusin( eventData, handler ), use .on( "focusin", handler ) or .on( "focusin", eventData, handler ), respectively.

+

Instead of .focusin(), use .trigger( "focusin" ).

+
+
+ + + + + +
diff --git a/entries/focusin.xml b/entries/focusin.xml index 9b7f11334..7b5288f67 100644 --- a/entries/focusin.xml +++ b/entries/focusin.xml @@ -1,40 +1,70 @@ - - .focusin() + + +Bind an event handler to the "focusin" event, or trigger that event on an element. + + focusin event Bind an event handler to the "focusin" event. - 1.4 - - A function to execute each time the event is triggered. + 1.7 + + The string "focusin". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + -

This method is a shortcut for .on('focusin', handler).

-

The focusin event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the focus event in that it supports detecting the focus event on parent elements (in other words, it supports event bubbling).

-

This event will likely be used together with the focusout event.

+
+

This page describes the focusin event. For the deprecated .focusin() method, see .focusin().

+
+

The focusin event is sent to an element when it, or any element inside of it, gains focus. This is distinct from the focus event in that it supports detecting the focus event on parent elements (in other words, it supports event bubbling).

+

This event will likely be used together with the focusout event.

Watch for a focus to occur within the paragraphs on the page. - + - + - - + + + + + +
+ + + focusin event + Trigger the "focusin" event on an element. + + 1.0 + + The string "focusin". + + + +

See the description for .on( "focusin", ... ).

+
+ + + -
+ +
diff --git a/entries/focusout-shorthand.xml b/entries/focusout-shorthand.xml new file mode 100644 index 000000000..6114a08be --- /dev/null +++ b/entries/focusout-shorthand.xml @@ -0,0 +1,37 @@ + + + .focusout() + Bind an event handler to the "focusout" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
+

This API is deprecated.

+

Instead of .focusout( handler ) or .focusout( eventData, handler ), use .on( "focusout", handler ) or .on( "focusout", eventData, handler ), respectively.

+

Instead of .focusout(), use .trigger( "focusout" ).

+
+
+ + + + + +
diff --git a/entries/focusout.xml b/entries/focusout.xml index ea156acb4..7b90cb82d 100644 --- a/entries/focusout.xml +++ b/entries/focusout.xml @@ -1,62 +1,91 @@ - - .focusout() - Bind an event handler to the "focusout" JavaScript event. + + +Bind an event handler to the "focusout" event, or trigger that event on an element. + + focusout event + Bind an event handler to the "focusout" event. - 1.4 - - A function to execute each time the event is triggered. + 1.7 + + The string "focusout". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + -

This method is a shortcut for .on('focusout', handler).

-

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

-

This event will likely be used together with the focusin event.

+
+

This page describes the focusout event. For the deprecated .focusout() method, see .focusout().

+
+

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

+

This event will likely be used together with the focusin event.

- Watch for a loss of focus to occur inside paragraphs and note the difference between the focusout count and the blur count. + Watch for a loss of focus to occur inside paragraphs and note the difference between the focusout count and the blur count. (The blur count does not change because those events do not bubble.) - - + + + + + +
+ + + focusout event + Trigger the "focuout" event on an element. + + 1.0 + + The string "focusout". + + + +

See the description for .on( "focusout", ... ).

+
+ + + -
+ +
diff --git a/entries/get.xml b/entries/get.xml index de6ef14a3..cb52eb2d0 100644 --- a/entries/get.xml +++ b/entries/get.xml @@ -1,81 +1,120 @@ - - .get() - - 1.0 - - A zero-based integer indicating which element to retrieve. - - + Retrieve the DOM elements matched by the jQuery object. - -

The .get() method grants us access to the DOM nodes underlying each jQuery object. Suppose we had a simple unordered list on the page:

-

+  
+    .get()
+    
+      1.0
+      
+        A zero-based integer indicating which element to retrieve.
+      
+    
+    Retrieve one of the elements matched by the jQuery object.
+    
+      

The .get() method grants access to the DOM nodes underlying each jQuery object. If the value of index is out of bounds — less than the negative number of elements or equal to or greater than the number of elements — it returns undefined. Consider a simple unordered list:

+

 <ul>
   <li id="foo">foo</li>
   <li id="bar">bar</li>
 </ul>
-    
-

Without a parameter, .get() returns all of the elements:

-
alert($('li').get());
-

All of the matched DOM nodes are returned by this call, contained in a standard array:

-

- [<li id="foo">, <li id="bar">] -

-

With an index specified, .get() will retrieve a single element:

-
($('li').get(0));
-

Since the index is zero-based, the first list item is returned:

-

- <li id="foo"> -

-

Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:

-
alert($('li')[0]);
-

However, this syntax lacks some of the additional capabilities of .get(), such as specifying a negative index:

-
alert($('li').get(-1));
-

A negative index is counted from the end of the matched set, so this example will return the last item in the list:

-

- <li id="bar"> -

-
- - Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array. -
+

However, this syntax lacks some of the additional capabilities of .get(), such as specifying a negative index:

+

+console.log( $( "li" ).get( -1 ) );
+      
+

A negative index is counted from the end of the matched set, so this example returns the last item in the list:

+

+ <li id="bar"> +

+
+ + Display the tag name of the click element. + + + + + + +
+ + .get() + + 1.0 + + Retrieve the elements matched by the jQuery object. + +

Consider a simple unordered list:

+

+<ul>
+  <li id="foo">foo</li>
+  <li id="bar">bar</li>
+</ul>
+      
+

Without a parameter, .get() returns an array of all of the elements:

+

+console.log( $( "li" ).get() );
+      
+

All of the matched DOM nodes are returned by this call, contained in a standard array:

+

+ [<li id="foo">, <li id="bar">] +

+
+ + Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. + - - - - - Gives the tag name of the element clicked on. - - - + - - - -
\ No newline at end of file +
One
+
Two
+
Three
+]]> +
+ + + + diff --git a/entries/gt-selector.xml b/entries/gt-selector.xml index 8a26148e1..1aad2e3d7 100644 --- a/entries/gt-selector.xml +++ b/entries/gt-selector.xml @@ -1,34 +1,49 @@ - + :gt() Selector - :gt(index) + :gt(index) 1.0 Zero-based index. + + :gt(-index) + 1.8 + + Zero-based index, counting backwards from the last element. + + Select all elements at an index greater than index within the matched set. +
+

As of jQuery 3.4, the :gt pseudo-class is deprecated. Remove it from your selectors and filter the results later using .slice(). For example, :gt(3) can be replaced with a call to .slice( 4 ) (the provided index needs to be increased by one).

+

index-related selectors

The index-related selector expressions (including this "greater than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

-

Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $('.myclass:gt(1)') selects elements after the second element in the document with the class myclass, rather than after the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

+

Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $( ".myclass:gt(1)" ) selects elements after the second element in the document with the class myclass, rather than after the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

+

Prior to jQuery 1.8, the :gt(index) selector did not accept a negative value for index

- Finds TD #5 and higher. Reminder: the indexing starts at 0. - - + Give TD #5 and higher a yellow background and TD #8 a red text color. + + +
diff --git a/entries/has-attribute-selector.xml b/entries/has-attribute-selector.xml index 8c6a5bbac..1bd8b4d80 100644 --- a/entries/has-attribute-selector.xml +++ b/entries/has-attribute-selector.xml @@ -11,19 +11,22 @@ Selects elements that have the specified attribute, with any value. - Bind a single click that adds the div id to its text. + Bind a single click to divs with an id that adds the id to the div's text. - + -
\ No newline at end of file + diff --git a/entries/has-selector.xml b/entries/has-selector.xml index 73b8557ab..5d514b959 100644 --- a/entries/has-selector.xml +++ b/entries/has-selector.xml @@ -10,20 +10,25 @@ Selects elements which contain at least one element that matches the specified selector. -

The expression $('div:has(p)') matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.

+

The expression $( "div:has(p)" ) matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.

- + Adds the class "test" to all divs that have a paragraph inside of them. - - + + + .test { + border: 3px inset red; + } +]]> - \ No newline at end of file + diff --git a/entries/has.xml b/entries/has.xml index ed31dbccb..2b3be9913 100644 --- a/entries/has.xml +++ b/entries/has.xml @@ -29,19 +29,25 @@ <li>list item 3</li> <li>list item 4</li> </ul> -
+

We can apply this method to the set of list items as follows:

-
$('li').has('ul').css('background-color', 'red');
+

+$( "li" ).has( "ul" ).css( "background-color", "red" );
+    

The result of this call is a red background for item 2, as it is the only <li> that has a <ul> among its descendants.

Check if an element is inside another. + p { + margin: 8px; + font-size: 16px; + } + .selected { + color: red; + } +]]> +

This paragraph is black and is the first paragraph.

+

This paragraph is red and is the second paragraph.

+
First paragraph has selected class:
+
Second paragraph has selected class:
+
At least one paragraph has selected class:
+]]>
- \ No newline at end of file + diff --git a/entries/header-selector.xml b/entries/header-selector.xml index d8db55d9b..5889ae7be 100644 --- a/entries/header-selector.xml +++ b/entries/header-selector.xml @@ -10,18 +10,17 @@ Adds a background and text color to all the headers on the page. - - - + + - \ No newline at end of file + diff --git a/entries/height.xml b/entries/height.xml index 807196301..3a57f6039 100644 --- a/entries/height.xml +++ b/entries/height.xml @@ -1,57 +1,76 @@ Get the current computed height for the first element in the set of matched elements or set the height of every matched element. - + .height() 1.0 Get the current computed height for the first element in the set of matched elements. -

The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

-

+

The difference between .css( "height" ) and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

+
-

+
Figure 1 - Illustration of the measured height
+

This method is also able to find the height of the window and document.

-
$(window).height();   // returns height of browser viewport
-$(document).height(); // returns height of HTML document
-

Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property.

-
+

+// Returns height of browser viewport
+$( window ).height();
+
+// Returns height of HTML document
+$( document ).height();
+      
+

Note that .height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "height" ) rather than .height().

+

Note: Although style and script tags will report a value for .width() or height() when absolutely positioned and given display:block, it is strongly discouraged to call those methods on these tags. In addition to being a bad practice, the results may also prove unreliable.

-
+
+ + Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. - + +
 
+

+ Sample paragraph to test height +

+]]>
@@ -70,7 +89,13 @@ $(document).height(); // returns height of HTML document 1.4.1 - + + + + + + + A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. @@ -82,18 +107,31 @@ $(document).height(); // returns height of HTML document To set the height of each div on click to 30px plus a color change. - - - + + + diff --git a/entries/hidden-selector.xml b/entries/hidden-selector.xml index a47a52164..44b8397c6 100644 --- a/entries/hidden-selector.xml +++ b/entries/hidden-selector.xml @@ -14,43 +14,61 @@
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.
  • -

    Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start of the animation.

    -

    How :hidden is determined was changed in jQuery 1.3.2. An element is assumed to be hidden if it or any of its parents consumes no space in the document. CSS visibility isn't taken into account (therefore $(elem).css('visibility','hidden').is(':hidden') == false). The release notes outline the changes in more detail.

    +

    Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation.

    +

    Elements that are not in a document are not considered to be visible; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

    +

    This selector is the opposite of the :visible selector. So, every element selected by :hidden isn't selected by :visible and vice versa.

    +

    During animations to show an element, the element is considered to be visible at the start of the animation.

    +

    How :hidden is determined was changed in jQuery 1.3.2. An element is assumed to be hidden if it or any of its parents consumes no space in the document. CSS visibility isn't taken into account (therefore $( elem ).css( "visibility", "hidden" ).is( ":hidden" ) == false). The release notes outline the changes in more detail.

    +

    jQuery 3 slightly modifies the meaning of :hidden (and therefore of :visible). Starting with this version, elements will be considered :hidden if they don't have any layout boxes. For example, br elements and inline elements with no content will not be selected by the :hidden selector.

    + Shows all hidden divs and counts hidden inputs. - + + +]]> -
    \ No newline at end of file +
    diff --git a/entries/hide.xml b/entries/hide.xml index 6d6755c4e..01f88a155 100644 --- a/entries/hide.xml +++ b/entries/hide.xml @@ -28,104 +28,130 @@

    With no parameters, the .hide() method is the simplest way to hide an element:

    -
    $('.target').hide();
    +    
    
    +$( ".target" ).hide();
         
    -

    The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

    +

    The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline and is hidden then shown, it will once again be displayed inline.

    When a duration, a plain object, or a "complete" function is provided, .hide() becomes an animation method. The .hide() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0, the display style property is set to none to ensure that the element no longer affects the layout of the page.

    Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

    Note that .hide() is fired immediately and will override the animation queue if no duration or a duration of 0 is specified.

    -

    As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

    +

    As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

    If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

    +
    +

    Note: This method may cause performance issues, especially when used on many elements. If you're encountering such issues, use performance testing tools to determine whether this method is causing them. Moreover, this method can cause problems with responsive layouts if the display value differs at different viewport sizes.

    +

    We can animate any element, such as a simple image:

    -
    <div id="clickme">
    +    
    
    +<div id="clickme">
       Click here
     </div>
    -<img id="book" src="book.png" alt="" width="100" height="123" />
    -With the element initially shown, we can hide it slowly:
    -$('#clickme').click(function() {
    -  $('#book').hide('slow', function() {
    -    alert('Animation complete.');
    +<img id="book" src="book.png" alt="" width="100" height="123">
    +    
    +
    
    +// With the element initially shown, we can hide it slowly:
    +$( "#clickme" ).on( "click", function() {
    +  $( "#book" ).hide( "slow", function() {
    +    alert( "Animation complete." );
       });
    -});
    -

    - - - - -

    +}); +
    +
    + + + + +
    Figure 1 - Illustration of the hide() effect
    +
    Hides all paragraphs then the link on click. - + Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds. - + p { + background: #dad; + font-weight: bold; + } +]]> + Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one. - + + +]]> Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time. - + div { + background: #ece023; + width: 30px; + height: 40px; + margin: 2px; + float: left; + } +]]> + diff --git a/entries/hover.xml b/entries/hover.xml index 13e81c7ee..a924d368f 100644 --- a/entries/hover.xml +++ b/entries/hover.xml @@ -1,116 +1,156 @@ Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - + .hover() Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. 1.0 - - A function to execute when the mouse pointer enters the element. + + + A function to execute when the mouse pointer enters the element. - - A function to execute when the mouse pointer leaves the element. + + + A function to execute when the mouse pointer leaves the element. +
    +

    This API is deprecated. Use .on( "mouseenter", handlerIn ).on( "mouseleave", handlerOut ) instead.

    +

    The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

    -

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for:

    -
    $(selector).mouseenter(handlerIn).mouseleave(handlerOut);
    -

    See the discussions for .mouseenter() and .mouseleave() for more details.

    +

    Calling $( selector ).hover( handlerIn, handlerOut ) is shorthand for:

    +
    
    +$( selector ).on( "mouseenter", handlerIn ).on( "mouseleave", handlerOut );
    +      
    +

    See the discussions for mouseenter and mouseleave for more details.

    To add a special style to list items that are being hovered over, try: - + To add a special style to table cells that are being hovered over, try: - +); +]]>
    To unbind the above example use: - + + - + + Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. 1.4 - - A function to execute when the mouse pointer enters or leaves the element. + + + A function to execute when the mouse pointer enters or leaves the element. +
    +

    This API is deprecated. Use .on( "mouseenter mouseleave", handlerInOut ) instead.

    +

    The .hover() method, when passed a single function, will execute that handler for both mouseenter and mouseleave events. This allows the user to use jQuery's various toggle methods within the handler or to respond differently within the handler depending on the event.type.

    Calling $(selector).hover(handlerInOut) is shorthand for:

    -
    $(selector).on("mouseenter mouseleave", handlerInOut);
    -

    See the discussions for .mouseenter() and .mouseleave() for more details.

    +
    
    +$( selector ).on( "mouseenter mouseleave", handlerInOut );
    +      
    +

    See the discussions for mouseenter and mouseleave for more details.

    Slide the next sibling LI up or down on hover, and toggle a class. - + ul { + margin-left: 20px; + color: blue; + } + li { + cursor: default; + } + li.active { + background: black; + color: white; + } + span { + color:red; + } +]]> + +
    diff --git a/entries/html.xml b/entries/html.xml index 43b68a3e0..1a29d361a 100644 --- a/entries/html.xml +++ b/entries/html.xml @@ -10,38 +10,55 @@

    This method is not available on XML documents.

    In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

    -
    $('div.demo-container').html();
    +
    
    +$( "div.demo-container" ).html();
    +      

    In order for the following <div>'s content to be retrieved, it would have to be the first one with class="demo-container" in the document:

    -
    <div class="demo-container">
    +      
    
    +<div class="demo-container">
       <div class="demo-box">Demonstration Box</div>
    -  </div>
    +</div> +

    The result would look like this:

    -
    <div class="demo-box">Demonstration Box</div>
    +
    
    +<div class="demo-box">Demonstration Box</div>
    +      

    This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

    + Click a paragraph to convert it from html to text. - + p { + margin: 8px; + font-size: 20px; + color: blue; + cursor: pointer; + } + b { + text-decoration: underline; + } + button { + cursor: pointer; + } +]]> + @@ -57,7 +74,10 @@ $("p").click(function () { 1.4 - + + + + A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; @@ -74,49 +94,70 @@ $("p").click(function () { handlers from child elements before replacing those elements with the new content.

    Consider the following HTML:

    -
    <div class="demo-container">
    +      
    
    +<div class="demo-container">
       <div class="demo-box">Demonstration Box</div>
    -</div>
    +</div> +

    The content of <div class="demo-container"> can be set like this:

    -
    $('div.demo-container')
    -  .html('<p>All new content. <em>You bet!</em></p>');
    +
    
    +$( "div.demo-container" )
    +  .html( "<p>All new content. <em>You bet!</em></p>" );
    +      

    That line of code will replace everything inside <div class="demo-container">:

    -
    <div class="demo-container">
    +      
    
    +<div class="demo-container">
       <p>All new content. <em>You bet!</em></p>
    -</div>
    +</div> +

    As of jQuery 1.4, the .html() method allows the HTML content to be set by passing in a function.

    -
    $('div.demo-container').html(function() {
    -  var emph = '<em>' + $('p').length + ' paragraphs!</em>';
    -  return '<p>All new content for ' + emph + '</p>';
    -});
    +
    
    +$( "div.demo-container" ).html(function() {
    +  var emphasis = "<em>" + $( "p" ).length + " paragraphs!</em>";
    +  return "<p>All new content for " + emphasis + "</p>";
    +});
    +      

    Given a document with six paragraphs, this example will set the HTML of <div class="demo-container"> to <p>All new content for <em>6 paragraphs!</em></p>.

    -

    This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

    -

    Note: In Internet Explorer up to and including version 9, setting the text content of an HTML element may corrupt the text nodes of its children that are being removed from the document as a result of the operation. If you are keeping references to these DOM elements and need them to be unchanged, use .empty().html(string) instead of .html(string) so that the elements are removed from the document before the new string is assigned to the element.

    +

    This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

    +

    To set the content of a <script> element, which does not contain HTML, use the .text() method and not .html().

    +

    Note: In Internet Explorer up to and including version 9, setting the text content of an HTML element may corrupt the text nodes of its children that are being removed from the document as a result of the operation. If you are keeping references to these DOM elements and need them to be unchanged, use .empty().html( string ) instead of .html(string) so that the elements are removed from the document before the new string is assigned to the element.

    Add some html to each div. - + - + .red { + color: red; + } +]]> + Add some html to each div then immediately do further manipulations to the inserted html. - + div { + color: blue; + font-size: 18px; + } +]]> + diff --git a/entries/id-selector.xml b/entries/id-selector.xml index 988c356c7..3cc8b926c 100644 --- a/entries/id-selector.xml +++ b/entries/id-selector.xml @@ -11,45 +11,49 @@ Selects a single element with the given id attribute.

    For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector, such as h2#pageTitle, jQuery performs an additional check before identifying the element as a match.

    -
    -

    As always, remember that as a developer, your time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved.

    -
    +

    Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

    Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

    -

    If the id contains characters like periods or colons you have to escape those characters with backslashes.

    +

    If the id contains characters like periods or colons you have to escape those characters with backslashes.

    - Finds the element with the id "myDiv". - - + Select the element with the id "myDiv" and give it a red border. + + +]]> - Finds the element with the id "myID.entry[1]". See how certain characters must be escaped with backslashes. - - id="myID.entry[0]" - -
    id="myID.entry[1]"
    -
    id="myID.entry[2]"
    ]]> + Select the element with the id "myID.entry[1]" and give it a red border. Note how certain characters must be escaped with backslashes. + + id="myID.entry[0]" +
    id="myID.entry[1]"
    +
    id="myID.entry[2]"
    +]]> +]]>
    diff --git a/entries/image-selector.xml b/entries/image-selector.xml index 28dc1e47a..2b569d3a8 100644 --- a/entries/image-selector.xml +++ b/entries/image-selector.xml @@ -13,37 +13,44 @@ Finds all image inputs. - + +
    +]]>
    -
    \ No newline at end of file + diff --git a/entries/index.xml b/entries/index.xml index acde75f62..1db070aa0 100644 --- a/entries/index.xml +++ b/entries/index.xml @@ -1,5 +1,5 @@ - + .index() 1.4 @@ -32,127 +32,180 @@ <li id="bar">bar</li> <li id="baz">baz</li> </ul> -
    +

    If we retrieve one of the three list items (for example, through a DOM function or as the context to an event handler), .index() can search for this list item within the set of matched elements:

    
    -var listItem = document.getElementById('bar');
    -alert('Index: ' + $('li').index(listItem));
    -We get back the zero-based position of the list item:
    -
    +var listItem = document.getElementById( "bar" ); +alert( "Index: " + $( "li" ).index( listItem ) ); + +

    We get back the zero-based position of the list item:

    - Index: 1 + Index: 1

    Similarly, if we retrieve a jQuery object consisting of one of the three list items, .index() will search for that list item:

    
    -var listItem = $('#bar');
    -alert('Index: ' + $('li').index(listItem));
    -
    +var listItem = $( "#bar" ); +alert( "Index: " + $( "li" ).index( listItem ) ); +

    We get back the zero-based position of the list item:

    - Index: 1 + Index: 1

    Note that if the jQuery collection used as the .index() method's argument contains more than one element, the first element within the matched set of elements will be used.

    
    -var listItems = $('li:gt(0)');
    -alert('Index: ' + $('li').index(listItems));
    -
    +var listItems = $( "li" ).slice( 1 ); +alert( "Index: " + $( "li" ).index( listItems ) ); +

    We get back the zero-based position of the first list item within the matched set:

    - Index: 1 + Index: 1

    If we use a string as the .index() method's argument, it is interpreted as a jQuery selector string. The first element among the object's matched elements which also matches this selector is located.

    
    -var listItem = $('#bar');
    -alert('Index: ' + listItem.index('li'));
    -
    +var listItem = $( "#bar" ); +alert( "Index: " + listItem.index( "li" ) ); +

    We get back the zero-based position of the list item:

    - Index: 1 + Index: 1

    If we omit the argument, .index() will return the position of the first element within the set of matched elements in relation to its siblings:

    -
    alert('Index: ' + $('#bar').index());
    +
    
    +alert( "Index: " + $( "#bar" ).index() );
    +    

    Again, we get back the zero-based position of the list item:

    - Index: 1 + Index: 1

    - On click, returns the index (based zero) of that div in the page. + On click, returns the index (zero-based) of that div in the page. - +
    Third div
    +]]>
    Returns the index for the element with ID bar. - div { font-weight: bold; color: #090; } - - + + +
    +]]>
    Returns the index for the first item in the jQuery collection. - div { font-weight: bold; color: #090; } - + - +
    +]]>
    Returns the index for the element with ID bar in relation to all <li> elements. - div { font-weight: bold; color: #090; } - - + + +
    +]]>
    Returns the index for the element with ID bar in relation to its siblings. - div { font-weight: bold; color: #090; } - - + + +
    +]]>
    Returns -1, as there is no element with ID foobar. - div { font-weight: bold; color: #090; } - - + + +
    +]]>
    diff --git a/entries/innerHeight.xml b/entries/innerHeight.xml index 497015f0b..2f71ae9f9 100644 --- a/entries/innerHeight.xml +++ b/entries/innerHeight.xml @@ -1,26 +1,109 @@ - + + Get the current computed inner height (including padding but not border) for the first element in the set of matched elements or set the inner height of every matched element. + + .innerHeight() 1.2.6 Get the current computed height for the first element in the set of matched elements, including padding but not border. -

    This method returns the height of the element, including top and bottom padding, in pixels.

    -

    This method is not applicable to window and document objects; for these, use .height() instead.

    -

    +

    This method returns the height of the element, including top and bottom padding, in pixels. If called on an empty set of elements, returns undefined (null before jQuery 3.0).

    +

    This method is not applicable to window and document objects; for these, use .height() instead.

    +
    -

    +
    Figure 1 - Illustration of the measured height
    +
    + + Get the innerHeight of a paragraph. - - - + + + -
    \ No newline at end of file +
    + + + + 1.8 + + + + A number representing the number of pixels, or a number along with an optional unit of measure appended (as a string). + + + + 1.8 + + + + + + + + A function returning the inner height (including padding but not border) to set. Receives the index position of the element in the set and the old inner height as arguments. Within the function, this refers to the current element in the set. + + +Set the CSS inner height of each element in the set of matched elements. + +

    When calling .innerHeight("value"), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the height (such as 100px, 50%, or auto). Note that in modern browsers, the CSS height property does not include padding, border, or margin, unless the box-sizing CSS property is used.

    +

    If no explicit unit is specified (like "em" or "%") then "px" is assumed.

    +
    + + Change the inner height of each div the first time it is clicked (and change its color). + + + + + + + + +
    + +
    diff --git a/entries/innerWidth.xml b/entries/innerWidth.xml index c2561360a..54b6b3588 100644 --- a/entries/innerWidth.xml +++ b/entries/innerWidth.xml @@ -1,26 +1,107 @@ - + + Get the current computed inner width (including padding but not border) for the first element in the set of matched elements or set the inner width of every matched element. + .innerWidth() 1.2.6 - Get the current computed width for the first element in the set of matched elements, including padding but not border. + Get the current computed inner width for the first element in the set of matched elements, including padding but not border. -

    This method returns the width of the element, including left and right padding, in pixels.

    -

    This method is not applicable to window and document objects; for these, use .width() instead.

    -

    +

    This method returns the width of the element, including left and right padding, in pixels. If called on an empty set of elements, returns undefined (null before jQuery 3.0).

    +

    This method is not applicable to window and document objects; for these, use .width() instead.

    +
    -

    +
    Figure 1 - Illustration of the measured width
    +
    + + Get the innerWidth of a paragraph. - - - + + + -
    \ No newline at end of file +
    + + + + 1.8 + + + + A number representing the number of pixels, or a number along with an optional unit of measure appended (as a string). + + + + 1.8 + + + + + + + + A function returning the inner width (including padding but not border) to set. Receives the index position of the element in the set and the old inner width as arguments. Within the function, this refers to the current element in the set. + + +Set the CSS inner width of each element in the set of matched elements. + +

    When calling .innerWidth("value"), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the width (such as 100px, 50%, or auto). Note that in modern browsers, the CSS width property does not include padding, border, or margin, unless the box-sizing CSS property is used.

    +

    If no explicit unit is specified (like "em" or "%") then "px" is assumed.

    +
    + + Change the inner width of each div the first time it is clicked (and change its color). + + + + + + + + +
    + diff --git a/entries/input-selector.xml b/entries/input-selector.xml index 069949e99..ec5c6c23d 100644 --- a/entries/input-selector.xml +++ b/entries/input-selector.xml @@ -13,41 +13,42 @@ Finds all input elements. - + - \ No newline at end of file + diff --git a/entries/insertAfter.xml b/entries/insertAfter.xml index ec9e832de..8c406cfa0 100644 --- a/entries/insertAfter.xml +++ b/entries/insertAfter.xml @@ -4,49 +4,70 @@ 1.0 - A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + Insert every element in the set of matched elements after the target. -

    The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

    +

    The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

    Consider the following HTML:

    -
    <div class="container">
    +    
    
    +<div class="container">
       <h2>Greetings</h2>
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
    -</div>
    +</div> +

    We can create content and insert it after several elements at once:

    -
    $('<p>Test</p>').insertAfter('.inner');
    +
    
    +$( "<p>Test</p>" ).insertAfter( ".inner" );
    +    

    Each inner <div> element gets this new content:

    -
    <div class="container">
    +    
    
    +<div class="container">
       <h2>Greetings</h2>
       <div class="inner">Hello</div>
       <p>Test</p>
       <div class="inner">Goodbye</div>
       <p>Test</p>
    -</div>
    +</div> +

    We can also select an element on the page and insert it after another:

    -
    $('h2').insertAfter($('.container'));
    -

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved after the target (not cloned):

    -
    <div class="container">
    +    
    
    +$( "h2" ).insertAfter( $( ".container" ) );
    +    
    +

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved after the target (not cloned) and a new set consisting of the inserted element is returned:

    +
    
    +<div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
     </div>
    -<h2>Greetings</h2>
    +<h2>Greetings</h2> +

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

    +

    Before jQuery 1.9, the append-to-single-element case did not create a new set, but instead returned the original set which made it difficult to use the .end() method reliably when being used with an unknown number of elements.

    + + - Insert all paragraphs after an element with id of "foo". Same as $("#foo").after("p") + Insert all paragraphs after an element with id of "foo". Same as $( "#foo" ).after( "p" ) - - + + diff --git a/entries/insertBefore.xml b/entries/insertBefore.xml index 94fd3d742..21801192d 100644 --- a/entries/insertBefore.xml +++ b/entries/insertBefore.xml @@ -4,49 +4,70 @@ 1.0 - A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + Insert every element in the set of matched elements before the target. -

    The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .before(), the selector expression preceding the method is the container before which the content is inserted. With .insertBefore(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

    +

    The .before() and .insertBefore() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .before(), the selector expression preceding the method is the container before which the content is inserted. With .insertBefore(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

    Consider the following HTML:

    -
    <div class="container">
    +    
    
    +<div class="container">
       <h2>Greetings</h2>
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
    -</div>
    +</div> +

    We can create content and insert it before several elements at once:

    -
    $('<p>Test</p>').insertBefore('.inner');
    +
    
    +$( "<p>Test</p>" ).insertBefore( ".inner" );
    +    

    Each inner <div> element gets this new content:

    -
    <div class="container">
    +    
    
    +<div class="container">
       <h2>Greetings</h2>
       <p>Test</p>
       <div class="inner">Hello</div>
       <p>Test</p>
       <div class="inner">Goodbye</div>
    -</div>
    +</div> +

    We can also select an element on the page and insert it before another:

    -
    $('h2').insertBefore($('.container'));
    -

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned):

    -
    <h2>Greetings</h2>
    +    
    
    +$( "h2" ).insertBefore( $( ".container" ) );
    +    
    +

    If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned) and a new set consisting of the inserted element is returned:

    +
    
    +<h2>Greetings</h2>
     <div class="container">
       <div class="inner">Hello</div>
       <div class="inner">Goodbye</div>
    -</div>
    +</div> +

    If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.

    +

    Before jQuery 1.9, the append-to-single-element case did not create a new set, but instead returned the original set which made it difficult to use the .end() method reliably when being used with an unknown number of elements.

    + + - Insert all paragraphs before an element with id of "foo". Same as $("#foo").before("p") + Insert all paragraphs before an element with id of "foo". Same as $( "#foo" ).before( "p" ) - - + + diff --git a/entries/is.xml b/entries/is.xml index f502f00da..e6eb2ce55 100644 --- a/entries/is.xml +++ b/entries/is.xml @@ -9,20 +9,23 @@ 1.6 - - A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + + A function used as a test for every element in the set. It accepts two arguments, index, which is the element's index in the jQuery collection, and element, which is the DOM element. Within the function, this refers to the current DOM element. + + + 1.6 - + An existing jQuery object to match the current set of elements against. 1.6 - - An element to match the current set of elements against. + + One or more elements to match the current set of elements against. Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. @@ -35,18 +38,17 @@ <li><span>list item 2</span></li> <li>list item 3</li> </ul> -
    +

    You can attach a click handler to the <ul> element, and then limit the code to be triggered only when a list item itself, not one of its children, is clicked:

    -
    $("ul").click(function(event) {
    -  var $target = $(event.target);
    -  if ( $target.is("li") ) {
    -    $target.css("background-color", "red");
    +    
    
    +$( "ul" ).on( "click", function( event ) {
    +  var target = $( event.target );
    +  if ( target.is( "li" ) ) {
    +    target.css( "background-color", "red" );
       }
    -});
    -

    Now, when the user clicks on the word "list" in the first item or anywhere in the third item, the clicked list item will be given a red background. However, when the user clicks on item 1 in the first item or anywhere in the second item, nothing will occur, because in those cases the target of the event would be <strong> or <span>, respectively. -

    -

    Prior to jQuery 1.7, in selector strings with positional selectors such as :first, :gt(), or :even, the positional filtering is done against the jQuery object passed to .is(), not against the containing document. So for the HTML shown above, an expression such as $("li:first").is("li:last") returns true, but $("li:first-child").is("li:last-child") returns false. In addition, a bug in Sizzle prevented many positional selectors from working properly. These two factors made positional selectors almost unusable in filters.

    -

    Starting with jQuery 1.7, selector strings with positional selectors apply the selector against the document, and then determine whether the first element of the current jQuery set matches any of the resulting elements. So for the HTML shown above, an expression such as $("li:first").is("li:last") returns false. Note that since positional selectors are jQuery additions and not W3C standard, we recommend using the W3C selectors whenever feasible.

    +}); +
    +

    Now, when the user clicks on the word "list" in the first item or anywhere in the third item, the clicked list item will be given a red background. However, when the user clicks on item 1 in the first item or anywhere in the second item, nothing will occur, because in those cases the target of the event would be <strong> or <span>, respectively.

    Using a Function

    The second form of this method evaluates expressions related to elements based on a function rather than a selector. For each element, if the function returns true, .is() returns true as well. For example, given a somewhat more involved HTML snippet:

    
    @@ -58,120 +60,171 @@
       <li>list item 4</li>
       <li>list item 5</li>
     </ul>
    -
    +

    You can attach a click handler to every <li> that evaluates the number of <strong> elements within the clicked <li> at that time like so:

    
    -$("li").click(function() {
    -  var $li = $(this),
    -    isWithTwo = $li.is(function() {
    -      return $('strong', this).length === 2;
    +$( "li" ).on( "click", function() {
    +  var li = $( this ),
    +    isWithTwo = li.is(function() {
    +      return $( "strong", this ).length === 2;
         });
       if ( isWithTwo ) {
    -    $li.css("background-color", "green");
    +    li.css( "background-color", "green" );
       } else {
    -    $li.css("background-color", "red");
    +    li.css( "background-color", "red" );
       }
     });
    -
    + Shows a few ways is() can be used inside an event handler. - +

     

    +]]>
    Returns true, because the parent of the input is a form element. - - + + Returns false, because the parent of the input is a p element. - - + + Checks against an existing collection of alternating list elements. Blue, alternating list elements slide up while others turn red. - + + +]]> An alternate way to achieve the above example using an element rather than a jQuery object. Checks against an existing collection of alternating list elements. Blue, alternating list elements slide up while others turn red. - + + +]]> diff --git a/entries/jQuery.Callbacks.xml b/entries/jQuery.Callbacks.xml index 7082eaa61..251bc1110 100644 --- a/entries/jQuery.Callbacks.xml +++ b/entries/jQuery.Callbacks.xml @@ -15,47 +15,47 @@

    The following are two sample methods named fn1 and fn2:

    
     function fn1( value ) {
    -    console.log( value );
    +  console.log( value );
     }
     
     function fn2( value ) {
    -    fn1("fn2 says: " + value);
    -    return false;
    +  console.log( "fn2 says: " + value );
    +  return false;
     }
    -
    +

    These can be added as callbacks to a $.Callbacks list and invoked as follows:

    
     var callbacks = $.Callbacks();
     callbacks.add( fn1 );
     
    -// outputs: foo!
    +// Outputs: foo!
     callbacks.fire( "foo!" );
     
     callbacks.add( fn2 );
     
    -// outputs: bar!, fn2 says: bar!
    +// Outputs: bar!, fn2 says: bar!
     callbacks.fire( "bar!" );
    -
    +

    The result of this is that it becomes simple to construct complex lists of callbacks where input values can be passed through to as many functions as needed with ease.

    Two specific methods were being used above: .add() and .fire(). The .add() method supports adding new callbacks to the callback list, while the .fire() method executes the added functions and provides a way to pass arguments to be processed by the callbacks in the same list.

    -

    Another method supported by $.Callbacks is .remove(), which has the ability to remove a particular callback from the callback list. Here"s a practical example of .remove() being used:

    +

    Another method supported by $.Callbacks is .remove(), which has the ability to remove a particular callback from the callback list. Here's a practical example of .remove() being used:

    
     var callbacks = $.Callbacks();
     callbacks.add( fn1 );
     
    -// outputs: foo!
    +// Outputs: foo!
     callbacks.fire( "foo!" );
     
     callbacks.add( fn2 );
     
    -// outputs: bar!, fn2 says: bar!
    +// Outputs: bar!, fn2 says: bar!
     callbacks.fire( "bar!" );
     
     callbacks.remove( fn2 );
     
    -// only outputs foobar, as fn2 has been removed.
    +// Only outputs foobar, as fn2 has been removed.
     callbacks.fire( "foobar" );
    -
    +

    Supported Flags

    The flags argument is an optional argument to $.Callbacks(), structured as a list of space-separated strings that change how the callback list behaves (eg. $.Callbacks( "unique stopOnFalse" )).

    Possible flags:

    @@ -81,9 +81,10 @@ callbacks.fire( "foobar" ); output: foo */ - +

    $.Callbacks( "memory" ):

    -
    var callbacks = $.Callbacks( "memory" );
    +    
    
    +var callbacks = $.Callbacks( "memory" );
     callbacks.add( fn1 );
     callbacks.fire( "foo" );
     callbacks.add( fn2 );
    @@ -99,12 +100,13 @@ bar
     fn2 says:bar
     foobar
     */
    -
    +

    $.Callbacks( "unique" ):

    -
    var callbacks = $.Callbacks( "unique" );
    +    
    
    +var callbacks = $.Callbacks( "unique" );
     callbacks.add( fn1 );
     callbacks.fire( "foo" );
    -callbacks.add( fn1 ); // repeat addition
    +callbacks.add( fn1 ); // Repeat addition
     callbacks.add( fn2 );
     callbacks.fire( "bar" );
     callbacks.remove( fn2 );
    @@ -117,17 +119,17 @@ bar
     fn2 says:bar
     foobar
     */
    -
    +

    $.Callbacks( "stopOnFalse" ):

    
    -function fn1( value ){
    -    console.log( value );
    -    return false;
    +function fn1( value ) {
    +  console.log( value );
    +  return false;
     }
     
    -function fn2( value ){
    -    fn1( "fn2 says: " + value );
    -    return false;
    +function fn2( value ) {
    +  fn1( "fn2 says: " + value );
    +  return false;
     }
     
     var callbacks = $.Callbacks( "stopOnFalse" );
    @@ -144,24 +146,24 @@ foo
     bar
     foobar
     */
    -
    +

    Because $.Callbacks() supports a list of flags rather than just one, setting several flags has a cumulative effect similar to "&&". This means it's possible to combine flags to create callback lists that, say, both are unique and ensure if list was already fired, adding more callbacks will have it called with the latest fired value (i.e. $.Callbacks("unique memory")).

    $.Callbacks( 'unique memory' ):

    
     function fn1( value ) {
    -    console.log( value );
    -    return false;
    +  console.log( value );
    +  return false;
     }
     
     function fn2( value ) {
    -    fn1( "fn2 says: " + value );
    -    return false;
    +  fn1( "fn2 says: " + value );
    +  return false;
     }
     
     var callbacks = $.Callbacks( "unique memory" );
     callbacks.add( fn1 );
     callbacks.fire( "foo" );
    -callbacks.add( fn1 ); // repeat addition
    +callbacks.add( fn1 ); // Repeat addition
     callbacks.add( fn2 );
     callbacks.fire( "bar" );
     callbacks.add( fn2 );
    @@ -184,40 +186,41 @@ foobar
         

    The methods of $.Callbacks can also be detached, should there be a need to define short-hand versions for convenience:

    
     var callbacks = $.Callbacks(),
    -    add = callbacks.add,
    -    remove = callbacks.remove,
    -    fire = callbacks.fire;
    +  add = callbacks.add,
    +  remove = callbacks.remove,
    +  fire = callbacks.fire;
     
     add( fn1 );
     fire( "hello world" );
     remove( fn1 );
    -
    +

    $.Callbacks, $.Deferred and Pub/Sub

    The general idea behind pub/sub (Publish/Subscribe, or, the Observer pattern) is the promotion of loose coupling in applications. Rather than single objects calling on the methods of other objects, an object instead subscribes to a specific task or activity of another object and is notified when it occurs. Observers are also called Subscribers, and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.

    To demonstrate the component-creation capabilities of $.Callbacks(), it's possible to implement a Pub/Sub system using only callback lists. Using $.Callbacks as a topics queue, a system for publishing and subscribing to topics can be implemented as follows:

    -
    var topics = {};
    +    
    
    +var topics = {};
     
     jQuery.Topic = function( id ) {
    -    var callbacks,
    -        method,
    -        topic = id && topics[ id ];
    +  var callbacks, method,
    +    topic = id && topics[ id ];
     
    -    if ( !topic ) {
    -        callbacks = jQuery.Callbacks();
    -        topic = {
    -            publish: callbacks.fire,
    -            subscribe: callbacks.add,
    -            unsubscribe: callbacks.remove
    -        };
    -        if ( id ) {
    -            topics[ id ] = topic;
    -        }
    +  if ( !topic ) {
    +    callbacks = jQuery.Callbacks();
    +    topic = {
    +      publish: callbacks.fire,
    +      subscribe: callbacks.add,
    +      unsubscribe: callbacks.remove
    +    };
    +    if ( id ) {
    +      topics[ id ] = topic;
         }
    -    return topic;
    +  }
    +  return topic;
     };
    -
    +

    This can then be used by parts of your application to publish and subscribe to events of interest quite easily:

    -
    // Subscribers
    +    
    
    +// Subscribers
     $.Topic( "mailArrived" ).subscribe( fn1 );
     $.Topic( "mailArrived" ).subscribe( fn2 );
     $.Topic( "mailSent" ).subscribe( fn1 );
    @@ -237,29 +240,30 @@ hello world!
     fn2 says: hello world!
     woo! mail!
     */
    -
    +

    While this is useful, the implementation can be taken further. Using $.Deferreds, it's possible to ensure publishers only publish notifications for subscribers once particular tasks have been completed (resolved). See the below code sample for some further comments on how this could be used in practice:

    -
    // subscribe to the mailArrived notification
    +    
    
    +// Subscribe to the mailArrived notification
     $.Topic( "mailArrived" ).subscribe( fn1 );
     
    -// create a new instance of Deferreds
    +// Create a new instance of Deferreds
     var dfd = $.Deferred();
     
    -// define a new topic (without directly publishing)
    +// Define a new topic (without directly publishing)
     var topic = $.Topic( "mailArrived" );
     
    -// when the deferred has been resolved, publish a
    +// When the deferred has been resolved, publish a
     // notification to subscribers
     dfd.done( topic.publish );
     
     // Here the Deferred is being resolved with a message
     // that will be passed back to subscribers. It's possible to
     // easily integrate this into a more complex routine
    -// (eg. waiting on an ajax call to complete) so that
    +// (eg. waiting on an Ajax call to complete) so that
     // messages are only published once the task has actually
     // finished.
     dfd.resolve( "it's been published!" );
    -
    +
    diff --git a/entries/jQuery.Deferred.exceptionHook.xml b/entries/jQuery.Deferred.exceptionHook.xml new file mode 100644 index 000000000..db6c3226c --- /dev/null +++ b/entries/jQuery.Deferred.exceptionHook.xml @@ -0,0 +1,34 @@ + + + jQuery.Deferred.exceptionHook() + + 3.0 + + Handle errors produced by Deferreds. + +

    This API is called every time an error is thrown inside Deferreds. By default, it only warns about errors that are more likely to be programmer errors than errors thrown due to application logic. This includes errors like SyntaxError or ReferenceError.

    +

    The function accepts two parameters - the first one is the error thrown and the second, optional parameter is a "fake" error created before the handler is called so that a stack trace from before an async barrier is available. This second error is only provided if jQuery.Deferred.getErrorHook is defined; see the docs for that API for more details.

    +

    Example

    +
    +
    + + +
    diff --git a/entries/jQuery.Deferred.getErrorHook.xml b/entries/jQuery.Deferred.getErrorHook.xml new file mode 100644 index 000000000..b20f98e8e --- /dev/null +++ b/entries/jQuery.Deferred.getErrorHook.xml @@ -0,0 +1,29 @@ + + + jQuery.Deferred.getErrorHook() + + 3.7 + + Return an Error instance with a defined stack. + +
    +

    Note: This API is not defined by default, but jQuery will make use of it when defined.

    +
    +

    When jQuery.Deferred.getErrorHook is defined, it extends the jQuery.Deferred features added in jQuery 3.0 to include an error captured before the async barrier whenever a Deferred throws an exception. This makes it easier to find programming errors that occur inside Deferreds. You can find an example implementation you can copy-paste below, or you can use jquery-deferred-reporter plugin.

    +
    
    +jQuery.Deferred.getErrorHook = function() {
    +  try {
    +    throw new Error( "Exception in jQuery.Deferred" );
    +  } catch ( err ) {
    +    return err;
    +  }
    +};
    +    
    +

    When defined, an error returned by this API is passed to jQuery.Deferred.exceptionHook as the second parameter.

    +

    Why does this API exist?

    +

    Prior to jQuery 3.0, Deferreds would simply terminate and the browser would generate a message on the console if an exception occurred such as attempting to call an undefined method as a function (e.g., myobject.missingFunction()). As of version 3.0, jQuery.Deferred follows the Promise/A+ specification when you use the .then method. The spec requires all errors to be trapped by the Promise, which prevents console errors from being logged. If the user has forgotten to add a handler for rejected promises, this can result in the error being silently swallowed with no notification at all!

    +

    The native Promise object as implemented in the browser tracks Promise rejections and reports problems on the console. However, doing the same type of reporting in the JavaScript world is much more difficult. jQuery itself is unable to use the native Promise because jQuery.Deferred implements a superset of Promise that requires additional features for methods like .done or .fail, and because Promise is not implemented on all the platforms that jQuery supports.

    +
    + + +
    diff --git a/entries/jQuery.Deferred.getStackHook.xml b/entries/jQuery.Deferred.getStackHook.xml new file mode 100644 index 000000000..87ee61387 --- /dev/null +++ b/entries/jQuery.Deferred.getStackHook.xml @@ -0,0 +1,30 @@ + + + jQuery.Deferred.getStackHook() + + 3.0 + + Return an Error instance with a defined stack. + +
    +

    Note: This API has been deprecated in jQuery 3.7; please use the jQuery.Deferred.getErrorHook method instead.

    +
    +
    +

    Note: This API is not defined by default, but jQuery will make use of it when defined.

    +
    +

    See jQuery.Deferred.getErrorHook for the context why this API was created. Initially, we advised users to assign to it a function returning an error stack:

    +
    
    +jQuery.Deferred.getStackHook = function() {
    +  try {
    +    throw new Error( "Exception in jQuery.Deferred" );
    +  } catch ( err ) {
    +    return err.stack; // stack property returned here
    +  }
    +};
    +    
    +

    However, when such a stack is then logged by jQuery from inside of jQuery.Deferred.exceptionHook, the browser won't apply source maps. Therefore, we changed the recommendation to return the full error object itself. To make it clearer, the API was also renamed.

    +
    + + + +
    diff --git a/entries/jQuery.Deferred.xml b/entries/jQuery.Deferred.xml index 3b8885031..2884ad879 100644 --- a/entries/jQuery.Deferred.xml +++ b/entries/jQuery.Deferred.xml @@ -14,18 +14,18 @@ - A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. -

    The jQuery.Deferred() constructor creates a new Deferred object. The new operator is optional.

    -

    The jQuery.Deferred method can be passed an optional function, which is called just before the constructor returns and is passed the constructed deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred.then(), for example.

    -

    A Deferred object starts in the pending state. Any callbacks added to the object with deferred.then(), deferred.always(), deferred.done(), or deferred.fail() are queued to be executed later. Calling deferred.resolve() or deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any doneCallbacks that are set. Calling deferred.reject() or deferred.rejectWith() transitions the Deferred into the rejected state and immediately executes any failCallbacks that are set. Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.

    +

    The jQuery.Deferred() factory creates a new deferred object.

    +

    The jQuery.Deferred method can be passed an optional function, which is called just before the method returns and is passed the new deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred.then(), for example.

    +

    A Deferred object starts in the pending state. Any callbacks added to the object with deferred.then(), deferred.always(), deferred.done(), or deferred.fail() are queued to be executed later. Calling deferred.resolve() or deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any doneCallbacks that are set. Calling deferred.reject() or deferred.rejectWith() transitions the Deferred into the rejected state and immediately executes any failCallbacks that are set. Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.

    Enhanced Callbacks with jQuery Deferred

    In JavaScript it is common to invoke functions that optionally accept callbacks that are called within that function. For example, in versions prior to jQuery 1.5, asynchronous processes such as jQuery.ajax() accept callbacks to be invoked some time in the near-future upon success, error, and completion of the ajax request.

    jQuery.Deferred() introduces several enhancements to the way callbacks are managed and invoked. In particular, jQuery.Deferred() provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred. jQuery Deferred is based on the CommonJS Promises/A design.

    -

    One model for understanding Deferred is to think of it as a chain-aware function wrapper. The deferred.then(), deferred.always(), deferred.done(), and deferred.fail() methods specify the functions to be called and the deferred.resolve(args) or deferred.reject(args) methods "call" the functions with the arguments you supply. Once the Deferred has been resolved or rejected it stays in that state; a second call to deferred.resolve(), for example, is ignored. If more functions are added by deferred.then(), for example, after the Deferred is resolved, they are called immediately with the arguments previously provided.

    -

    In most cases where a jQuery API call returns a Deferred or Deferred-compatible object, such as jQuery.ajax() or jQuery.when(), you will only want to use the deferred.then(), deferred.done(), and deferred.fail() methods to add callbacks to the Deferred's queues. The internals of the API call or code that created the Deferred will invoke deferred.resolve() or deferred.reject() on the deferred at some point, causing the appropriate callbacks to run.

    +

    One model for understanding Deferred is to think of it as a chain-aware function wrapper. The deferred.then(), deferred.always(), deferred.done(), and deferred.fail() methods specify the functions to be called and the deferred.resolve(args) or deferred.reject(args) methods "call" the functions with the arguments you supply. Once the Deferred has been resolved or rejected it stays in that state; a second call to deferred.resolve(), for example, is ignored. If more functions are added by deferred.then(), for example, after the Deferred is resolved, they are called immediately with the arguments previously provided.

    +

    In most cases where a jQuery API call returns a Deferred or Promise-compatible object, such as jQuery.ajax() or jQuery.when(), you will only want to use the deferred.then(), deferred.done(), and deferred.fail() methods to add callbacks to the Deferred's queues. The internals of the API call or code that created the Deferred will invoke deferred.resolve() or deferred.reject() on the deferred at some point, causing the appropriate callbacks to run.

    diff --git a/entries/jQuery.ajax.xml b/entries/jQuery.ajax.xml index 21737bc8c..9074388b9 100644 --- a/entries/jQuery.ajax.xml +++ b/entries/jQuery.ajax.xml @@ -8,23 +8,43 @@ A string containing the URL to which the request is sent. - A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. + A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. 1.0 - A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - - The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + + A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return. For example, the following defines a custom type mycustomtype to be sent with the request: +
    
    +$.ajax({
    +  accepts: {
    +    mycustomtype: 'application/x-some-custom-type'
    +  },
    +
    +  // Instructions for how to deserialize a `mycustomtype`
    +  converters: {
    +    'text mycustomtype': function(result) {
    +      // Do Stuff
    +      return newresult;
    +    }
    +  },
    +
    +  // Expect a `mycustomtype` back from server
    +  dataType: 'mycustomtype'
    +});
    +          
    + Note: You will need to specify a complementary entry for this type in converters for this to work properly. +
    - By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). + By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). - A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. + A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. @@ -32,21 +52,27 @@ - A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. - - When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side. + + + + When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server. - This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:
    $.ajax({
    +        This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example,  specifying a DOM element as the context will make that the context for the complete callback of a request, like so:
    +          
    
    +$.ajax({
       url: "test.html",
       context: document.body
     }).done(function() {
    -  $(this).addClass("done");
    -});
    + $( this ).addClass( "done" ); +}); +
    +
    An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. @@ -57,199 +83,243 @@ - Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). + + +

    Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.

    +

    When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

    +

    When data is passed as a string it should already be encoded using the correct encoding for contentType, which by default is application/x-www-form-urlencoded.

    +

    In requests with dataType: "json" or dataType: "jsonp", if the string contains a double question mark (??) anywhere in the URL or a single question mark (?) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745).

    +
    - - A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. + + A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are: -
    • "xml": Returns a XML document that can be processed via jQuery.
    • "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    • "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
    • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
    • "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
    • "text": A plain text string.
    • multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml. -
    +
      +
    • "xml": Returns a XML document that can be processed via jQuery.
    • +
    • "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    • +
    • "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests. Prior to jQuery 3.5.0, unsuccessful HTTP responses with a script Content-Type were still executed.
    • +
    • "json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests that have a callback placeholder, e.g. ?callback=?, are performed using JSONP unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
    • +
    • "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
    • +
    • "text": A plain text string.
    • +
    • multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
    • +
    +
    - A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event. + A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." (in HTTP/2 it may instead be an empty string) As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain scripts and cross-domain JSONP requests. This is an Ajax Event. - Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. + Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. - An object of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function. + An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. - Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. - - Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } + + + + Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons. - Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + + + The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). A mime type to override the XHR mime type. - A password to be used in response to an HTTP access authentication request. + A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + + + Defines an object with additional attributes to be used in a "script" or "jsonp" request. The key represents the name of the attribute and the value is the attribute's value. If this object is provided it will force the use of a script-tag transport. For example, this can be used to set nonce, integrity, or crossorigin attributes to satisfy Content Security Policy requirements. - Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. + Only applies when the "script" transport is used. Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. Alternatively, the charset attribute can be specified in scriptAttrs instead, which will also ensure the use of the "script" transport.

    An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

    -
    $.ajax({
    +          
    
    +$.ajax({
       statusCode: {
         404: function() {
    -      alert("page not found");
    +      alert( "page not found" );
         }
       }
    -});
    -

    If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.

    +}); +
    +

    If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.

    - + - A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. - Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. + Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. - Set this to true if you wish to use the traditional style of param serialization. + Set this to true if you wish to use the traditional style of param serialization. - The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. + An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0. A string containing the URL to which the request is sent. - A username to be used in response to an HTTP access authentication request. + A username to be used with XMLHttpRequest in response to an HTTP access authentication request. Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. -

    An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. -

    $.ajax({
    +          

    An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

    +
    
    +$.ajax({
        url: a_cross_domain_url,
        xhrFields: {
           withCredentials: true
        }
    -});
    -

    In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. -

    -

    +}); +
    +

    In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.

    Perform an asynchronous HTTP (Ajax) request. -

    The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.

    +

    The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.

    At its simplest, the $.ajax() function can be called with no arguments:

    -
    $.ajax();
    -

    Note: Default settings can be set globally by using the $.ajaxSetup() function.

    +
    
    +$.ajax();
    +    
    +

    Note: Default settings can be set globally by using the $.ajaxSetup() function.

    This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.

    The jqXHR Object

    The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

    As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:

    
     $.ajax({
    -  url: "http://fiddle.jshell.net/favicon.png",
    -  beforeSend: function ( xhr ) {
    -    xhr.overrideMimeType("text/plain; charset=x-user-defined");
    -  }
    -}).done(function ( data ) {
    -  if( console && console.log ) {
    -    console.log("Sample of data:", data.slice(0, 100));
    +  url: "https://fiddle.jshell.net/favicon.png",
    +  beforeSend: function( xhr ) {
    +    xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
       }
    -});
    -
    -

    The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

    +}) + .done(function( data ) { + if ( console && console.log ) { + console.log( "Sample of data:", data.slice( 0, 100 ) ); + } + }); + +

    The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

    • - jqXHR.done(function(data, textStatus, jqXHR) {}); -

      An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

      + jqXHR.done(function( data, textStatus, jqXHR ) {}); +

      An alternative construct to the success callback option, refer to deferred.done() for implementation details.

    • - jqXHR.fail(function(jqXHR, textStatus, errorThrown) {}); + jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

      An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

    • - jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { }); + jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (added in jQuery 1.6)

      An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

      In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

    • - jqXHR.then(function(data, textStatus, jqXHR) {}, function(jqXHR, textStatus, errorThrown) {}); + jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

      Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

    -
    -

    Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    -
    -
    // Assign handlers immediately after making the request,
    -// and remember the jqxhr object for this request
    +    
    +

    Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    +
    +
    
    +// Assign handlers immediately after making the request,
    +// and remember the jqXHR object for this request
     var jqxhr = $.ajax( "example.php" )
    -    .done(function() { alert("success"); })
    -    .fail(function() { alert("error"); })
    -    .always(function() { alert("complete"); });
    +  .done(function() {
    +    alert( "success" );
    +  })
    +  .fail(function() {
    +    alert( "error" );
    +  })
    +  .always(function() {
    +    alert( "complete" );
    +  });
     
    -// perform other work here ...
    +// Perform other work here ...
     
     // Set another completion function for the request above
    -jqxhr.always(function() { alert("second complete"); });
    +jqxhr.always(function() { + alert( "second complete" ); +}); +

    The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

    For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

    • readyState
    • +
    • + responseXML and/or responseText when the underlying request responded with xml and/or text, respectively +
    • status
    • - statusText + statusText (may be an empty string in HTTP/2)
    • -
    • responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
    • -
    • setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
    • - getAllResponseHeaders() + abort( [ statusText ] )
    • - getResponseHeader() + getAllResponseHeaders() as a string
    • - statusCode() + getResponseHeader( name )
    • - abort() + overrideMimeType( mimeType ) +
    • +
    • + setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one +
    • +
    • + statusCode( callbacksByStatusCode )

    No onreadystatechange mechanism is provided, however, since done, fail, always, and statusCode cover all conceivable requirements.

    Callback Function Queues

    The beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.

    -

    As of jQuery 1.5, the fail and done, and, as of jQuery 1.6, always callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax() callback hooks.

    +

    As of jQuery 1.5, the fail and done, and, as of jQuery 1.6, always callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax() callback hooks.

    The callback hooks provided by $.ajax() are as follows:

    1. beforeSend callback option is invoked; it receives the jqXHR object and the settings object as parameters.
    2. @@ -261,79 +331,45 @@ jqxhr.always(function() { alert("second complete"); });

    Data Types

    -

    The $.ajax() function relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected, such as HTML in the example above, the data is treated as text.

    -

    Different data handling can be achieved by using the dataType option. Besides plain xml, the dataType can be html, json, jsonp, script, or text.

    -

    The text and xml types return the data with no processing. The data is simply passed on to the success handler, either through the responseText or responseXML property of the jqXHR object, respectively.

    -

    Note: We must ensure that the MIME type reported by the web server matches our choice of dataType. In particular, XML must be declared by the server as text/xml or application/xml for consistent results.

    -

    If html is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, script will execute the JavaScript that is pulled back from the server, then return nothing.

    -

    The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor. Malformed JSON data will throw a parse error (see json.org for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the jsonp type instead.

    -

    The jsonp type appends a query string parameter of callback=? to the URL. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than callback with the jsonp option to $.ajax().

    -

    Note: JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. More information about it can be found in the original post detailing its use.

    -

    When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.

    +

    Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.

    +

    The available data types are text, html, xml, json, jsonp, and script.

    +

    If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

    +

    If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument, to the success handler. The XML document is made available through the responseXML property of the jqXHR object.

    +

    If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

    +

    If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.

    +

    If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.

    +

    For more information on JSONP, see the original post detailing its use.

    Sending Data to the Server

    By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

    -

    The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

    +

    The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

    Advanced Options

    -

    The global option prevents handlers registered using .ajaxSend(), .ajaxError(), and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend() if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false. See the descriptions of these methods below for more details. See the descriptions of these methods below for more details.

    +

    The global option prevents handlers registered for the ajaxSend, ajaxError, and similar events from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with an ajaxSend handler if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false. See the descriptions of these methods below for more details.

    If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.

    -

    Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.

    +

    Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.

    By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false. To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true.

    The scriptCharset allows the character set to be explicitly specified for requests that use a <script> tag (that is, a type of script or jsonp). This is useful if the script and host page have differing character sets.

    The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

    The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort() on the object will halt the request before it completes.

    -

    At present, due to a bug in Firefox where .getAllResponseHeaders() returns the empty string although .getResponseHeader('Content-Type') returns a non-empty string, automatically decoding JSON CORS responses in Firefox with jQuery is not supported.

    -

    A workaround to this is possible by overriding jQuery.ajaxSettings.xhr as follows:

    -
    
    -(function () {
    -  var _super = jQuery.ajaxSettings.xhr,
    -    xhrCorsHeaders = [ "Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma" ];
    -
    -  jQuery.ajaxSettings.xhr = function () {
    -    var xhr = _super(),
    -      getAllResponseHeaders = xhr.getAllResponseHeaders;
    -
    -    xhr.getAllResponseHeaders = function () {
    -      var allHeaders = "";
    -      try {
    -        allHeaders = getAllResponseHeaders.apply( xhr );
    -        if ( allHeaders ) {
    -          return allHeaders;
    -        }
    -      } catch ( e ) {
    -      }
    -
    -      $.each( xhrCorsHeaders, function ( i, headerName ) {
    -        if ( xhr.getResponseHeader( headerName ) ) {
    -          allHeaders += headerName + ": " + xhr.getResponseHeader( headerName ) + "\n";
    -        }
    -      });
    -      return allHeaders;
    -    };
    -
    -    return xhr;
    -  };
    -})();
    -

    Extending Ajax

    As of jQuery 1.5, jQuery's Ajax implementation includes prefilters, transports, and converters that allow you to extend Ajax with a great deal of flexibility.

    Using Converters

    -

    $.ajax() converters support mapping data types to other data types. If, however, you want to map a custom data type to a known type (e.g json), you must add a correspondance between the response Content-Type and the actual data type using the contents option:

    +

    $.ajax() converters support mapping data types to other data types. If, however, you want to map a custom data type to a known type (e.g json), you must add a correspondence between the response Content-Type and the actual data type using the contents option:

    
     $.ajaxSetup({
       contents: {
         mycustomtype: /mycustomtype/
       },
       converters: {
    -    "mycustomtype json": function ( result ) {
    -      // do stuff
    +    "mycustomtype json": function( result ) {
    +      // Do stuff
           return newresult;
         }
       }
     });
    -
    -

    This extra object is necessary because the response Content-Types and data types never have a strict one-to-one correspondance (hence the regular expression).

    + +

    This extra object is necessary because the response Content-Types and data types never have a strict one-to-one correspondence (hence the regular expression).

    To convert from a supported type (e.g text, json) to a custom data type and back again, use another pass-through converter:

    
     $.ajaxSetup({
    @@ -342,76 +378,90 @@ $.ajaxSetup({
       },
       converters: {
         "text mycustomtype": true,
    -    "mycustomtype json": function ( result ) {
    -      // do stuff
    +    "mycustomtype json": function( result ) {
    +      // Do stuff
           return newresult;
         }
       }
     });
    -
    +

    The above now allows passing from text to mycustomtype and then mycustomtype to json.

    Save some data to the server and notify the user once it's complete. - +}) + .done(function( msg ) { + alert( "Data Saved: " + msg ); + }); +]]> Retrieve the latest version of an HTML page. - +}) + .done(function( html ) { + $( "#results" ).append( html ); + }); +]]> Send an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented. - +xmlRequest.done( handleResponse ); +]]> Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user. - +}); +]]> Load and execute a JavaScript file. - +}); +]]> + + diff --git a/entries/jQuery.ajaxPrefilter.xml b/entries/jQuery.ajaxPrefilter.xml index dbeef71cf..708ca8290 100644 --- a/entries/jQuery.ajaxPrefilter.xml +++ b/entries/jQuery.ajaxPrefilter.xml @@ -7,21 +7,24 @@ An optional string containing one or more space-separated dataTypes - + A handler to set default values for future Ajax requests. + + +

    A typical prefilter registration using $.ajaxPrefilter() looks like this:

    
    -$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
    +$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
       // Modify options, control originalOptions, store jqXHR, etc
     });
    -
    +

    where:

    • options are the request options
    • -
    • originalOptions are the options as provided to the ajax method, unmodified and, thus, without defaults from ajaxSettings
    • +
    • originalOptions are the options as provided to the $.ajax() method, unmodified and, thus, without defaults from ajaxSettings
    • jqXHR is the jqXHR object of the request

    Prefilters are a perfect fit when custom options need to be handled. Given the following code, for example, a call to $.ajax() would automatically abort a request to the same URL if the custom abortOnRetry option is set to true:

    @@ -36,22 +39,22 @@ $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { currentRequests[ options.url ] = jqXHR; } }); - -

    Prefilters can also be used to modify existing options. For example, the following proxies cross-domain requests through http://mydomain.net/proxy/:

    + +

    Prefilters can also be used to modify existing options. For example, the following proxies cross-domain requests through https://mydomain.net/proxy/:

    
    -$.ajaxPrefilter( function( options ) {
    +$.ajaxPrefilter(function( options ) {
       if ( options.crossDomain ) {
    -    options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
    +    options.url = "https://mydomain.net/proxy/" + encodeURIComponent( options.url );
         options.crossDomain = false;
       }
     });
    -
    +

    If the optional dataTypes argument is supplied, the prefilter will be only be applied to requests with the indicated dataTypes. For example, the following only applies the given prefilter to JSON and script requests:

    
     $.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
       // Modify options, control originalOptions, store jqXHR, etc
     });
    -
    +

    The $.ajaxPrefilter() method can also redirect a request to another dataType by returning that dataType. For example, the following sets a request as "script" if the URL has some specific properties defined in a custom isActuallyScript() function:

    
     $.ajaxPrefilter(function( options ) {
    @@ -59,7 +62,7 @@ $.ajaxPrefilter(function( options ) {
         return "script";
       }
     });
    -
    +

    This would ensure not only that the request is considered "script" but also that all the prefilters specifically attached to the script dataType would be applied to it.

    diff --git a/entries/jQuery.ajaxSetup.xml b/entries/jQuery.ajaxSetup.xml index 9ec7a6a2c..b0b54447e 100644 --- a/entries/jQuery.ajaxSetup.xml +++ b/entries/jQuery.ajaxSetup.xml @@ -1,5 +1,5 @@ - + jQuery.ajaxSetup() 1.1 @@ -7,33 +7,39 @@ A set of key/value pairs that configure the default Ajax request. All options are optional.
    - Set default values for future Ajax requests. + Set default values for future Ajax requests. Its use is not recommended. -

    For details on the settings available for $.ajaxSetup(), see $.ajax().

    +

    For details on the settings available for $.ajaxSetup(), see $.ajax().

    All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().

    +

    Note: The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

    For example, the following sets a default for the url parameter before pinging the server repeatedly:

    -
    $.ajaxSetup({
    -  url: 'ping.php'
    -});
    +
    
    +$.ajaxSetup({
    +  url: "ping.php"
    +});
    +    

    Now each time an Ajax request is made, the "ping.php" URL will be used automatically:

    -
    $.ajax({
    +    
    
    +$.ajax({
       // url not set here; uses ping.php
    -  data: {'name': 'Dan'}
    -});
    -
    -

    Note: Global callback functions should be set with their respective global Ajax event handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than within the options object for $.ajaxSetup().

    -
    + data: { "name": "Dan" } +}); +
    +
    +

    Note: Global callback functions should be set via .on() with their respective global Ajax events—ajaxStart, ajaxStop, ajaxComplete, ajaxError, ajaxSuccess, ajaxSend—rather than within the options object for $.ajaxSetup().

    +
    Sets the defaults for Ajax requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else. - + - \ No newline at end of file + diff --git a/entries/jQuery.ajaxTransport.xml b/entries/jQuery.ajaxTransport.xml index bbcd2602c..ccc73ce88 100644 --- a/entries/jQuery.ajaxTransport.xml +++ b/entries/jQuery.ajaxTransport.xml @@ -7,8 +7,11 @@ A string identifying the data type to use - + A handler to return the new transport object to use with the data type provided in the first argument. + + + @@ -16,77 +19,68 @@

    Since each request requires its own transport object instance, transports cannot be registered directly. Therefore, you should provide a function that returns a transport instead.

    Transports factories are registered using $.ajaxTransport(). A typical registration looks like this:

    
    -$.ajaxTransport( function( options, originalOptions, jqXHR ) {
    +$.ajaxTransport( dataType, function( options, originalOptions, jqXHR ) {
       if( /* transportCanHandleRequest */ ) {
         return {
           send: function( headers, completeCallback ) {
    -        /* send code */
    +        // Send code
           },
           abort: function() {
    -        /* abort code */
    +        // Abort code
           }
         };
       }
     });
    -
    +

    where:

    • options are the request options
    • -
    • originalOptions are the options as provided to the ajax method, unmodified and, thus, without defaults from ajaxSettings
    • +
    • originalOptions are the options as provided to the $.ajax() method, unmodified and, thus, without defaults from ajaxSettings
    • jqXHR is the jqXHR object of the request
    • headers is an object of (key-value) request headers that the transport can transmit if it supports it
    • -
    • completeCallback is the callback used to notify ajax of the completion of the request
    • +
    • completeCallback is the callback used to notify Ajax of the completion of the request

    completeCallback has the following signature:

    
     function( status, statusText, responses, headers ) {}
    -
    +

    where:

    • status is the HTTP status code of the response, like 200 for a typical success, or 404 for when the resource is not found.
    • statusText is the statusText of the response.
    • -
    • responses (Optional) is An object containing dataType/value that contains the response in all the formats the transport could provide (for instance, a native XMLHttpRequest object would set reponses to { xml: XMLData, text: textData } for a response that is an XML document)
    • +
    • responses (Optional) is An object containing dataType/value that contains the response in all the formats the transport could provide (for instance, a native XMLHttpRequest object would set responses to { xml: XMLData, text: textData } for a response that is an XML document)
    • headers (Optional) is a string containing all the response headers if the transport has access to them (akin to what XMLHttpRequest.getAllResponseHeaders() would provide).

    Just like prefilters, a transport's factory function can be attached to a specific dataType:

    
     $.ajaxTransport( "script", function( options, originalOptions, jqXHR ) {
    -    /* Will only be called for script requests */
    +  // Will only be called for script requests
     });
    -
    +

    The following example shows how a minimal image transport could be implemented:

    
     $.ajaxTransport( "image", function( s ) {
    -
       if ( s.type === "GET" && s.async ) {
    -
         var image;
    -
         return {
    -
           send: function( _ , callback ) {
    -
             image = new Image();
    -
             function done( status ) {
               if ( image ) {
    -            var statusText = ( status == 200 ) ? "success" : "error",
    -            tmp = image;
    +            var statusText = ( status === 200 ) ? "success" : "error",
    +              tmp = image;
                 image = image.onreadystatechange = image.onerror = image.onload = null;
                 callback( status, statusText, { image: tmp } );
               }
             }
    -
             image.onreadystatechange = image.onload = function() {
               done( 200 );
             };
             image.onerror = function() {
               done( 404 );
             };
    -
             image.src = s.url;
           },
    -
           abort: function() {
             if ( image ) {
               image = image.onreadystatechange = image.onerror = image.onload = null;
    @@ -95,34 +89,31 @@ $.ajaxTransport( "image", function( s ) {
         };
       }
     });
    -
    +

    Handling Custom Data Types

    The jQuery Ajax implementation comes with a set of standard dataTypes, such as text, json, xml, and html.

    -

    Use the converters option in $.ajaxSetup() to augment or modify the data type conversion strategies used by $.ajax().

    +

    Use the converters option in $.ajaxSetup() to augment or modify the data type conversion strategies used by $.ajax().

    The unminified jQuery source itself includes a list of default converters, which effectively illustrates how they can be used:

    
     // List of data converters
    -// 1) key format is "source_type destination_type"
    +// 1) Key format is "source_type destination_type"
     //    (a single space in-between)
    -// 2) the catchall symbol "*" can be used for source_type
    +// 2) The catchall symbol "*" can be used for source_type
     converters: {
    -
       // Convert anything to text
       "* text": window.String,
    -
       // Text to html (true = no transformation)
       "text html": true,
    -
       // Evaluate text as a json expression
       "text json": jQuery.parseJSON,
    -
       // Parse text as xml
       "text xml": jQuery.parseXML
     }
    -
    +

    When you specify a converters option globally in $.ajaxSetup() or per call in $.ajax(), the object will map onto the default converters, overwriting those you specify and leaving the others intact.

    For example, the jQuery source uses $.ajaxSetup() to add a converter for "text script":

    -
    jQuery.ajaxSetup({
    +    
    
    +jQuery.ajaxSetup({
       accepts: {
         script: "text/javascript, application/javascript"
       },
    @@ -132,7 +123,8 @@ converters: {
       converters: {
         "text script": jQuery.globalEval
       }
    -});
    +}); +
    diff --git a/entries/jQuery.boxModel.xml b/entries/jQuery.boxModel.xml index f055db0e4..b80abe29a 100644 --- a/entries/jQuery.boxModel.xml +++ b/entries/jQuery.boxModel.xml @@ -1,30 +1,17 @@ - + jQuery.boxModel 1.0 - Deprecated in jQuery 1.3 (see jQuery.support). States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model. - - - Returns the box model for the iframe. - - - - - - Returns false if the page is in Quirks Mode in Internet Explorer - - - + States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model. + +
    +

    Note: This API has been removed in jQuery 3.0; check if .document.compatMode is equal to "CSS1Compat" instead. Or, even better - always specify a DOCTYPE and avoid using quirks mode which jQuery doesn't support.

    +
    +
    + +
    diff --git a/entries/jQuery.browser.xml b/entries/jQuery.browser.xml index b5b36f53e..11686eaec 100644 --- a/entries/jQuery.browser.xml +++ b/entries/jQuery.browser.xml @@ -5,8 +5,11 @@ 1.0 - Contains flags for the useragent, read from navigator.userAgent. We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery. + Contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin. Please try to use feature detection instead. +
    +

    Note: This API has been removed in jQuery 1.9; please rely on feature detection instead.

    +

    The $.browser property provides information about the web browser that is accessing the page, as reported by the browser itself. It contains flags for each of the four most prevalent browser classes (Internet Explorer, Mozilla, Webkit, and Opera) as well as version information.

    Available flags are:

      @@ -18,60 +21,47 @@

    This property is available immediately. It is therefore safe to use it to determine whether or not to call $(document).ready(). The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery.

    -

    Because $.browser uses navigator.userAgent to determine the platform, it is vulnerable to spoofing by the user or misrepresentation by the browser itself. It is always best to avoid browser-specific code entirely where possible. The $.support property is available for detection of support for particular features rather than relying on $.browser.

    +

    Because $.browser uses navigator.userAgent to determine the platform, it is vulnerable to spoofing by the user or misrepresentation by the browser itself. It is always best to avoid browser-specific code entirely where possible. Instead of relying on $.browser it's better to use libraries like Modernizr.

    Show the browser info. - - - Returns true if the current useragent is some version of Microsoft's Internet Explorer. - - Alerts "this is WebKit!" only for WebKit browsers + Return true if the current useragent is some version of Microsoft's Internet Explorer. Will not work in jQuery 1.9 or later unless the jQuery Migrate plugin is included. - Alerts "Do stuff for Firefox 3" only for Firefox 3 browsers. + Alert "this is WebKit!" only for WebKit browsers. Will not work in jQuery 1.9 or later unless the jQuery Migrate plugin is included. - - - Set a CSS property that's specific to a particular browser. - + +
    1.1.3 - The version number of the rendering engine for the user's browser. + The version number of the rendering engine for the user's browser. This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin. +
    +

    Note: This API has been removed in jQuery 1.9; please rely on feature detection instead.

    +

    Here are some typical results:

    • Internet Explorer: 6.0, 7.0, 8.0
    • @@ -82,31 +72,25 @@ jQuery.each(jQuery.browser, function(i, val) {

      Note that IE8 claims to be 7 in Compatibility View.

      - Returns the version number of the rendering engine used by the user's current browser. For example, FireFox 4 returns 2.0 (the version of the Gecko rendering engine it utilizes). + Return the version number of the rendering engine used by the user's current browser. For example, FireFox 4 returns 2.0 (the version of the Gecko rendering engine it utilizes). Will not work in jQuery 1.9 or later unless the jQuery Migrate plugin is included. - Alerts the version of IE's rendering engine that is being used: + Alert the version of IE's rendering engine that is being used. Will not work in jQuery 1.9 or later unless the jQuery Migrate plugin is included. - - - Often you only care about the "major number," the whole number, which you can get by using JavaScript's built-in parseInt() function: - + + diff --git a/entries/jQuery.contains.xml b/entries/jQuery.contains.xml index 45db68c5e..9bf3285f7 100644 --- a/entries/jQuery.contains.xml +++ b/entries/jQuery.contains.xml @@ -13,14 +13,16 @@ Check to see if a DOM element is a descendant of another DOM element.

      The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

      -
      +

      Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

      -
      +
      Check if an element is a descendant of another. - + diff --git a/entries/jQuery.cssHooks.xml b/entries/jQuery.cssHooks.xml index 5098607fb..ec36ccfe1 100644 --- a/entries/jQuery.cssHooks.xml +++ b/entries/jQuery.cssHooks.xml @@ -10,179 +10,172 @@

      For example, some versions of Webkit-based browsers require -webkit-border-radius to set the border-radius on an element, while earlier Firefox versions require -moz-border-radius. A css hook can normalize these vendor-prefixed properties to let .css() accept a single, standard property name (border-radius, or with DOM property syntax, borderRadius).

      In addition to providing fine-grained control over how specific style properties are handled, $.cssHooks also extends the set of properties available to the .animate() method.

      Defining a new css hook is straight-forward. The skeleton template below can serve as a guide to creating your own.

      -
      -      (function($) {
      -  // first, check to see if cssHooks are supported
      -  if ( !$.cssHooks ) {
      -    // if not, output an error message
      -    throw("jQuery 1.4.3 or above is required for this plugin to work");
      -    return;
      -  }
      +    
      
      +(function( $ ) {
      +
      +// First, check to see if cssHooks are supported
      +if ( !$.cssHooks ) {
      +  // If not, output an error message
      +  throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );
      +}
      +
      +// Wrap in a document ready call, because jQuery writes
      +// cssHooks at this time and will blow away your functions
      +// if they exist.
      +$(function () {
      +  $.cssHooks[ "someCSSProp" ] = {
      +    get: function( elem, computed, extra ) {
      +      // Handle getting the CSS property
      +    },
      +    set: function( elem, value ) {
      +      // Handle setting the CSS value
      +    }
      +  };
      +});
       
      -  // Wrap in a document ready call, because jQuery writes
      -  // cssHooks at this time and will blow away your functions
      -  // if they exist.
      -  $(function () {
      -    $.cssHooks["someCSSProp"] = {
      -      get: function( elem, computed, extra ) {
      -        // handle getting the CSS property
      -      },
      -      set: function( elem, value ) {
      -        // handle setting the CSS value
      -      }
      -    };
      -  });
      -})(jQuery);
      -
      -    
      +})( jQuery ); +

      Feature Testing

      Before normalizing a vendor-specific CSS property, first determine whether the browser supports the standard property or a vendor-prefixed variation. For example, to check for support of the border-radius property, see if any variation is a member of a temporary element's style object.

      -
      -      (function($) {
      -  function styleSupport( prop ) {
      -    var vendorProp, supportedProp,
      -
      -        // capitalize first character of the prop to test vendor prefix
      -        capProp = prop.charAt(0).toUpperCase() + prop.slice(1),
      -        prefixes = [ "Moz", "Webkit", "O", "ms" ],
      -        div = document.createElement( "div" );
      -
      -    if ( prop in div.style ) {
      -
      -      // browser supports standard CSS property name
      -      supportedProp = prop;
      -    } else {
      -
      -      // otherwise test support for vendor-prefixed property names
      -      for ( var i = 0; i < prefixes.length; i++ ) {
      -        vendorProp = prefixes[i] + capProp;
      -        if ( vendorProp in div.style ) {
      -          supportedProp = vendorProp;
      -          break;
      -        }
      +    
      
      +(function( $ ) {
      +
      +function styleSupport( prop ) {
      +  var vendorProp, supportedProp,
      +
      +    // Capitalize first character of the prop to test vendor prefix
      +    capProp = prop.charAt( 0 ).toUpperCase() + prop.slice( 1 ),
      +    prefixes = [ "Moz", "Webkit", "ms" ],
      +    div = document.createElement( "div" );
      +
      +  if ( prop in div.style ) {
      +
      +    // Browser supports standard CSS property name
      +    supportedProp = prop;
      +  } else {
      +
      +    // Otherwise test support for vendor-prefixed property names
      +    for ( var i = 0; i < prefixes.length; i++ ) {
      +      vendorProp = prefixes[ i ] + capProp;
      +      if ( vendorProp in div.style ) {
      +        supportedProp = vendorProp;
      +        break;
             }
           }
      +  }
       
      -    // avoid memory leak in IE
      -    div = null;
      +  // Avoid memory leak in IE
      +  div = null;
       
      -    // add property to $.support so it can be accessed elsewhere
      -    $.support[ prop ] = supportedProp;
      +  // Add property to $.support so it can be accessed elsewhere
      +  $.support[ prop ] = supportedProp;
      +  return supportedProp;
      +}
       
      -    return supportedProp;
      -  }
      +// Call the function, e.g. testing for "border-radius" support:
      +styleSupport( "borderRadius" );
       
      -  // call the function, e.g. testing for "border-radius" support:
      -  styleSupport( "borderRadius" );
      -})(jQuery);
      -
      -    
      +})( jQuery ); +

      Defining a complete css hook

      To define a complete css hook, combine the support test with a filled-out version of the skeleton template provided in the first example:

      -
      -      (function($) {
      -  if ( !$.cssHooks ) {
      -    throw("jQuery 1.4.3+ is needed for this plugin to work");
      -    return;
      -  }
      -
      -  function styleSupport( prop ) {
      -    var vendorProp, supportedProp,
      -        capProp = prop.charAt(0).toUpperCase() + prop.slice(1),
      -        prefixes = [ "Moz", "Webkit", "O", "ms" ],
      -        div = document.createElement( "div" );
      -
      -    if ( prop in div.style ) {
      -      supportedProp = prop;
      -    } else {
      -      for ( var i = 0; i < prefixes.length; i++ ) {
      -        vendorProp = prefixes[i] + capProp;
      -        if ( vendorProp in div.style ) {
      -          supportedProp = vendorProp;
      -          break;
      -        }
      +    
      
      +(function( $ ) {
      +
      +if ( !$.cssHooks ) {
      +  throw( new Error( "jQuery 1.4.3+ is needed for this plugin to work" ) );
      +}
      +
      +function styleSupport( prop ) {
      +  var vendorProp, supportedProp,
      +    capProp = prop.charAt( 0 ).toUpperCase() + prop.slice( 1 ),
      +    prefixes = [ "Moz", "Webkit", "ms" ],
      +    div = document.createElement( "div" );
      +
      +  if ( prop in div.style ) {
      +    supportedProp = prop;
      +  } else {
      +    for ( var i = 0; i < prefixes.length; i++ ) {
      +      vendorProp = prefixes[ i ] + capProp;
      +      if ( vendorProp in div.style ) {
      +        supportedProp = vendorProp;
      +        break;
             }
           }
      -
      -    div = null;
      -    $.support[ prop ] = supportedProp
      -    return supportedProp;
         }
       
      -  var borderRadius = styleSupport( "borderRadius" );
      -
      -  // Set cssHooks only for browsers that
      -  // support a vendor-prefixed border radius
      -  if ( borderRadius && borderRadius !== "borderRadius" ) {
      -    $.cssHooks.borderRadius = {
      -      get: function( elem, computed, extra ) {
      -        return $.css( elem, borderRadius );
      -      },
      -      set: function( elem, value) {
      -        elem.style[ borderRadius ] = value;
      -      }
      -    };
      -  }
      -})(jQuery);
      -
      -    
      + div = null; + $.support[ prop ] = supportedProp; + return supportedProp; +} + +var borderRadius = styleSupport( "borderRadius" ); + +// Set cssHooks only for browsers that support a vendor-prefixed border radius +if ( borderRadius && borderRadius !== "borderRadius" ) { + $.cssHooks.borderRadius = { + get: function( elem, computed, extra ) { + return $.css( elem, borderRadius ); + }, + set: function( elem, value) { + elem.style[ borderRadius ] = value; + } + }; +} + +})( jQuery ); +

      You can then set the border radius in a supported browser using either the DOM (camelCased) style or the CSS (hyphenated) style:

      -
      -      
      -$("#element").css("borderRadius", "10px");
      -$("#another").css("border-radius", "20px");
      -
      -    
      +
      
      +$( "#element" ).css( "borderRadius", "10px" );
      +$( "#another" ).css( "border-radius", "20px" );
      +    

      If the browser lacks support for any form of the CSS property, vendor-prefixed or not, the style is not applied to the element. However, if the browser supports a proprietary alternative, it can be applied to the cssHooks instead.

      -
      -      
      - (function($) {
      -  // feature test for support of a CSS property
      -  // and a proprietary alternative
      -  // ...
      -
      -
      - if ( $.support.someCSSProp && $.support.someCSSProp !== "someCSSProp" ) {
      -
      -    // Set cssHooks for browsers that
      -    // support only a vendor-prefixed someCSSProp
      -    $.cssHooks.someCSSProp = {
      -      get: function( elem, computed, extra ) {
      -        return $.css( elem, $.support.someCSSProp );
      -      },
      -      set: function( elem, value) {
      -        elem.style[ $.support.someCSSProp ] = value;
      -      }
      -    };
      -  } else if ( supportsProprietaryAlternative ) {
      -    $.cssHooks.someCSSProp = {
      -      get: function( elem, computed, extra ) {
      -        // Handle crazy conversion from the proprietary alternative
      -      },
      -      set: function( elem, value ) {
      -        // Handle crazy conversion to the proprietary alternative
      -      }
      +    
      
      +(function( $ ) {
      +
      +// Feature test for support of a CSS property
      +// and a proprietary alternative
      +// ...
      +if ( $.support.someCSSProp && $.support.someCSSProp !== "someCSSProp" ) {
      +
      +  // Set cssHooks for browsers that
      +  // support only a vendor-prefixed someCSSProp
      +  $.cssHooks.someCSSProp = {
      +    get: function( elem, computed, extra ) {
      +      return $.css( elem, $.support.someCSSProp );
      +    },
      +    set: function( elem, value) {
      +      elem.style[ $.support.someCSSProp ] = value;
      +    }
      +  };
      +} else if ( supportsProprietaryAlternative ) {
      +  $.cssHooks.someCSSProp = {
      +    get: function( elem, computed, extra ) {
      +      // Handle crazy conversion from the proprietary alternative
      +    },
      +    set: function( elem, value ) {
      +      // Handle crazy conversion to the proprietary alternative
           }
         }
      +}
       
      -})(jQuery);
      -
      -    
      +})( jQuery ); +

      Special units

      -

      By default, jQuery adds a "px" unit to the values passed to the .css() method. This behavior can be prevented by adding the property to the jQuery.cssNumber object

      -
      -      $.cssNumber["someCSSProp"] = true;
      -    
      +

      By default, jQuery adds a "px" unit to the values passed to the .css() method. This behavior can be prevented by adding the property to the jQuery.cssNumber object

      +
      
      +$.cssNumber.someCSSProp = true;
      +    

      Animating with cssHooks

      A css hook can also hook into jQuery's animation mechanism by adding a property to the jQuery.fx.step object:

      -
      -      $.fx.step["someCSSProp"] = function(fx){
      -  $.cssHooks["someCSSProp"].set( fx.elem, fx.now + fx.unit );
      +    
      
      +$.fx.step.someCSSProp = function( fx ) {
      +  $.cssHooks.someCSSProp.set( fx.elem, fx.now + fx.unit );
       };
      -
      -    
      +

      Note that this works best for simple numeric-value animations. More custom code may be required depending on the CSS property, the type of value it returns, and the animation's complexity.

      - \ No newline at end of file + diff --git a/entries/jQuery.cssNumber.xml b/entries/jQuery.cssNumber.xml new file mode 100644 index 000000000..c49b3c785 --- /dev/null +++ b/entries/jQuery.cssNumber.xml @@ -0,0 +1,53 @@ + + + jQuery.cssNumber + + 1.4.3 + + An object containing all CSS properties that may be used without a unit. Prior to jQuery 4.0, the .css() method uses this object to see if it may append px to unitless values. + +
      +

      Note: This API has been removed in jQuery 4.0; please pass a string value with the desired units instead.

      +
      +

      You can think about jQuery.cssNumber as a list of all CSS properties you might use without a unit. Prior to jQuery 4.0, it was used by .css() to determine if it needs to add px to unitless values.

      +

      The keys of the jQuery.cssNumber object are camel-cased and the values are all set to true. If you want to prevent the .css() method from automatically adding the px unit for a specific CSS property and that property is not yet a key of the jQuery.cssNumber object, you can add such an extra property:

      +
      
      +if ( jQuery.cssNumber ) {
      +  jQuery.cssNumber.someCSSProp = true;
      +}
      +    
      +

      By default the object contains the following properties:

      +
        +
      • animationIterationCount (added in 1.12.0/2.2.0)
      • +
      • aspectRatio (added in 3.7.0)
      • +
      • borderImageSlice (added in 3.7.0)
      • +
      • columnCount (added in 1.9.0)
      • +
      • flexGrow (added in 1.11.1/2.1.1)
      • +
      • flexShrink (added in 1.11.1/2.1.1)
      • +
      • fontWeight (added in 1.4.3)
      • +
      • gridArea (added in 3.4.0)
      • +
      • gridColumn (added in 3.4.0)
      • +
      • gridColumnEnd (added in 3.4.0)
      • +
      • gridColumnStart (added in 3.4.0)
      • +
      • gridRow (added in 3.4.0)
      • +
      • gridRowEnd (added in 3.4.0)
      • +
      • gridRowStart (added in 3.4.0)
      • +
      • lineHeight (added in 1.4.3)
      • +
      • opacity (added in 1.4.3)
      • +
      • order (added in 1.10.2/2.0.3)
      • +
      • orphans (added in 1.6.0)
      • +
      • scale (added in 3.7.0)
      • +
      • widows (added in 1.6.0)
      • +
      • zIndex (added in 1.4.3)
      • +
      • zoom (added in 1.4.3)
      • +
      • fillOpacity (SVG-related, added in 1.6.2)
      • +
      • floodOpacity (SVG-related, added in 3.7.0)
      • +
      • stopOpacity (SVG-related, added in 3.7.0)
      • +
      • strokeMiterlimit (SVG-related, added in 3.7.0)
      • +
      • strokeOpacity (SVG-related, added in 3.7.0)
      • +
      +
      + + + +
      diff --git a/entries/jQuery.data.xml b/entries/jQuery.data.xml index e3933dcf1..5207c8b89 100644 --- a/entries/jQuery.data.xml +++ b/entries/jQuery.data.xml @@ -11,36 +11,48 @@ A string naming the piece of data to set. - - The new data value. + + The new data value; this can be any Javascript type except undefined. Store arbitrary data associated with the specified element. Returns the value that was set. -

      Note: This is a low-level method; a more convenient .data() is also available.

      +

      Note: This is a low-level method; a more convenient .data() is also available.

      The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page. We can set several distinct values for a single element and retrieve them later:

      
      -jQuery.data(document.body, 'foo', 52);
      -jQuery.data(document.body, 'bar', 'test');
      -
      -

      Note: this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

      +jQuery.data( document.body, "foo", 52 ); +jQuery.data( document.body, "bar", "test" ); +
      + + Store then retrieve a value from the div element. - + - + + +]]> @@ -66,56 +78,68 @@ jQuery.data(document.body, 'bar', 'test'); Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. -

      Note: This is a low-level method; a more convenient .data() is also available.

      -

      Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.

      +

      Note: This is a low-level method; a more convenient .data() is also available.

      +

      Regarding HTML5 data-* attributes: This low-level method does NOT retrieve the data-* attributes unless the more convenient .data() method has already retrieved them.

      The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:

      -
      alert(jQuery.data( document.body, 'foo' ));
      -alert(jQuery.data( document.body ));
      +
      
      +alert( jQuery.data( document.body, "foo" ) );
      +alert( jQuery.data( document.body ) );
      +      

      The above lines alert the data values that were set on the body element. If nothing was set on that element, an empty string is returned.

      -

      Calling jQuery.data(element) retrieves all of the element's associated values as a JavaScript object. Note that jQuery itself uses this method to store data for internal use, such as event handlers, so do not assume that it contains only data that your own code has stored.

      +

      Calling jQuery.data( element ) retrieves all of the element's associated values as a JavaScript object. Note that jQuery itself uses this method to store data for internal use, such as event handlers, so do not assume that it contains only data that your own code has stored.

      Note: this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

      Get the data named "blah" stored at for an element. - + +

      The "blah" value of this div is ?

      +]]>
      diff --git a/entries/jQuery.dequeue.xml b/entries/jQuery.dequeue.xml index 1982a6e78..c9b6faf29 100644 --- a/entries/jQuery.dequeue.xml +++ b/entries/jQuery.dequeue.xml @@ -12,29 +12,43 @@ Execute the next function on the queue for the matched element. -

      Note: This is a low-level method, you should probably use .dequeue() instead.

      +

      Note: This is a low-level method, you should probably use .dequeue() instead.

      When jQuery.dequeue() is called, the next function on the queue is removed from the queue, and then executed. This function should in turn (directly or indirectly) cause jQuery.dequeue() to be called, so that the sequence can continue.

      Use jQuery.dequeue() to end a custom queue function which allows the queue to keep going. - - - + + + - \ No newline at end of file + diff --git a/entries/jQuery.each.xml b/entries/jQuery.each.xml index 31584a790..188360154 100644 --- a/entries/jQuery.each.xml +++ b/entries/jQuery.each.xml @@ -3,79 +3,106 @@ jQuery.each() 1.0 - - The object or array to iterate over. + + The array or array-like object to iterate over. - - The function that will be executed on every object. + + + + The function that will be executed on every value. + + + + 1.0 + + The object to iterate over. + + + + + The function that will be executed on every value. A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

      The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

      -
      $.each([52, 97], function(index, value) {
      -  alert(index + ': ' + value);
      +    
      
      +$.each([ 52, 97 ], function( index, value ) {
      +  alert( index + ": " + value );
       });
      -
      +

      This produces two messages:

      - 0: 52 + 0: 52
      - 1: 97 + 1: 97

      If an object is used as the collection, the callback is passed a key-value pair each time:

      -
      var obj = {
      +    
      
      +var obj = {
         "flammable": "inflammable",
         "duh": "no duh"
       };
       $.each( obj, function( key, value ) {
         alert( key + ": " + value );
      -});
      +}); +

      Once again, this produces two messages:

      - flammable: inflammable + flammable: inflammable
      - duh: no duh + duh: no duh

      We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

      Iterates through the array displaying each number as both a word and numeral + div { + color: blue; + } + div#five { + color: red; + } +]]> +
      +
      +
      +
      +
      +]]>
      Iterates over items in an array, accessing both the current item and its index. - + Iterates over the properties in an object, accessing both the current item and its key. - + diff --git a/entries/jQuery.error.xml b/entries/jQuery.error.xml index f6bd7cd5f..54b64d5d9 100644 --- a/entries/jQuery.error.xml +++ b/entries/jQuery.error.xml @@ -10,11 +10,17 @@ Takes a string and throws an exception containing it.

      This method exists primarily for plugin developers who wish to override it and provide a better display (or more information) for the error messages.

      +

      If you do override the method, remember to still throw an error at the end to preserve semantics.

      - Override jQuery.error for display in Firebug. - + Override jQuery.error to send it to a logging service, assuming the sendErrorLog method is provided by this service. + - \ No newline at end of file + diff --git a/entries/jQuery.escapeSelector.xml b/entries/jQuery.escapeSelector.xml new file mode 100644 index 000000000..9e9a91d1e --- /dev/null +++ b/entries/jQuery.escapeSelector.xml @@ -0,0 +1,29 @@ + + + jQuery.escapeSelector() + Escapes any character that has a special meaning in a CSS selector. + + 3.0 + + A string containing a selector expression to escape. + + + +

      This method is useful for situations where a class name or an ID contains characters that have a special meaning in CSS, such as the dot or the semicolon.

      +

      The method is essentially a shim for the CSS Working Group's CSS.escape() method. The main difference is that $.escapeSelector() can be reliably used in all of jQuery's supported browsers.

      +
      + + Escape an ID containing a hash. + + + + Select all the elements having a class name of .box inside a div. + + + + +
      diff --git a/entries/jQuery.extend.xml b/entries/jQuery.extend.xml index 2007fa65b..472626153 100644 --- a/entries/jQuery.extend.xml +++ b/entries/jQuery.extend.xml @@ -4,9 +4,9 @@ 1.0 - An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + An object that will receive the new properties. - + An object containing additional properties to merge in. @@ -16,7 +16,7 @@ 1.1.4 - If true, the merge becomes recursive (aka. deep copy). + If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. The object to extend. It will receive the new properties. @@ -28,45 +28,43 @@ Additional objects containing properties to merge in. + + 1.0 + + An object to merge onto the jQuery namespace. + + Merge the contents of two or more objects together into the first object. -

      When two or more objects are supplied to $.extend(), properties from all of the objects are added to the target object.

      +

      When two or more object arguments are supplied to $.extend(), properties from all of the objects are added to the target object. Arguments that are null or undefined are ignored.

      If only one argument is supplied to $.extend(), this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, you can add new functions to the jQuery namespace. This can be useful for plugin authors wishing to add new methods to JQuery.

      Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, you want to preserve both of the original objects, you can do so by passing an empty object as the target:

      var object = $.extend({}, object1, object2);
      -

      The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true for the first function argument, objects will be recursively merged.

      +

      The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second or subsequent object. The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true for the first function argument, objects will be recursively merged.

      +

      Warning: Versions prior to 3.4 had a security issue where calling jQuery.extend(true, {}, object) on an unsanitized object containing a __proto__ property would extend Object.prototype.

      Warning: Passing false for the first argument is not supported.

      Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Properties that are an object constructed via new MyCustomObject(args), or built-in JavaScript types such as Date or RegExp, are not re-constructed and will appear as plain Objects in the resulting object or array.

      -

      On a deep extend, Object and Array are extended, but object wrappers on primitive types such as String, Boolean, and Number are not.

      -

      For needs that fall outside of this behavior, write a custom extend method instead.

      +

      On a deep extend, Object and Array are extended, but object wrappers on primitive types such as String, Boolean, and Number are not. Deep-extending a cyclical data structure will result in an error.

      +

      For needs that fall outside of this behavior, write a custom extend method instead, or use a library like lodash.

      Merge two objects, modifying the first. defaults -- " + printObj(defaults) + "" ); -$("#log").append( "
      options -- " + printObj(options) + "
      " ); -$("#log").append( "
      settings -- " + printObj(settings) + "
      " ); +// Merge defaults and options, without modifying defaults +var settings = $.extend( {}, defaults, options ); +// Assuming JSON.stringify - not available in IE<8 +$( "#log" ).append( "
      defaults -- " + JSON.stringify( defaults ) + "
      " ); +$( "#log" ).append( "
      options -- " + JSON.stringify( options ) + "
      " ); +$( "#log" ).append( "
      settings -- " + JSON.stringify( settings ) + "
      " ); ]]> : Elements whose NAME attribute doesn't match the specified value. Equivalent to :not([NAME=VALUE]). +
    • :contains(TEXT): Elements with textContent containing the word 'TEXT'. Case-sensitive.
    • +
    • :header: Header elements (h1, h2, h3, h4, h5, h6).
    • +
    • :parent: Elements with at least one child node (either text or an element).
    • +
    • :selected: (option) elements that are currently selected
    • +
    + +

    Form Selector Additions

    + +

    Note: In this context, input, button, select, and textarea are all considered to be input elements.

    + +
      +
    • :input: Input elements
    • +
    • :button: Input elements that are buttons or have type "button"
    • +
    • :checkbox, :file, :image, :password, :radio, :reset, :submit, :text: Input elements with the specified type
    • +
    + +

    Positional Selector Additions

    + +

    In this context, "positional" refers to an element's placement in the collection after a selection, based on document order. For example, div:first would return an array containing the first div on the page, while div:first em would target the first div on the page and select all em elements within.

    + +

    Note: Positional indexes begin at zero.

    + +
      +
    • :first/:last: The first/last matching element
    • +
    • :even/:odd: Even/odd-numbered elements
    • +
    • :eq/:nth: The nth element; e.g. :eq(5) finds the 6th element
    • +
    • :lt/:gt: Elements at positions above/below the specified position
    • +
    + +

    API

    + +

    The jQuery Selection API consists of 3 parts:

    + + + +

    Public API

    + +

    jQuery.find( String selector[, DOMNode context[, Array results]] )

    + +

    The main function for finding elements. Uses querySelectorAll if available.

    + +

    returns (Array): All elements matching the selector

    + +

    Parameters

    + +

    selector: A CSS selector

    + +

    context: An element, document, or document fragment to use as the context for finding elements. Defaults to document. + Note: Prior to version 2.1, document fragments were not valid here.

    + +

    results: An array or an array-like object, to which jQuery will append results. For example, jQuery passes a jQuery collection. An "array-like object" is an object with a nonnegative numeric length property and a push method.

    + +

    jQuery.find.matchesSelector( DOMElement element, String selector )

    + +

    Uses native matchesSelector if available

    + +

    returns(Boolean): Whether the given element matches the selector

    + +

    Parameters

    + +

    element: A DOMElement against which jQuery will test the selector

    + +

    selector: A CSS selector

    + +

    jQuery.find.matches( String selector, Array<DOMElement> elements )

    + +

    returns(Array): Elements in the array that match the given selector

    + +

    Parameters

    + +

    selector: A CSS selector

    + +

    elements: An array of DOMElements to filter against the specified selector

    + +

    Extension API

    + +

    jQuery.expr.match.NAME = RegExp

    + +

    This contains the regular expressions used to parse a selector into different parts, to be used for finding and filtering. The name of each of the regular expressions should correspond to the names specified in the jQuery.expr.find and jQuery.expr.filter objects.

    + +

    Finding

    + +

    In order to add a new find function:

    +
      +
    • A regular expression must be added to the match object.
    • +
    • A function to find must be defined.
    • +
    • "|" + NAME must be appended to the jQuery.expr.order regex.
    • +
    + +
    jQuery.expr.find.NAME = function( match, context, isXML ) {}
    + +

    A method for finding some elements on a page. The specified function will be called no more than once per selector.

    +
      +
    • match is the array of results returned from matching the specified regex against the selector.
    • +
    • context is the DOMElement or DOMDocument from which selection will occur.
    • +
    • isXML is a boolean value indicating whether the function is currently operating within an XML document.
    • +
    + +

    Filtering

    + +

    In order to add a new filtering statement:

    +
      +
    • A regular expression must be added to the match object.
    • +
    • A function must be added to the filter object.
    • +
    • A function may optionally be added to the preFilter object.
    • +
    + +
    jQuery.expr.preFilter.NAME = function( match ) {}
    + +

    An optional pre-filter function which allows filtering of the matched array against the corresponding regular expression, which will return a new matched array. This matched array will eventually be passed and flattened as arguments against the corresponding filter function. This is intended to clean up some of the repetitive processing that occurs in a filter function.

    + +
    jQuery.expr.filter.NAME: function( element, match[1][, match[2], match[3], ...] ) {}
    + +

    Note: match[0] will be deleted prior to being passed to a filter, and must not be used.

    + +

    The arguments for a filter method are the element and the captures from the regex corresponding to this filter (indicated above by what is in the match, starting at index 1). The return result must be boolean: true if the element matches the selector, false if not.

    + +

    Attributes

    + +
    jQuery.expr.attrHandle.LOWERCASE_NAME = function( elem, casePreservedName, isXML ) {}
    + +

    Handle an attribute which requires specialized processing (such as href, which has cross-browser issues). The return result must be the actual string value of that attribute.

    + +

    Pseudo-selectors (pseudos)

    + +
    jQuery.expr.pseudos.NAME = function( elem ) {}
    + +

    The most common extension to a selector engine: adding a new pseudo. The return result from this function must be boolean: true if the element matches the selector, false if not.

    + +

    For example, this defines a simple :fixed pseudo:

    +
    
    +var $test = jQuery( document );
    +jQuery.expr.pseudos.fixed = function( elem ) {
    +  $test[ 0 ] = elem;
    +  return $test.css( "position" ) === "fixed";
    +};
    +    
    + +
    jQuery.expr.createPseudo( function )
    + +

    createPseudo is only required if the custom pseudo-selector accepts an argument.

    + +

    Note: In jQuery 1.8 and earlier, the API for creating custom pseudos with arguments was broken. In jQuery 1.8.1+, the API is backwards-compatible. Regardless, the use of createPseudo is greatly encouraged.

    + +

    Now that the parser compiles a single function containing other functions, custom pseudo-selectors with arguments are much cleaner.

    + +

    For example, within jQuery, the implementation of the :not( <sub-selector> ) pseudo is very similar to:

    + +
    
    +jQuery.expr.pseudos.not =
    +  jQuery.expr.createPseudo( function( subSelector ) {
    +    var matcher = jQuery.find.compile( subSelector );
    +    return function( elem ) {
    +      return !matcher( elem );
    +    };
    +  } );
    +    
    + +
    jQuery.expr.setFilters.LOWERCASE_NAME = function( elements, argument, not ) {}
    + +

    These filters are run after a previous part of a selector has already returned results. setFilters are found from matching jQuery.expr.match.POS. When applicable, argument is expected to be an integer. The not argument is a boolean indicating whether the result should be inverted (as in div:not(:first)).

    + +

    For example, the code for the :first setFilter is similar to:

    +
    
    +var first = function( elements, argument, not ) {
    +  // No argument for first
    +  return not ? elements.slice( 1 ) : [ elements[ 0 ] ];
    +};
    +jQuery.expr.setFilters.first = first;
    +    
    + +

    It is easy to extend jQuery selection engine — even jQuery's POS selectors. For example, to rename :first as :uno:

    +
    + +

    Internal API

    + +

    Note: Functionality should be accessed via the Public and Extension APIs. While the Internal API is intended specifically for internal use, it has been exposed for edge cases.

    + +

    jQuery.expr.cacheLength

    + +

    jQuery internally caches compiled selector functions and tokenization objects. The length of these caches defaults to 50, but can be set to any positive integer by assigning to this property.

    + +

    jQuery.find.compile( selector )

    + +

    This method compiles a selector function and caches it for later use. For example, calling jQuery.find.compile( ".myWidget:myPseudo" ) during initialization of a plugin will speed up the first selection of matching elements.

    + +

    returns(Function): The compiled function to be used when filtering the set of possibly matching elements

    + +

    Parameters

    + +

    selector: A CSS selector

    + +
    +
    diff --git a/entries/jQuery.fn.extend.xml b/entries/jQuery.fn.extend.xml new file mode 100644 index 000000000..1ece082d2 --- /dev/null +++ b/entries/jQuery.fn.extend.xml @@ -0,0 +1,46 @@ + + + jQuery.fn.extend() + + 1.0 + + An object to merge onto the jQuery prototype. + + + Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. + + The jQuery.fn.extend() method extends the jQuery prototype ($.fn) object to provide new methods that can be chained to the jQuery() function. + + + Add two methods to the jQuery prototype ($.fn) object and then use one of them. + + + label { + display: block; + margin: .5em; + } + + + + + + diff --git a/entries/jQuery.fx.interval.xml b/entries/jQuery.fx.interval.xml index b47bbc8df..b86516c3e 100644 --- a/entries/jQuery.fx.interval.xml +++ b/entries/jQuery.fx.interval.xml @@ -1,32 +1,41 @@ - + jQuery.fx.interval The rate (in milliseconds) at which animations fire. 1.4.3 -

    This property can be manipulated to adjust the number of frames per second at which animations will run. The default is 13 milliseconds. Making this a lower number could make the animations run smoother in faster browsers (such as Chrome) but there may be performance and CPU implications of doing so.

    +
    +

    This property is deprecated as of version 3.0, and has no effect in browsers that support the requestAnimationFrame method.

    +
    +

    On browsers that do not support requestAnimationFrame, this property can be changed to adjust the interval at which animations will run. The default is 13 milliseconds.

    Since jQuery uses one global interval, no animation should be running or all animations should stop for the change of this property to take effect.

    -

    Note:jQuery.fx.interval currently has no effect in browsers that support the requestAnimationFrame property, such as Google Chrome 11. This behavior is subject to change in a future release.

    Cause all animations to run with less frames. +]]> - + -
    \ No newline at end of file + +
    diff --git a/entries/jQuery.fx.off.xml b/entries/jQuery.fx.off.xml index a10f09c69..8464f69f5 100644 --- a/entries/jQuery.fx.off.xml +++ b/entries/jQuery.fx.off.xml @@ -9,7 +9,7 @@

    When this property is set to true, all animation methods will immediately set elements to their final state when called, rather than displaying an effect. This may be desirable for a couple reasons:

    • jQuery is being used on a low-resource device.
    • -
    • Users are encountering accessibility problems with the animations (see the article Turn Off Animation for more information).
    • +
    • Users are encountering accessibility problems with the animations.

    Animations can be turned back on by setting the property to false.

    @@ -20,21 +20,27 @@ var toggleFx = function() { $.fx.off = !$.fx.off; }; toggleFx(); - -$("button").click(toggleFx) - -$("input").click(function(){ - $("div").toggle("slow"); -}); - ]]> +$( "button" ).on( "click", toggleFx ); +$( "input" ).on( "click", function() { + $( "div" ).toggle( "slow" ); +} ); +]]> - + div { + width: 50px; + height: 30px; + margin: 5px; + float: left; + background: green; + } +]]> + - \ No newline at end of file + diff --git a/entries/jQuery.get.xml b/entries/jQuery.get.xml index 368157e0f..e0f7af6f2 100644 --- a/entries/jQuery.get.xml +++ b/entries/jQuery.get.xml @@ -11,89 +11,133 @@ A plain object or string that is sent to the server with the request.
    - - A callback function that is executed if the request succeeds. + + + + + A callback function that is executed if the request succeeds. Required if dataType is provided, but you can use null or jQuery.noop as a placeholder. NOTE: In jQuery 3.x and older, when providing a null value for success you also have to provide the data parameter; you can set it to null or undefined. - The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + + + + 1.12-and-2.2 + + A set of key/value pairs that configure the Ajax request. All properties except for url are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a complete list of all settings. The type option will automatically be set to GET. Load data from the server using a HTTP GET request.

    This is a shorthand Ajax function, which is equivalent to:

    -
    $.ajax({
    +    
    
    +$.ajax({
       url: url,
       data: data,
       success: success,
       dataType: dataType
     });
    -
    +

    The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

    -

    As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

    +

    As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

    Most implementations will specify a success handler:

    -
    $.get('ajax/test.html', function(data) {
    -  $('.result').html(data);
    -  alert('Load was performed.');
    +    
    
    +$.get( "ajax/test.html", function( data ) {
    +  $( ".result" ).html( data );
    +  alert( "Load was performed." );
     });
    -
    +

    This example fetches the requested HTML snippet and inserts it on the page.

    The jqXHR Object

    -

    As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

    +

    As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

    The Promise interface also allows jQuery's Ajax methods, including $.get(), to chain multiple .done(), .fail(), and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

    -
    // Assign handlers immediately after making the request,
    +    
    
    +// Assign handlers immediately after making the request,
     // and remember the jqxhr object for this request
    -var jqxhr = $.get("example.php", function() {
    -  alert("success");
    +var jqxhr = $.get( "example.php", function() {
    +  alert( "success" );
     })
    -.done(function() { alert("second success"); })
    -.fail(function() { alert("error"); })
    -.always(function() { alert("finished"); });
    +  .done(function() {
    +    alert( "second success" );
    +  })
    +  .fail(function() {
    +    alert( "error" );
    +  })
    +  .always(function() {
    +    alert( "finished" );
    +  });
     
    -// perform other work here ...
    +// Perform other work here ...
     
     // Set another completion function for the request above
    -jqxhr.always(function(){ alert("second finished"); });
    -
    +jqxhr.always(function() { + alert( "second finished" ); +}); +

    Deprecation Notice

    -

    The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    +

    The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    Request the test.php page, but ignore the return results. - + Request the test.php page and send some additional data along (while still ignoring the return results). - + Pass arrays of data to the server (while still ignoring the return results). - + Alert the results from requesting test.php (HTML or XML, depending on what was returned). - + Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned). - + + + + Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( "name"=>"John","time"=>"2pm" ) ); ?>), and add it to the page. + - Get the test.php page contents, which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>), and add it to the page. - + Get another page on the same domain. Outputs to console both the data returned and the type of data returned. + + diff --git a/entries/jQuery.getJSON.xml b/entries/jQuery.getJSON.xml index 30f11c4a6..1449293d2 100644 --- a/entries/jQuery.getJSON.xml +++ b/entries/jQuery.getJSON.xml @@ -6,103 +6,142 @@ A string containing the URL to which the request is sent. - + + + A plain object or string that is sent to the server with the request. - + + + + A callback function that is executed if the request succeeds. Load JSON-encoded data from the server using a GET HTTP request.

    This is a shorthand Ajax function, which is equivalent to:

    -
    $.ajax({
    +    
    
    +$.ajax({
       dataType: "json",
       url: url,
       data: data,
       success: success
     });
    -
    +

    Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL.

    Most implementations will specify a success handler:

    -
    $.getJSON('ajax/test.json', function(data) {
    +    
    
    +$.getJSON( "ajax/test.json", function( data ) {
       var items = [];
    -
    -  $.each(data, function(key, val) {
    -    items.push('<li id="' + key + '">' + val + '</li>');
    +  $.each( data, function( key, val ) {
    +    items.push( "<li id='" + key + "'>" + val + "</li>" );
       });
     
    -  $('<ul/>', {
    -    'class': 'my-new-list',
    -    html: items.join('')
    -  }).appendTo('body');
    +  $( "<ul/>", {
    +    "class": "my-new-list",
    +    html: items.join( "" )
    +  }).appendTo( "body" );
     });
     

    This example, of course, relies on the structure of the JSON file:

    -
    {
    +    
    
    +{
       "one": "Singular sensation",
       "two": "Beady little eyes",
       "three": "Little birds pitch by my doorstep"
     }
    -
    +

    Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

    -

    The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

    -

    As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

    -
    -

    Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

    -
    +

    The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

    +

    As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

    +
    +

    Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see https://json.org/.

    +

    JSONP

    -

    If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

    +

    If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

    The jqXHR Object

    -

    As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.getJSON() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). For convenience and consistency with the callback names used by $.ajax(), it provides .error(), .success(), and .complete() methods. These methods take a function argument that is called when the request terminates, and the function receives the same arguments as the correspondingly-named $.ajax() callback.

    -

    The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.getJSON(), to chain multiple .success(), .complete(), and .error() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

    -
    // Assign handlers immediately after making the request,
    +    

    As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.getJSON() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

    +

    The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.getJSON(), to chain multiple .done(), .always(), and .fail() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

    +
    
    +// Assign handlers immediately after making the request,
     // and remember the jqxhr object for this request
    -var jqxhr = $.getJSON("example.json", function() {
    -  alert("success");
    +var jqxhr = $.getJSON( "example.json", function() {
    +  console.log( "success" );
     })
    -.success(function() { alert("second success"); })
    -.error(function() { alert("error"); })
    -.complete(function() { alert("complete"); });
    +  .done(function() {
    +    console.log( "second success" );
    +  })
    +  .fail(function() {
    +    console.log( "error" );
    +  })
    +  .always(function() {
    +    console.log( "complete" );
    +  });
     
    -// perform other work here ...
    +// Perform other work here ...
     
     // Set another completion function for the request above
    -jqxhr.complete(function(){ alert("second complete"); });
    +jqxhr.always(function() { + console.log( "second complete" ); +}); +
    +

    Deprecation Notice

    +

    The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    - Loads the four most recent cat pictures from the Flickr JSONP API. + Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API. - - +})(); +]]>
    + + Load the JSON data from test.js and access a name from the returned JSON data. - + - Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. - + Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. + If an error occurs, log an error message instead. + diff --git a/entries/jQuery.getScript.xml b/entries/jQuery.getScript.xml index da850c244..d44d1f3a1 100644 --- a/entries/jQuery.getScript.xml +++ b/entries/jQuery.getScript.xml @@ -6,66 +6,73 @@ A string containing the URL to which the request is sent. - + + + + A callback function that is executed if the request succeeds. Load a JavaScript file from the server using a GET HTTP request, then execute it.

    This is a shorthand Ajax function, which is equivalent to:

    -
    $.ajax({
    +    
    
    +$.ajax({
       url: url,
       dataType: "script",
       success: success
     });
    -
    +

    The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.

    Success Callback

    -

    The callback is fired once the script has been loaded but not necessarily executed.

    -
    $(".result").html("<p>Lorem ipsum dolor sit amet.</p>");
    +

    The callback is fired once the script has been loaded and executed.

    Scripts are included and run by referencing the file name:

    -
    $.getScript("ajax/test.js", function(data, textStatus, jqxhr) {
    -   console.log(data); //data returned
    -   console.log(textStatus); //success
    -   console.log(jqxhr.status); //200
    -   console.log('Load was performed.');
    -});
    +
    
    +$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
    +  console.log( data ); // Data returned
    +  console.log( textStatus ); // Success
    +  console.log( jqxhr.status ); // 200
    +  console.log( "Load was performed." );
    +});
    +    

    Handling Errors

    -

    As of jQuery 1.5, you may use .fail() to account for errors:

    +

    As of jQuery 1.5, you may use .fail() to account for errors:

    
    -$.getScript("ajax/test.js")
    -.done(function(script, textStatus) {
    -  console.log( textStatus );
    -})
    -.fail(function(jqxhr, settings, exception) {
    -  $( "div.log" ).text( "Triggered ajaxError handler." );
    +$.getScript( "ajax/test.js" )
    +  .done(function( script, textStatus ) {
    +    console.log( textStatus );
    +  })
    +  .fail(function( jqxhr, settings, exception ) {
    +    $( "div.log" ).text( "Triggered ajaxError handler." );
     });
    -
    -

    Prior to jQuery 1.5, the global .ajaxError() callback event had to be used in order to handle $.getScript() errors:

    +
    +

    Prior to jQuery 1.5, the global ajaxError callback event had to be used in order to handle $.getScript() errors:

    
    -$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
    -  if (settings.dataType=='script') {
    -    $(this).text( "Triggered ajaxError handler." );
    +$( "div.log" ).on( "ajaxError", function( e, jqxhr, settings, exception ) {
    +  if ( settings.dataType == "script" ) {
    +    $( this ).text( "Triggered ajaxError handler." );
       }
    -});
    -
    +} ); + +

    Prior to jQuery 3.5.0, unsuccessful HTTP responses with a script Content-Type were still executed.

    Caching Responses

    -

    By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

    +

    By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

    
     $.ajaxSetup({
       cache: true
     });
    -
    +

    Alternatively, you could define a new method that uses the more flexible $.ajax() method.

    Define a $.cachedScript() method that allows fetching a cached script: - jQuery.cachedScript = function(url, options) { + - Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded. + Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded. + .block { + background-color: blue; + width: 150px; + height: 70px; + margin: 10px; + } +]]> + diff --git a/entries/jQuery.globalEval.xml b/entries/jQuery.globalEval.xml index f7584d01c..f6234efed 100644 --- a/entries/jQuery.globalEval.xml +++ b/entries/jQuery.globalEval.xml @@ -1,5 +1,5 @@ - + jQuery.globalEval() 1.0.4 @@ -7,19 +7,57 @@ The JavaScript code to execute.
    + + 3.4 + + The JavaScript code to execute. + + + + The nonce attribute passed to the executed script. + + + + + 3.5 + + The JavaScript code to execute. + + + + The nonce attribute passed to the executed script. + + + + A document in which context the code will be evaluated. + + Execute some JavaScript code globally.

    This method behaves differently from using a normal JavaScript eval() in that it's executed within the global context (which is important for loading external scripts dynamically).

    Execute a script in the global context. - + + + + Execute a script with a nonce value on a site with Content Security Policy enabled. + - \ No newline at end of file + diff --git a/entries/jQuery.grep.xml b/entries/jQuery.grep.xml index 40c0ff68a..5195ffdd8 100644 --- a/entries/jQuery.grep.xml +++ b/entries/jQuery.grep.xml @@ -4,10 +4,13 @@ Finds the elements of an array which satisfy a filter function. The original array is not affected. 1.0 - - The array to search through. + + The array-like object to search through. - + + + + The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. @@ -22,41 +25,59 @@ Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s. 4); +arr = jQuery.grep(arr, function( n, i ) { + return ( n !== 5 && i > 4 ); }); -$("p").text(arr.join(", ")); +$( "p" ).text( arr.join( ", " ) ); -arr = jQuery.grep(arr, function (a) { return a != 9; }); -$("span").text(arr.join(", ")); +arr = jQuery.grep(arr, function( a ) { + return a !== 9; +}); +$( "span" ).text( arr.join( ", " ) ); ]]> - + div { + color: blue; + } + p { + color: green; + margin: 0; + } + span { + color: red; + } +]]> + Filter an array of numbers to include only numbers bigger then zero. - 0; - });]]> - + 0; +}); +]]> + Filter an array of numbers to include numbers that are not bigger than zero. - 0; -},true);]]> - +}, true ); +]]>
    + - \ No newline at end of file + diff --git a/entries/jQuery.hasData.xml b/entries/jQuery.hasData.xml index 4919998d7..ece74c751 100644 --- a/entries/jQuery.hasData.xml +++ b/entries/jQuery.hasData.xml @@ -9,7 +9,7 @@ Determine whether an element has any jQuery data associated with it. -

    The jQuery.hasData() method provides a way to determine if an element currently has any values that were set using jQuery.data(). If no data is associated with an element (there is no data object at all or the data object is empty), the method returns false; otherwise it returns true.

    +

    The jQuery.hasData() method provides a way to determine if an element currently has any values that were set using jQuery.data(). If there is no data object associated with an element, the method returns false; otherwise it returns true.

    The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.

    Note that jQuery's event system uses the jQuery data API to store event handlers. Therefore, binding an event to an element using .on(), .bind(), .live(), .delegate(), or one of the shorthand event methods also associates a data object with that element. @@ -18,24 +18,25 @@ Set data on an element and see the results of hasData. - + - \ No newline at end of file + diff --git a/entries/jQuery.holdReady.xml b/entries/jQuery.holdReady.xml index 8572c853f..0ba8ceb04 100644 --- a/entries/jQuery.holdReady.xml +++ b/entries/jQuery.holdReady.xml @@ -1,5 +1,5 @@ - + jQuery.holdReady() Holds or releases the execution of jQuery's ready event. @@ -9,18 +9,31 @@ +

    +

    Note: This API has been deprecated in jQuery 3.2. Instead of relying on this global switch, it's better to put explicitly wait for required code. If you need to wait both for the ready state & for a custom promise, use the following pattern:

    + +

    The $.holdReady() method allows the caller to delay jQuery's ready event. This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready. This method must be called early in the document, such as in the <head> immediately after the jQuery script tag. Calling this method after the ready event has already fired will have no effect.

    -

    To delay the ready event, first call $.holdReady(true). When the ready event should be released to execute, call $.holdReady(false). Note that multiple holds can be put on the ready event, one for each $.holdReady(true) call. The ready event will not actually fire until all holds have been released with a corresponding number of $.holdReady(false) calls and the normal document ready conditions are met. (See ready for more information.)

    +

    To delay the ready event, first call $.holdReady( true ). When the ready event should be released to execute, call $.holdReady( false ). Note that multiple holds can be put on the ready event, one for each $.holdReady( true ) call. The ready event will not actually fire until all holds have been released with a corresponding number of $.holdReady( false ) calls and the normal document ready conditions are met. (See ready for more information.)

    Delay the ready event until a custom plugin has loaded. + + - \ No newline at end of file + + diff --git a/entries/jQuery.htmlPrefilter.xml b/entries/jQuery.htmlPrefilter.xml new file mode 100644 index 000000000..753819039 --- /dev/null +++ b/entries/jQuery.htmlPrefilter.xml @@ -0,0 +1,17 @@ + + + jQuery.htmlPrefilter() + Modify and filter HTML strings passed through jQuery manipulation methods. + + 1.12-and-2.2 + + The HTML string on which to operate. + + + +

    This method rarely needs to be called directly. Instead, use it as an entry point to modify existing jQuery manipulation methods. jQuery calls this method on input HTML before processing it further: it accepts an HTML string & should return a HTML string as well.

    +

    This function can also be overwritten in order to bypass certain edge case issues. The default htmlPrefilter function in jQuery leaves input unmodified since 3.5.0. Older versions would greedily ensure that all tags were XHTML-compliant. This included anything that looked like an HTML tag, but was actually within a string (e.g. <a title="<div />"><>), leading to potential security issues. For more information, see the jQuery Core 3.5 Upgrade guide.

    +
    + + +
    diff --git a/entries/jQuery.inArray.xml b/entries/jQuery.inArray.xml index 2d9cf228a..e7a3ca80e 100644 --- a/entries/jQuery.inArray.xml +++ b/entries/jQuery.inArray.xml @@ -16,26 +16,34 @@ Search for a specified value within an array and return its index (or -1 if not found).

    The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

    -

    Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.

    +

    Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value within array, you need to check if it's not equal to (or greater than) -1.

    +

    The comparison between values is strict. The following will return -1 (not found) because a number is being searched in an array of strings:

    +
    $.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );
    Report the index of some elements in the array. - +
    "Pete" is in the array, but not at or after index 2, so
    +]]>
    diff --git a/entries/jQuery.isArray.xml b/entries/jQuery.isArray.xml index 9b7c5c454..9891126ff 100644 --- a/entries/jQuery.isArray.xml +++ b/entries/jQuery.isArray.xml @@ -1,5 +1,5 @@ - + jQuery.isArray() 1.3 @@ -9,13 +9,21 @@ Determine whether the argument is an array. +
    +

    Note: This API has been deprecated in jQuery 3.2; please use the native Array.isArray method instead.

    +

    $.isArray() returns a Boolean indicating whether the object is a JavaScript array (not an array-like object, such as a jQuery object).

    Finds out if the parameter is an array. - - ]]> + + +]]> -
    \ No newline at end of file + +
    diff --git a/entries/jQuery.isEmptyObject.xml b/entries/jQuery.isEmptyObject.xml index 44d9732bd..0610cb0c2 100644 --- a/entries/jQuery.isEmptyObject.xml +++ b/entries/jQuery.isEmptyObject.xml @@ -9,13 +9,14 @@ Check to see if an object is empty (contains no enumerable properties). -

    As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty). The argument should always be a plain JavaScript Object as other types of object (DOM elements, primitive strings/numbers, host objects) may not give consistent results across browsers. To determine if an object is a plain JavaScript object, use $.isPlainObject()

    +

    As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty). The argument should always be a plain JavaScript Object as other types of object (DOM elements, primitive strings/numbers, host objects) may not give consistent results across browsers. To determine if an object is a plain JavaScript object, use $.isPlainObject()

    Check an object to see if it's empty. - + diff --git a/entries/jQuery.isFunction.xml b/entries/jQuery.isFunction.xml index ba6750a40..5160f0a70 100644 --- a/entries/jQuery.isFunction.xml +++ b/entries/jQuery.isFunction.xml @@ -1,53 +1,64 @@ - + jQuery.isFunction() 1.2 - - Object to test whether or not it is a function. + + The value to be tested. - Determine if the argument passed is a Javascript function object. + Determines if its argument is callable as a function. +
    +

    As of jQuery 3.3, jQuery.isFunction() has been deprecated. In most cases, its use can be replaced by typeof x === "function".

    +

    Note: As of jQuery 1.3, functions provided by the browser like alert() and DOM element methods like getAttribute() are not guaranteed to be detected as functions in browsers such as Internet Explorer.

    Test a few parameter examples. + div { + color: blue; + margin: 2px; + font-size: 14px; + } + span { + color: red; + } +]]> - -
    jQuery.isFunction(objs[1]) =
    -
    jQuery.isFunction(objs[2]) =
    -
    jQuery.isFunction(objs[3]) =
    - -
    jQuery.isFunction(objs[4]) =
    - ]]> +
    jQuery.isFunction( objs[ 0 ] ) =
    +
    jQuery.isFunction( objs[ 1 ] ) =
    +
    jQuery.isFunction( objs[ 2 ] ) =
    +
    jQuery.isFunction( objs[ 3 ] ) =
    +
    jQuery.isFunction( objs[ 4 ] ) =
    +]]>
    Finds out if the parameter is a function. - - + + -
    \ No newline at end of file + +
    diff --git a/entries/jQuery.isNumeric.xml b/entries/jQuery.isNumeric.xml index de4940380..c4fe4a72d 100644 --- a/entries/jQuery.isNumeric.xml +++ b/entries/jQuery.isNumeric.xml @@ -1,36 +1,46 @@ - + jQuery.isNumeric() - Determines whether its argument is a number. + Determines whether its argument represents a JavaScript number. 1.7 - + The value to be tested. +
    +

    Note: This API has been deprecated in jQuery 3.3.

    +

    The $.isNumeric() method checks whether its argument represents a numeric value. If so, it returns true. Otherwise it returns false. The argument can be of any type.

    +

    As of jQuery 3.0 $.isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers. In all other cases, it returns false.

    Sample return values of $.isNumeric with various inputs. -
    \ No newline at end of file + +
    diff --git a/entries/jQuery.isPlainObject.xml b/entries/jQuery.isPlainObject.xml index cc3c1b0ec..1f8f3ce2e 100644 --- a/entries/jQuery.isPlainObject.xml +++ b/entries/jQuery.isPlainObject.xml @@ -12,14 +12,16 @@

    Note: Host objects (or objects used by browser host environments to complete the execution environment of ECMAScript) have a number of inconsistencies which are difficult to robustly feature detect cross-platform. As a result of this, $.isPlainObject() may evaluate inconsistently across browsers in certain instances.

    An example of this is a test against document.location using $.isPlainObject() as follows:

    
    -  console.log($.isPlainObject(document.location));
    -
    +console.log( $.isPlainObject( document.location ) ); +

    which throws an invalid pointer exception in IE8. With this in mind, it's important to be aware of any of the gotchas involved in using $.isPlainObject() against older browsers. A couple basic examples that do function correctly cross-browser can be found below.

    Check an object to see if it's a plain object. - + diff --git a/entries/jQuery.isWindow.xml b/entries/jQuery.isWindow.xml index 2d9521f3b..76a58f176 100644 --- a/entries/jQuery.isWindow.xml +++ b/entries/jQuery.isWindow.xml @@ -1,5 +1,5 @@ - + jQuery.isWindow() 1.4.3 @@ -9,13 +9,24 @@ Determine whether the argument is a window. +
    +

    Note: This API has been deprecated in jQuery 3.3; if you need this function, reimplement it by yourself:

    + +

    This is used in a number of places in jQuery to determine if we're operating against a browser window (such as the current window or an iframe).

    Finds out if the parameter is a window. - - + + -
    \ No newline at end of file + +
    diff --git a/entries/jQuery.isXMLDoc.xml b/entries/jQuery.isXMLDoc.xml index 6cd855e7c..b1654d8e6 100644 --- a/entries/jQuery.isXMLDoc.xml +++ b/entries/jQuery.isXMLDoc.xml @@ -11,9 +11,11 @@ Check an object to see if it's in an XML document. - + - \ No newline at end of file + diff --git a/entries/jQuery.makeArray.xml b/entries/jQuery.makeArray.xml index d82a21c6e..0feac18a0 100644 --- a/entries/jQuery.makeArray.xml +++ b/entries/jQuery.makeArray.xml @@ -15,29 +15,37 @@ Turn a collection of HTMLElements into an Array of them. - + div { + color: red; + } +]]> + Turn a jQuery object into an array - + - \ No newline at end of file + diff --git a/entries/jQuery.map.xml b/entries/jQuery.map.xml index 7d374c381..2016df876 100644 --- a/entries/jQuery.map.xml +++ b/entries/jQuery.map.xml @@ -3,43 +3,42 @@ jQuery.map() 1.0 - - The Array to translate. + + The Array or an Array-like object to translate. - - The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + + + + + The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. 1.6 - - - - The Array or Object to translate. + + The non-Array-like Object to translate. - - The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + + + + + The function to process each item against. The first argument to the function is the value; the second argument is the key of the object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. Translate all items in an array or object to new array of items.

    If you wish to process a jQuery object — for example, $('div').map( callback ); — use .map() instead.

    -

    The $.map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $.map() supports traversing arrays only. As of jQuery 1.6 it also traverses objects.

    -

    Array-like objects — those with a .length property and a value on the .length - 1 index — must be converted to actual arrays before being passed to $.map(). The jQuery library provides $.makeArray() for such conversions.

    -
    -      
    -// The following object masquerades as an array.
    -var fakeArray = {"length": 1, 0: "Addy", 1: "Subtracty"};
    +    

    The $.map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $.map() supports traversing arrays and array-like objects only. As of jQuery 1.6 it also traverses objects.

    +

    Array-like objects — those with a .length property and a value on the .length - 1 index — may be passed to $.map().

    +
    
    +// The following object is array-like.
    +var fakeArray = { "length": 2, 0: "Addy", 1: "Subtracty" };
     
    -// Therefore, convert it to a real array
    -var realArray = $.makeArray( fakeArray )
    -
    -// Now it can be used reliably with $.map()
    -$.map( realArray, function(val, i) {
    -  // do something
    +// It can be used reliably with $.map()
    +$.map( realArray, function( val, i ) {
    +  // Do something
     });
    -
    -    
    +

    The translation function that is provided to this method is called for each top-level element in the array or object and is passed two arguments: The element's value and its index or key within the array or object.

    The function can return:

      @@ -51,50 +50,69 @@ $.map( realArray, function(val, i) { Use $.map() to change the values of an array. - + div { + color: blue; + } + p { + color: green; + margin: 0; + } + span { + color: red; + } +]]> + Map the original array to a new one and add 4 to each value. - - +}); +]]> + Map the original array to a new one, adding 1 to each value if it is bigger then zero and removing it if not. - 0 ? n + 1 : null; -});]]> - +}); +]]> + Map the original array to a new one; each element is added with its original value and the value plus one. - - +}); +]]> + Map the original object to a new array and double each value. @@ -102,8 +120,11 @@ $.map( realArray, function(val, i) { var dimensions = { width: 10, height: 15, length: 20 }; dimensions = $.map( dimensions, function( value, index ) { return value * 2; -}); ]]> - +}); +]]> + Map an object's keys to an array. @@ -111,32 +132,45 @@ dimensions = $.map( dimensions, function( value, index ) { var dimensions = { width: 10, height: 15, length: 20 }; var keys = $.map( dimensions, function( value, key ) { return key; -}); ]]> - +}); +]]> + Map the original array to a new one; each element is squared. - +}); +]]> + Map the original array to a new one, removing numbers less than 50 by returning null and subtracting 45 from the rest. 50 ? a - 45 : null); -});]]> - +}); +]]> + Augment the resulting array by returning an array inside the function. - - + + diff --git a/entries/jQuery.merge.xml b/entries/jQuery.merge.xml index 94dc936cf..b122635e9 100644 --- a/entries/jQuery.merge.xml +++ b/entries/jQuery.merge.xml @@ -4,38 +4,51 @@ Merge the contents of two arrays together into the first array. 1.0 - - The first array to merge, the elements of second added. + + The first array-like object to merge, the elements of second added. - - The second array to merge into the first, unaltered. + + The second array-like object to merge into the first, unaltered. -

      The $.merge() operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended. The $.merge() function is destructive. It alters the first parameter to add the items from the second.

      +

      The $.merge() operation forms an array that contains all elements from the two arrays. The orders of items in the arrays are preserved, with items from the second array appended. The $.merge() function is destructive. It alters the length and numeric index properties of the first object to include items from the second.

      If you need the original first array, make a copy of it before calling $.merge(). Fortunately, $.merge() itself can be used for this duplication:

      -
      var newArray = $.merge([], oldArray);
      +
      
      +var newArray = $.merge([], oldArray);
      +    

      This shortcut creates a new, empty array and merges the contents of oldArray into it, effectively cloning the array.

      Prior to jQuery 1.4, the arguments should be true Javascript Array objects; use $.makeArray if they are not.

      Merges two arrays, altering the first argument. - - + + Merges two arrays, altering the first argument. - - + + Merges two arrays, but uses a copy, so the original isn't altered. - - + - \ No newline at end of file + diff --git a/entries/jQuery.noConflict.xml b/entries/jQuery.noConflict.xml index 611d84386..b72d7de57 100644 --- a/entries/jQuery.noConflict.xml +++ b/entries/jQuery.noConflict.xml @@ -10,66 +10,81 @@ Relinquish jQuery's control of the $ variable.

      Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them.

      -

      If for some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.

      +

      If for some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict( true ) from the second version will return the globally scoped jQuery variables to those of the first version.

      
      -<script type="text/javascript" src="other_lib.js"></script>
      -<script type="text/javascript" src="jquery.js"></script>
      -<script type="text/javascript">
      -  $.noConflict();
      -  // Code that uses other library's $ can follow here.
      +<script src="other_lib.js"></script>
      +<script src="jquery.js"></script>
      +<script>
      +$.noConflict();
      +// Code that uses other library's $ can follow here.
       </script>
      -
      +

      This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within callback passed to .ready() you can use $ if you wish without fear of conflicts later:

      
      -<script type="text/javascript" src="other_lib.js"></script>
      -<script type="text/javascript" src="jquery.js"></script>
      -<script type="text/javascript">
      -  $.noConflict();
      -  jQuery(document).ready(function($) {
      -    // Code that uses jQuery's $ can follow here.
      -  });
      -  // Code that uses other library's $ can follow here.
      +<script src="other_lib.js"></script>
      +<script src="jquery.js"></script>
      +<script>
      +$.noConflict();
      +jQuery( document ).ready(function( $ ) {
      +  // Code that uses jQuery's $ can follow here.
      +});
      +// Code that uses other library's $ can follow here.
       </script>
      -
      +

      If necessary, you can free up the jQuery name as well by passing true as an argument to the method. This is rarely necessary, and if you must do this (for example, if you need to use multiple versions of the jQuery library on the same page), you need to consider that most plug-ins rely on the presence of the jQuery variable and may not operate correctly in this situation.

      Map the original object that was referenced by $ back to $. - +$( "content" ).style.display = "none"; +]]> Revert the $ alias and then create and execute a function to provide the $ as a jQuery alias inside the function's scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library. - + +// Other code using $ as an alias to the other library +]]> Create a different alias instead of jQuery to use in the rest of the script. - +$( "content" ).style.display = "none"; +]]> Completely move jQuery to a new namespace in another object. - - + +jQuery( "div > p" ).hide(); +]]> Load two versions of jQuery (not recommended). Then, restore jQuery's globally scoped variables to the first loaded jQuery. @@ -77,18 +92,17 @@ jQuery("div > p").hide();]]>

      Before $.noConflict(true)

      - + ]]> -
      +
      
      +[
      +  { name: "first", value: "Rick" },
      +  { name: "last", value: "Astley" },
      +  { name: "job", value: "Rock Star" }
      +]
      +    
      +

      Note: Because some frameworks have limited ability to parse serialized arrays, developers should exercise caution when passing an obj argument that contains objects or arrays nested within another array.

      -
      -
      -

      Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Until such time that there is, the $.param method will remain in its current form.

      -
      + +
      +

      Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.

      +

      In jQuery 1.4, HTML5 input elements are also serialized.

      We can display a query string representation of an object and a URI-decoded version of the same as follows:

      -
      var myObject = {
      +    
      
      +var myObject = {
         a: {
           one: 1,
           two: 2,
           three: 3
         },
      -  b: [1,2,3]
      +  b: [ 1, 2, 3 ]
       };
      -var recursiveEncoded = $.param(myObject);
      -var recursiveDecoded = decodeURIComponent($.param(myObject));
      +var recursiveEncoded = $.param( myObject );
      +var recursiveDecoded = decodeURIComponent( $.param( myObject ) );
       
      -alert(recursiveEncoded);
      -alert(recursiveDecoded);
      -
      +alert( recursiveEncoded ); +alert( recursiveDecoded ); +

      The values of recursiveEncoded and recursiveDecoded are alerted as follows:

      - a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3 + a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
      - a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3 + a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

      To emulate the behavior of $.param() prior to jQuery 1.4, we can set the traditional argument to true:

      -
      var myObject = {
      +    
      
      +var myObject = {
         a: {
           one: 1,
           two: 2,
           three: 3
         },
      -  b: [1,2,3]
      +  b: [ 1, 2, 3 ]
       };
      -var shallowEncoded = $.param(myObject, true);
      -var shallowDecoded = decodeURIComponent(shallowEncoded);
      +var shallowEncoded = $.param( myObject, true );
      +var shallowDecoded = decodeURIComponent( shallowEncoded );
       
      -alert(shallowEncoded);
      -alert(shallowDecoded);
      +alert( shallowEncoded );
      +alert( shallowDecoded );
       

      The values of shallowEncoded and shallowDecoded are alerted as follows:

      - a=%5Bobject+Object%5D&b=1&b=2&b=3 + a=%5Bobject+Object%5D&b=1&b=2&b=3
      - a=[object+Object]&b=1&b=2&b=3 + a=[object+Object]&b=1&b=2&b=3

      Serialize a key/value object. - - + + Serialize a few complex objects =1.4: -$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4" +$.param({ a: [ 2, 3, 4 ] }); // "a[]=2&a[]=3&a[]=4" // <=1.3.2: -$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a=[object+Object]&d=3&d=4&d=[object+Object]" -// >=1.4: -$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5" +$.param({ a: { b: 1, c: 2 }, d: [ 3, 4, { e: 5 } ] }); +// "a=[object+Object]&d=3&d=4&d=[object+Object]" +// >=1.4: +$.param({ a: { b: 1, c: 2 }, d: [ 3, 4, { e: 5 } ] }); +// "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5" ]]> - + diff --git a/entries/jQuery.parseHTML.xml b/entries/jQuery.parseHTML.xml index c78dd53c2..5ff74ce77 100644 --- a/entries/jQuery.parseHTML.xml +++ b/entries/jQuery.parseHTML.xml @@ -8,17 +8,21 @@ HTML string to be parsed - DOM element to serve as the context in which the HTML fragment will be created + Document element to serve as the context in which the HTML fragment will be created A Boolean indicating whether to include scripts passed in the HTML string -

      jQuery.parseHTML uses a native DOM element creation function to convert the string to a set of DOM elements, which can then be inserted into the document.

      +

      jQuery.parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace). To prevent trailing/leading whitespace from being converted to text nodes you can pass the HTML string through jQuery.trim.

      +

      By default, the context is the current document if not specified or given as null or undefined. If the HTML was to be used in another document such as an iframe, that frame's document could be used.

      +

      As of 3.0 the default behavior is changed. If the context is not specified or given as null or undefined, a new document is used. This can potentially improve security because inline events will not execute when the HTML is parsed. Once the parsed HTML is injected into a document it does execute, but this gives tools a chance to traverse the created DOM and remove anything deemed unsafe. This improvement does not apply to internal uses of jQuery.parseHTML as they usually pass in the current document. Therefore, a statement like $( "#log" ).append( $( htmlString ) ) is still subject to the injection of malicious code.

      +

      Security Considerations

      +

      Most jQuery APIs that accept HTML strings will run scripts that are included in the HTML. jQuery.parseHTML does not run scripts in the parsed HTML unless keepScripts is explicitly true. However, it is still possible in most environments to execute scripts indirectly, for example via the <img onerror> attribute. The caller should be aware of this and guard against it by cleaning or escaping any untrusted inputs from sources such as the URL or cookies. For future compatibility, callers should not depend on the ability to run any script content when keepScripts is unspecified or false.

      - Create an array of Dom nodes using an HTML string and insert it into a div. + Create an array of DOM nodes using an HTML string and insert it into a div. my name is jQuery.", + html = $.parseHTML( str ), + nodeNames = []; // Append the parsed HTML $log.append( html ); // Gather the parsed HTML's node names $.each( html, function( i, el ) { - nodeNames[i] = "
    • " + el.nodeName + "
    • "; + nodeNames[ i ] = "
    • " + el.nodeName + "
    • "; }); // Insert the node names @@ -43,7 +47,6 @@ $log.append( "

      Node Names:

      " ); $( "
        " ) .append( nodeNames.join( "" ) ) .appendTo( $log ); - ]]>
        diff --git a/entries/jQuery.parseJSON.xml b/entries/jQuery.parseJSON.xml index 41f56861e..2023ebc83 100644 --- a/entries/jQuery.parseJSON.xml +++ b/entries/jQuery.parseJSON.xml @@ -1,5 +1,10 @@ - + + + + + + jQuery.parseJSON() 1.4.1 @@ -7,21 +12,32 @@ The JSON string to parse. - Takes a well-formed JSON string and returns the resulting JavaScript object. + Takes a well-formed JSON string and returns the resulting JavaScript value. -

        Passing in a malformed JSON string may result in an exception being thrown. For example, the following are all malformed JSON strings:

        +
        +

        As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

        +
        +

        Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

          -
        • {test: 1} (test does not have double quotes around it).
        • -
        • {'test': 1} ('test' is using single quotes instead of double quotes).
        • +
        • "{test: 1}" (test does not have double quotes around it).
        • +
        • "{'test': 1}" ('test' is using single quotes instead of double quotes).
        • +
        • "'test'" ('test' is using single quotes instead of double quotes).
        • +
        • ".1" (a number must start with a digit; "0.1" would be valid).
        • +
        • "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
        • +
        • "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also not permitted).
        -

        Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/. -

        +

        The JSON standard does not permit "control characters" such as a tab or newline. An example like $.parseJSON( '{ "testing":"1\t2\n3" }' ) will throw an error in most implementations because the JavaScript parser converts the string's tab and newline escapes into literal tab and newline; doubling the backslashes like "1\\t2\\n3" yields expected results. This problem is often seen when injecting JSON into a JavaScript file from a server-side language such as PHP.

        +

        Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string. For details on the JSON format, see https://json.org/.

        +

        Prior to jQuery 1.9, $.parseJSON returned null instead of throwing an error if it was passed an empty string, null, or undefined, even though those are not valid JSON.

        Parse a JSON string. - + -
        \ No newline at end of file + +
        diff --git a/entries/jQuery.parseXML.xml b/entries/jQuery.parseXML.xml index 1617e0c10..8829bdb95 100644 --- a/entries/jQuery.parseXML.xml +++ b/entries/jQuery.parseXML.xml @@ -19,20 +19,20 @@ ]]> - \ No newline at end of file + diff --git a/entries/jQuery.post.xml b/entries/jQuery.post.xml index 852685232..e862071fa 100644 --- a/entries/jQuery.post.xml +++ b/entries/jQuery.post.xml @@ -11,127 +11,161 @@ A plain object or string that is sent to the server with the request. - - A callback function that is executed if the request succeeds. + + + + + A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null or jQuery.noop as a placeholder. NOTE: In jQuery 3.x and older, when providing a null value for success you also have to provide the data parameter; you can set it to undefined. The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - Load data from the server using a HTTP POST request. + + 1.12-and-2.2 + + A set of key/value pairs that configure the Ajax request. All properties except for url are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a complete list of all settings. Type will automatically be set to POST. + + + Send data to the server using a HTTP POST request.

        This is a shorthand Ajax function, which is equivalent to:

        -
        $.ajax({
        +    
        
        +$.ajax({
           type: "POST",
           url: url,
           data: data,
           success: success,
           dataType: dataType
         });
        -
        +

        The success callback function is passed the returned data, which will be an XML root element or a text string depending on the MIME type of the response. It is also passed the text status of the response.

        As of jQuery 1.5, the success callback function is also passed a "jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest object).

        Most implementations will specify a success handler:

        -
        $.post('ajax/test.html', function(data) {
        -  $('.result').html(data);
        +    
        
        +$.post( "ajax/test.html", function( data ) {
        +  $( ".result" ).html( data );
         });
        -
        +

        This example fetches the requested HTML snippet and inserts it on the page.

        -

        Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

        +

        Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

        The jqXHR Object

        -

        As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

        +

        As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.post() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

        The Promise interface also allows jQuery's Ajax methods, including $.get(), to chain multiple .done(), .fail(), and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

        -
        // Assign handlers immediately after making the request,
        +    
        
        +// Assign handlers immediately after making the request,
         // and remember the jqxhr object for this request
        -var jqxhr = $.post("example.php", function() {
        -  alert("success");
        +var jqxhr = $.post( "example.php", function() {
        +  alert( "success" );
         })
        -.done(function() { alert("second success"); })
        -.fail(function() { alert("error"); })
        -.always(function() { alert("finished"); });
        +  .done(function() {
        +    alert( "second success" );
        +  })
        +  .fail(function() {
        +    alert( "error" );
        +  })
        +  .always(function() {
        +    alert( "finished" );
        +  });
         
        -// perform other work here ...
        +// Perform other work here ...
         
         // Set another completion function for the request above
        -jqxhr.always(function(){ alert("second finished"); });
        -
        +jqxhr.always(function() { + alert( "second finished" ); +}); +

        Deprecation Notice

        -

        The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

        +

        The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

        Request the test.php page, but ignore the return results. - + Request the test.php page and send some additional data along (while still ignoring the return results). - + Pass arrays of data to the server (while still ignoring the return results). - + - Send form data using ajax requests - + Send form data using Ajax requests + Alert the results from requesting test.php (HTML or XML, depending on what was returned). - + Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). - Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). - + - Post a form using ajax and put results in a div + Post a form using Ajax and put results in a div - + diff --git a/entries/jQuery.proxy.xml b/entries/jQuery.proxy.xml index 03760189d..d00748b93 100644 --- a/entries/jQuery.proxy.xml +++ b/entries/jQuery.proxy.xml @@ -1,5 +1,5 @@ - + jQuery.proxy() 1.4 @@ -46,10 +46,13 @@ Takes a function and returns a new one that will always have a particular context. +
        +

        Note: This API has been deprecated in jQuery 3.3; please use the native Function.prototype.bind method instead.

        +

        This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function if passed the original.

        -

        Be aware, however, that jQuery's event binding subsystem assigns a unique id to each event handling function in order to track it when it is used to specify the function to be unbound. The function represented by jQuery.proxy() is seen as a single function by the event subsystem, even when it is used to bind different contexts. To avoid unbinding the wrong handler, use a unique event namespace for binding and unbinding (e.g., "click.myproxy1") rather than specifying the proxied function during unbinding. -

        -

        As of jQuery 1.6, any number of additional arguments may supplied to $.proxy(), and they will be passed to the function whose context will be changed.

        +

        Be aware, however, that jQuery's event binding subsystem assigns a unique id to each event handling function in order to track it when it is used to specify the function to be unbound. The function represented by jQuery.proxy() is seen as a single function by the event subsystem, even when it is used to bind different contexts. To avoid unbinding the wrong handler, use a unique event namespace for binding and unbinding (e.g., "click.myproxy1") rather than specifying the proxied function during unbinding.

        +

        As of jQuery 1.6, any number of additional arguments may be supplied to $.proxy(), and they will be passed to the function whose context will be changed.

        +

        As of jQuery 1.9, when the context is null or undefined the proxied function will be called with the same this object as the proxy was called with. This allows $.proxy() to be used to partially apply the arguments of a function without changing the context.

        Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. @@ -60,45 +63,43 @@ @@ -109,15 +110,14 @@ $("#test")

        ]]> @@ -130,30 +130,30 @@ $("#test") ]]> +$( "#test" ) + .on( "click", proxy ); +]]>
        + diff --git a/entries/jQuery.queue.xml b/entries/jQuery.queue.xml index a355413ce..16fa17531 100644 --- a/entries/jQuery.queue.xml +++ b/entries/jQuery.queue.xml @@ -14,42 +14,63 @@ Show the queue of functions to be executed on the matched element. -

        Note: This is a low-level method, you should probably use .queue() instead.

        +

        Note: This is a low-level method, you should probably use .queue() instead.

        Show the length of the queue. + - - + - + 1.3 @@ -70,13 +91,13 @@ A string containing the name of the queue. Defaults to fx, the standard effects queue. - + The new function to add to the queue. Manipulate the queue of functions to be executed on the matched element. -

        Note: This is a low-level method, you should probably use .queue() instead.

        +

        Note: This is a low-level method, you should probably use .queue() instead.

        Every element can have one or more queues of functions attached to it by jQuery. In most applications, only one queue (called fx) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution.

        The jQuery.queue() method allows us to directly manipulate this queue of functions. Calling jQuery.queue() with a callback is particularly useful; it allows us to place a new function at the end of the queue.

        Note that when adding a function with jQuery.queue(), we should ensure that jQuery.dequeue() is eventually called so that the next function in line executes.

        @@ -84,62 +105,85 @@ Queue a custom function. +$( document.body ).on( "click", function() { + var divs = $( "div" ) + .show( "slow" ) + .animate({ left: "+=200" }, 2000 ); + jQuery.queue( divs[ 0 ], "fx", function() { + $( this ).addClass( "newcolor" ); + jQuery.dequeue( this ); + } ); + divs.animate({ left: "-=200" }, 500 ); + jQuery.queue( divs[ 0 ], "fx", function() { + $( this ).removeClass( "newcolor" ); + jQuery.dequeue( this ); + } ); + divs.slideUp(); +} ); +]]> - + Set a queue array to delete the queue. + div { + margin: 3px; + width: 40px; + height: 40px; + position: absolute; + left: 0px; + top: 30px; + background: green; + display: none; + } + div.newcolor { + background: blue; + } +]]> + + +
        +]]>
        diff --git a/entries/jQuery.ready.xml b/entries/jQuery.ready.xml new file mode 100644 index 000000000..cc1a98f16 --- /dev/null +++ b/entries/jQuery.ready.xml @@ -0,0 +1,36 @@ + + + jQuery.ready + A Promise-like object (or "thenable") that resolves when the document is ready. + + 1.8 + + +

        As of jQuery 3.0, use of this object is supported via jQuery.when or the native Promise.resolve(). Code should not make assumptions about whether this object is a jQuery.Deferred, native Promise, or some other type of promise object.

        +

        See also ready(), which makes use of this.

        +
        + + Listen for document ready using jQuery.when. + + + + Typical usage involving another promise, using jQuery.when. + + + + + + +
        diff --git a/entries/jQuery.readyException.xml b/entries/jQuery.readyException.xml new file mode 100644 index 000000000..2c534ea9f --- /dev/null +++ b/entries/jQuery.readyException.xml @@ -0,0 +1,24 @@ + + + jQuery.readyException() + Handles errors thrown synchronously in functions wrapped in jQuery(). + + 3.1 + + An error thrown in the function wrapped in jQuery(). + + + +

        This method is fired when an error is thrown synchronously in a function wrapped in jQuery() or jQuery( document ).ready(), or equivalent. By default it re-throws the error in a timeout so that it's logged in the console and passed to window.onerror instead of being swallowed. Overwrite this method if you want to handle such errors differently.

        +
        + + Pass the received error to console.error. + + + + +
        diff --git a/entries/jQuery.removeData.xml b/entries/jQuery.removeData.xml index 219a4db1a..6a92a25f4 100644 --- a/entries/jQuery.removeData.xml +++ b/entries/jQuery.removeData.xml @@ -1,5 +1,5 @@ - + jQuery.removeData() 1.2.3 @@ -12,30 +12,38 @@ Remove a previously-stored piece of data. -

        Note: This is a low-level method, you should probably use .removeData() instead.

        -

        The jQuery.removeData() method allows us to remove values that were previously set using jQuery.data(). When called with the name of a key, jQuery.removeData() deletes that particular value; when called with no arguments, all values are removed.

        +

        Note: This is a low-level method, you should probably use .removeData() instead.

        +

        The jQuery.removeData() method allows us to remove values that were previously set using jQuery.data(). When called with the name of a key, jQuery.removeData() deletes that particular value; when called with no arguments, all values are removed.

        Set a data store for 2 names then remove one of them. +var div = $( "div" )[ 0 ]; +$( "span" ).eq( 0 ).text( "" + $( "div" ).data( "test1" ) ); +jQuery.data( div, "test1", "VALUE-1" ); +jQuery.data( div, "test2", "VALUE-2" ); +$( "span" ).eq( 1 ).text( "" + jQuery.data( div, "test1" ) ); +jQuery.removeData( div, "test1" ); +$( "span" ).eq( 2 ).text( "" + jQuery.data( div, "test1" ) ); +$( "span" ).eq( 3 ).text( "" + jQuery.data( div, "test2" ) ); +]]> - + div { + margin: 2px; + color: blue; + } + span { + color: red; + } +]]> + -
        \ No newline at end of file +
        diff --git a/entries/jQuery.speed.xml b/entries/jQuery.speed.xml new file mode 100644 index 000000000..75cd1e685 --- /dev/null +++ b/entries/jQuery.speed.xml @@ -0,0 +1,46 @@ + + + jQuery.speed + Creates an object containing a set of properties ready to be used in the definition of custom animations. + + 1.0 + + + + A string indicating which easing function to use for the transition. + + + A function to call once the animation is complete. + + + + + 1.1 + + + + + + 1.1 + + + A string or number determining how long the animation will run. + + + + + A string indicating which easing function to use for the transition. + + + A function to call once the animation is complete. + + + + +

        The $.speed() method provides a way to define properties, such as duration, easing, and queue, to use in a custom animation. By using it, you don't have to implement the logic that deals with default values and optional parameters.

        +

        This method is meant for plugin developers who are creating new animation methods. Letting $.speed() do all the parameter hockey and normalization for you, rather than duplicating the logic yourself, makes your work simpler. An example of use can be found in the animated form of .addClass() of jQuery UI.

        +
        + + + +
        diff --git a/entries/jQuery.sub.xml b/entries/jQuery.sub.xml index c247e4780..04cdfdb8d 100644 --- a/entries/jQuery.sub.xml +++ b/entries/jQuery.sub.xml @@ -6,9 +6,9 @@ Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object. -

        - This method is deprecated as of jQuery 1.7 and will be moved to a plugin in jQuery 1.8. -

        +
        +

        Note: This API has been removed in jQuery 1.9.

        +

        There are two specific use cases for which jQuery.sub() was created. The first was for providing a painless way of overriding jQuery methods without completely destroying the original methods and another was for helping to do encapsulation and basic namespacing for jQuery plugins.

        Note that jQuery.sub() doesn't attempt to do any sort of isolation - that's not its intention. All the methods on the sub'd version of jQuery will still point to the original jQuery (events bound and triggered will still be through the main jQuery, data will be bound to elements through the main jQuery, Ajax queries and events will run through the main jQuery, etc.).

        Note that if you're looking to use this for plugin development you should first strongly consider using something like the jQuery UI widget factory which manages both state and plugin sub-methods. Some examples of using the jQuery UI widget factory to build a plugin.

        @@ -16,19 +16,20 @@
        Adding a method to a jQuery sub so that it isn't exposed externally: - +typeof jQuery( "body" ).myCustomMethod // undefined +]]> Override some jQuery methods to provide new functionality. @@ -37,32 +38,35 @@ typeof jQuery('body').myCustomMethod // undefined]]> var myjQuery = jQuery.sub(); myjQuery.fn.remove = function() { + // New functionality: Trigger a remove event - this.trigger("remove"); + this.trigger( "remove" ); // Be sure to call the original jQuery remove method return jQuery.fn.remove.apply( this, arguments ); }; - myjQuery(function($) { - $(".menu").click(function() { - $(this).find(".submenu").remove(); + myjQuery(function( $ ) { + $( ".menu" ).on( "click", function() { + $( this ).find( ".submenu" ).remove(); }); // A new remove event is now triggered from this copy of jQuery - $(document).on("remove", function(e) { - $(e.target).parent().hide(); + $( document ).on( "remove", function( event ) { + $( event.target ).parent().hide(); }); }); })(); // Regular jQuery doesn't trigger a remove event when removing an element -// This functionality is only contained within the modified 'myjQuery'.]]> +// This functionality is only contained within the modified 'myjQuery'. +]]> Create a plugin that returns plugin-specific methods. // Add our plugin to the original jQuery jQuery.fn.myplugin = function() { - this.addClass("plugin"); + this.addClass( "plugin" ); // Make sure our plugin returns our special plugin version of jQuery return plugin( this ); }; })(); -$(document).ready(function() { +$( document ).ready(function() { + // Call the plugin, open method now exists - $('#main').myplugin().open(); + $( "#main" ).myplugin().open(); - // Note: Calling just $("#main").open() won't work as open doesn't exist! -});]]> + // Note: Calling just $( "#main" ).open() won't work as open doesn't exist! +}); +]]> + +
        diff --git a/entries/jQuery.support.xml b/entries/jQuery.support.xml index 605aeb158..3252fd6ea 100644 --- a/entries/jQuery.support.xml +++ b/entries/jQuery.support.xml @@ -1,77 +1,18 @@ - + jQuery.support 1.3 - A collection of properties that represent the presence of different browser features or bugs. Primarily intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance. + A collection of properties that represent the presence of different browser features or bugs; intended for jQuery's internal use. -

        Rather than using $.browser to detect the current user agent and alter the page presentation based on which browser is running, it is a good practice to use feature detection. To make this process simpler, jQuery performs many such tests and sets properties of the jQuery.support object.

        -

        - Since jQuery requires these tests internally, they must be performed on every page load. Although some of these properties are documented below, they are not subject to a long deprecation/removal cycle and may be removed once internal jQuery code no longer needs them. -

        -
        -

        Following are a few resources that explain how feature detection works:

        - -
        -

        For your own project's feature-detection needs, we strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support.

        -

        The tests included in jQuery.support are as follows:

        -
          -
        • ajax is equal to true if a browser is able to create an XMLHttpRequest object.
        • -
        • boxModel is equal to true if the page is rendering according to the W3C CSS Box Model (is currently false in IE 6 and 7 when they are in Quirks Mode). This property is null until document ready occurs.
        • -
        • changeBubbles is equal to true if the change event bubbles up the DOM tree, as required by the W3C DOM event model. (It is currently false in IE, and jQuery simulates bubbling).
        • -
        • checkClone is equal to true if a browser correctly clones the checked state of radio buttons or checkboxes in document fragments.
        • -
        • checkOn is equal to true if the value of a checkbox defaults to "on" when no value is specified.
        • -
        • cors is equal to true if a browser can create an XMLHttpRequest object and if that XMLHttpRequest object has a withCredentials property. To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;. - CORS WD
        • -
        • cssFloat is equal to true if the name of the property containing the CSS float value is .cssFloat, as defined in the CSS Spec. (It is currently false in IE, it uses styleFloat instead).
        • -
        • hrefNormalized is equal to true if the .getAttribute() method retrieves the href attribute of elements unchanged, rather than normalizing it to a fully-qualified URL. (It is currently false in IE, the URLs are normalized). -
        • -
        • htmlSerialize is equal to true if the browser is able to serialize/insert <link> elements using the .innerHTML property of elements. (is currently false in IE).
        • -
        • leadingWhitespace is equal to true if the browser inserts content with .innerHTML exactly as provided—specifically, if leading whitespace characters are preserved. (It is currently false in IE 6-8).
        • -
        • noCloneChecked is equal to true if cloned DOM elements copy over the state of the .checked expando. (It is currently false in IE). (Added in jQuery 1.5.1)
        • -
        • noCloneEvent is equal to true if cloned DOM elements are created without event handlers (that is, if the event handlers on the source element are not cloned). (It is currently false in IE).
        • -
        • opacity is equal to true if a browser can properly interpret the opacity style property. (It is currently false in IE, it uses alpha filters instead).
        • -
        • optDisabled is equal to true if option elements within disabled select elements are not automatically marked as disabled.
        • -
        • optSelected is equal to true if an <option> element that is selected by default has a working selected property.
        • -
        • scriptEval() is equal to true if inline scripts are automatically evaluated and executed when inserted into the document using standard DOM manipulation methods such as .appendChild() and .createTextNode(). (It is currently false in IE, it uses .text to insert executable scripts). -
          Note: No longer supported; removed in jQuery 1.6. Prior to jQuery 1.5.1, the scriptEval() method was the static scriptEval property. The change to a method allowed the test to be deferred until first use to prevent content security policy inline-script violations.
          -
        • -
        • style is equal to true if inline styles for an element can be accessed through the DOM attribute called style, as required by the DOM Level 2 specification. In this case, .getAttribute('style') can retrieve this value; in Internet Explorer, .cssText is used for this purpose.
        • -
        • submitBubbles is equal to true if the submit event bubbles up the DOM tree, as required by the W3C DOM event model. (It is currently false in IE, and jQuery simulates bubbling).
        • -
        • tbody is equal to true if an empty <table> element can exist without a <tbody> element. According to the HTML specification, this sub-element is optional, so the property should be true in a fully-compliant browser. If false, we must account for the possibility of the browser injecting <tbody> tags implicitly. (It is currently false in IE, which automatically inserts tbody if it is not present in a string assigned to innerHTML).
        • -
        +

        A collection of properties that represent the presence of different browser features or bugs. Intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance. For your own project's feature-detection needs, we strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support.

        +

        As of jQuery 1.11 or 1.12, jQuery.support is no longer JSON-serializable; some properties point to functions that return the support test result when called. This was necessary to support lazy execution of support tests.

        - - Returns the box model for the iframe. - - - - - - Returns false if the page is in QuirksMode in Internet Explorer - - - -
        \ No newline at end of file + + +
        diff --git a/entries/jQuery.trim.xml b/entries/jQuery.trim.xml index cd31b830d..cfc537b63 100644 --- a/entries/jQuery.trim.xml +++ b/entries/jQuery.trim.xml @@ -1,5 +1,5 @@ - + jQuery.trim() 1.0 @@ -9,25 +9,33 @@ Remove the whitespace from the beginning and end of a string. +
        +

        Note: This API has been deprecated in jQuery 3.5; please use the native String.prototype.trim method instead. Unlike jQuery.trim, String.prototype.trim does not work with types other than strings (null, undefined, Number). Make sure that your code is compatible when migrating.

        +

        The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.

        - Remove the two white spaces at the start and at the end of the string. + Remove the white spaces at the start and at the end of the string. +
        
        +
        
        +]]>
           
        - Remove the two white spaces at the start and at the end of the string. - - + Remove the white spaces at the start and at the end of the string. + + -
        \ No newline at end of file + +
        diff --git a/entries/jQuery.type.xml b/entries/jQuery.type.xml index 47c1f443a..4dd56897e 100644 --- a/entries/jQuery.type.xml +++ b/entries/jQuery.type.xml @@ -1,14 +1,17 @@ - + jQuery.type() 1.4.3 - + Object to get the internal JavaScript [[Class]] of. Determine the internal JavaScript [[Class]] of an object. +
        +

        Note: This API has been deprecated in jQuery 3.3.

        +

        A number of techniques are used to determine the exact return value for an object. The [[Class]] is determined as follows:

        • If the object is undefined or null, then "undefined" or "null" is returned accordingly. @@ -19,15 +22,21 @@
        • jQuery.type( null ) === "null"
        -
      1. If the object has an internal [[Class]] equivalent to one of the browser's built-in objects, the associated name is returned. (More details about this technique.) +
      2. If the argument is either a primitive value or an instance of a standard built-in ECMAScript object, the [[Class]] internal property is used to determine the type. (More details about this technique.)
        • jQuery.type( true ) === "boolean"
        • +
        • jQuery.type( new Boolean() ) === "boolean"
        • jQuery.type( 3 ) === "number"
        • +
        • jQuery.type( new Number( 3 ) ) === "number"
        • jQuery.type( "test" ) === "string"
        • -
        • jQuery.type( function(){} ) === "function"
        • +
        • jQuery.type( new String( "test" ) ) === "string"
        • +
        • jQuery.type( function() {} ) === "function"
        • jQuery.type( [] ) === "array"
        • +
        • jQuery.type( new Array() ) === "array"
        • jQuery.type( new Date() ) === "date"
        • jQuery.type( new Error() ) === "error" // as of jQuery 1.9
        • +
        • jQuery.type( Symbol() ) === "symbol" // as of jQuery 1.9
        • +
        • jQuery.type( Object( Symbol() ) ) === "symbol" // as of jQuery 1.12
        • jQuery.type( /test/ ) === "regexp"
      3. @@ -36,9 +45,14 @@
        Find out if the parameter is a RegExp. - - + + +
        diff --git a/entries/jQuery.unique.xml b/entries/jQuery.unique.xml index ab9075193..bac613345 100644 --- a/entries/jQuery.unique.xml +++ b/entries/jQuery.unique.xml @@ -1,5 +1,5 @@ - + jQuery.unique() 1.1.3 @@ -9,34 +9,41 @@ Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. -

        The $.unique() function searches through an array of objects, sorting the array, and removing any duplicate nodes. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery.

        +
        +

        As of jQuery 3.0, this method is deprecated and just an alias of jQuery.uniqueSort(). Please use that method instead.

        +
        +

        The $.unique() function searches through an array of objects, sorting the array, and removing any duplicate nodes. A node is considered a duplicate if it is the exact same node as one already in the array; two different nodes with identical attributes are not considered to be duplicates. This function only works on plain JavaScript arrays of DOM elements, and is chiefly used internally by jQuery. You probably will never need to use it.

        As of jQuery 1.4 the results will always be returned in document order.

        Removes any duplicate elements from the array of divs. - + div { + color: blue; + } +]]> + -
        \ No newline at end of file + +
        diff --git a/entries/jQuery.uniqueSort.xml b/entries/jQuery.uniqueSort.xml new file mode 100644 index 000000000..4cc086645 --- /dev/null +++ b/entries/jQuery.uniqueSort.xml @@ -0,0 +1,46 @@ + + + jQuery.uniqueSort() + + 1.12-and-2.2 + + The Array or an Array-like object of DOM elements. + + + Sorts an array or an array-like object of DOM elements, in place, with the duplicates removed. Note that this only works on arrays/array-likes of DOM elements, not strings or numbers. + +

        The $.uniqueSort() function searches through an array or an array-like object of DOM elements, sorting the array/array-like, and removing any duplicate nodes. A node is considered a duplicate if it is the exact same node as one already in the input; two different nodes with identical attributes are not considered to be duplicates. This function only works on plain JavaScript arrays/array-like objects of DOM elements, and is chiefly used internally by jQuery. You probably will never need to use it.

        +

        Prior to jQuery 3.0, this method was called jQuery.unique().

        +

        As of jQuery 1.4 the results will always be returned in document order.

        +
        + + Removes any duplicate elements from the array of divs. + + + + + + +
        diff --git a/entries/jQuery.when.xml b/entries/jQuery.when.xml index 30dde8ff4..a27f2adc7 100644 --- a/entries/jQuery.when.xml +++ b/entries/jQuery.when.xml @@ -3,39 +3,83 @@ jQuery.when() 1.5 - - One or more Deferred objects, or plain JavaScript objects. + + Zero or more Thenable objects. + + + - Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. -

        If a single Deferred is passed to jQuery.when, its Promise object (a subset of the Deferred methods) is returned by the method. Additional methods of the Promise object can be called to attach callbacks, such as deferred.then. When the Deferred is resolved or rejected, usually by the code that created the Deferred originally, the appropriate callbacks will be called. For example, the jqXHR object returned by jQuery.ajax() is a Promise and can be used this way:

        -
        $.when( $.ajax("test.aspx") ).then(function(data, textStatus, jqXHR){
        -     alert( jqXHR.status ); // alerts 200
        -});
        -

        If a single argument is passed to jQuery.when and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected. For example:

        -
        $.when( { testing: 123 } ).done(
        -    function(x) { alert(x.testing); } /* alerts "123" */
        -    );
        -

        In the case where multiple Deferred objects are passed to jQuery.when, the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, it is passed the resolved values of all the Deferreds that were passed to jQuery.when. For example, when the Deferreds are jQuery.ajax() requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.

        -

        In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.

        +

        If no arguments are passed to jQuery.when(), it will return a resolved Promise.

        +

        If a single Deferred is passed to jQuery.when(), its Promise object (a subset of the Deferred methods) is returned by the method. Additional methods of the Promise object can be called to attach callbacks, such as deferred.then. When the Deferred is resolved or rejected, usually by the code that created the Deferred originally, the appropriate callbacks will be called. For example, the jqXHR object returned by jQuery.ajax() is a Promise-compatible object and can be used this way:

        +
        
        +$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
        +  alert( jqXHR.status ); // Alerts 200
        +});
        +    
        +

        If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. The doneCallbacks are passed the original argument. In this case any failCallbacks you might set are never called since the Deferred is never rejected. For example:

        +
        
        +$.when( { testing: 123 } ).done(function( x ) {
        +  alert( x.testing ); // Alerts "123"
        +});
        +    
        +

        If you don't pass it any arguments at all, jQuery.when() will return a resolved promise.

        +
        
        +$.when().then(function( x ) {
        +  alert( "I fired immediately" );
        +});
        +    
        +

        In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, the doneCallbacks for the master Deferred are executed. The arguments passed to the doneCallbacks provide the resolved values for each of the Deferreds, and matches the order the Deferreds were passed to jQuery.when(). For example:

        +
        
        +var d1 = $.Deferred();
        +var d2 = $.Deferred();
        +
        +$.when( d1, d2 ).done(function ( v1, v2 ) {
        +    console.log( v1 ); // "Fish"
        +    console.log( v2 ); // "Pizza"
        +});
        +
        +d1.resolve( "Fish" );
        +d2.resolve( "Pizza" );
        +    
        +

        In the event a Deferred was resolved with no value, the corresponding doneCallback argument will be undefined. If a Deferred resolved to a single value, the corresponding argument will hold that value. In the case where a Deferred resolved to multiple values, the corresponding argument will be an array of those values. For example:

        +
        
        +var d1 = $.Deferred();
        +var d2 = $.Deferred();
        +var d3 = $.Deferred();
        +
        +$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
        +    console.log( v1 ); // v1 is undefined
        +    console.log( v2 ); // v2 is "abc"
        +    console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
        +});
        +
        +d1.resolve();
        +d2.resolve( "abc" );
        +d3.resolve( 1, 2, 3, 4, 5 );
        +    
        +

        In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when() immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. The arguments passed to the failCallbacks match the signature of the failCallback for the Deferred that was rejected. If you need to perform additional processing for this case, such as canceling any unfinished Ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.

        - Execute a function after two ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). - Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). + Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. - diff --git a/entries/jQuery.xml b/entries/jQuery.xml index 1b09927ec..8df77906f 100644 --- a/entries/jQuery.xml +++ b/entries/jQuery.xml @@ -5,13 +5,14 @@ jQuery() 1.0 - + A string containing a selector expression - A DOM Element, Document, or jQuery to use as context + + A DOM Element, Document, jQuery or selector to use as context @@ -34,7 +35,7 @@ 1.0 - + An existing jQuery object to clone. @@ -45,93 +46,105 @@

        In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements:

        $( "div.foo" );
        -

        If no elements match the provided selector, the new jQuery object is "empty"; that is, it contains no elements and has .length property of 0.

        +

        If no elements match the provided selector, the new jQuery object is "empty"; that is, it contains no elements and has .length property of 0.

        Selector Context

        By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:

        
        -$( "div.foo" ).click(function() {
        -  $(  "span", this ).addClass( "bar" );
        +$( "div.foo" ).on( "click", function() {
        +  $( "span", this ).addClass( "bar" );
         });
        -
        +

        When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.

        Internally, selector context is implemented with the .find() method, so $( "span", this ) is equivalent to $( this ).find( "span" ).

        Using DOM elements

        -

        The second and third formulations of this function create a jQuery object using one or more DOM elements that were already selected in some other way.

        -

        Note: These formulations are meant to consume only DOM elements; feeding mixed data to the elementArray form is particularly discouraged.

        -

        A common use of this facility is to call jQuery methods on an element that has been passed to a callback function through the keyword this:

        +

        The second and third formulations of this function create a jQuery object using one or more DOM elements that were already selected in some other way. A jQuery object is created from the array elements in the order they appeared in the array; unlike most other multi-element jQuery operations, the elements are not sorted in DOM order. Elements will be copied from the array as-is and won't be unwrapped if they're already jQuery collections.

        +

        Please note that although you can pass text nodes and comment nodes into a jQuery collection this way, most operations don't support them. The few that do will have an explicit note on their API documentation page.

        +

        A common use of single-DOM-element construction is to call jQuery methods on an element that has been passed to a callback function through the keyword this:

        
        -$( "div.foo" ).click(function() {
        -  $(this).slideUp();
        +$( "div.foo" ).on( "click", function() {
        +  $( this ).slideUp();
         });
        -
        +

        This example causes elements to be hidden with a sliding animation when clicked. Because the handler receives the clicked item in the this keyword as a bare DOM element, the element must be passed to the $() function before applying jQuery methods to it.

        XML data returned from an Ajax call can be passed to the $() function so individual elements of the XML structure can be retrieved using .find() and other DOM traversal methods.

        
        -$.post( "url.xml", function(data) {
        -  var $child = $(data).find("child");
        -})
        -
        +$.post( "url.xml", function( data ) { + var $child = $( data ).find( "child" ); +}); +

        Cloning jQuery Objects

        When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

        Returning an Empty Set

        -

        As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set (with a .length property of 0). In previous versions of jQuery, this would return a set containing the document node.

        +

        Calling the jQuery() method with no arguments returns an empty jQuery set (with a .length property of 0). Similarly, if an argument of null, undefined, an empty array ([]), or an empty string ("") is passed, the set contains no elements.

        Working With Plain Objects

        At present, the only operations supported on plain JavaScript objects wrapped in jQuery are: .data(),.prop(),.on(), .off(), .trigger() and .triggerHandler(). The use of .data() (or any method requiring .data()) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).

        
        -// define a plain object
        -var foo = {foo: "bar", hello: "world"};
        +// Define a plain object
        +var foo = { foo: "bar", hello: "world" };
         
         // Pass it to the jQuery function
         var $foo = $( foo );
         
        -// test accessing property values
        +// Test accessing property values
         var test1 = $foo.prop( "foo" ); // bar
         
        -// test setting property values
        +// Test setting property values
         $foo.prop( "foo", "foobar" );
         var test2 = $foo.prop( "foo" ); // foobar
         
        -// test using .data() as summarized above
        -$foo.data( "keyName", "someValue");
        +// Test using .data() as summarized above
        +$foo.data( "keyName", "someValue" );
         console.log( $foo ); // will now contain a jQuery{randomNumber} property
         
        -// test binding an event name and triggering
        +// Test binding an event name and triggering
         $foo.on( "eventName", function () {
        -  console.log("eventName was called");
        +  console.log( "eventName was called" );
         });
         
        -$foo.trigger( "eventName" ); // logs "eventName was called"
        -
        +$foo.trigger( "eventName" ); // Logs "eventName was called" +

        Should .trigger( "eventName" ) be used, it will search for an "eventName" property on the object and attempt to execute it after any attached jQuery handlers are executed. It does not check whether the property is a function or not. To avoid this behavior, .triggerHandler( "eventName" ) should be used instead.

        
        -$foo.triggerHandler( "eventName" ); // also logs "eventName was called"
        -
        +$foo.triggerHandler( "eventName" ); // Also logs "eventName was called" + Find all p elements that are children of a div element and apply a border to them. - +$( "div > p" ).css( "border", "1px solid gray" ); +]]> + Find all inputs of type radio within the first form in the document. - + Find all div elements within an XML document from an Ajax response. - + Set the background color of the page to black. - + Hide all the input elements within a form. - + @@ -143,8 +156,8 @@ $( "div > p").css("border", "1px solid gray"); A string of HTML to create on the fly. Note that this parses HTML, not XML. - - A document in which the new elements will be created + + A document in which the new elements will be created. @@ -162,59 +175,67 @@ $( "div > p").css("border", "1px solid gray");

        If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with <tag ... >). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object:

        $( "<p id='test'>My <em>new</em> text</p>" ).appendTo( "body" );

        For explicit parsing of a string to HTML, use the $.parseHTML() method.

        -

        If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) — $( "<img />" ) or $( "<img>" ), $( "<a></a>" ) or $( "<a>" ) — jQuery creates the element using the native JavaScript createElement() function.

        -

        When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser"s .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

        -

        Filtering isn't, however, limited to these tags. For example, Internet Explorer prior to version 8 will also convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

        +

        By default, elements are created with an .ownerDocument matching the document into which the jQuery library was loaded. Elements being injected into a different document should be created using that document, e.g., $("<p>hello iframe</p>", $("#myiframe").prop("contentWindow").document).

        +

        If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) — $( "<img />" ) or $( "<img>" ), $( "<a></a>" ) or $( "<a>" ) — jQuery creates the element using the native JavaScript .createElement() function.

        +

        When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

        +

        Filtering isn't, however, limited to these tags. For example, Internet Explorer prior to version 8 will also convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

        To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

        -
        $( "<a href='http://jquery.com'></a>" );
        +
        $( "<a href='https://jquery.com'></a>" );

        Tags that cannot contain elements may be quick-closed or not:

        -
        $( "<img />" );
        +      
        
        +$( "<img />" );
         $( "<input>" );
        -
        -

        When passing HTML to jQuery(), please also note that text nodes are not treated as DOM elements. With the exception of a few methods (such as .content()), they are generally otherwise ignored or removed. E.g:

        +
        +

        When passing HTML to jQuery(), note that text nodes are not treated as DOM elements. With the exception of a few methods (such as .content()), they are generally ignored or removed. E.g:

        
        -var el = $( "1<br/>2<br/>3" ); // returns [<br>, "2", <br>]
        -el  = $( "1<br/>2<br/>3 >" ); // returns [<br>, "2", <br>, "3 &gt;"]
        -
        -

        This behavior is expected.

        -

        As of jQuery 1.4, the second argument to jQuery() can accept a plain object consisting of a superset of the properties that can be passed to the .attr() method.

        -

        Important: If the second argument is passed, the HTML string in the first argument must represent a a simple element with no attributes. As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

        +var el = $( "<br>2<br>3" ); // returns [<br>, "2", <br>] +el = $( "<br>2<br>3 >" ); // returns [<br>, "2", <br>, "3 &gt;"] + +

        This behavior is expected. As of jQuery 1.9.0 (and unless using the jQuery Migrate plugin), jQuery() requires the HTML string to start with a < (i.e text nodes cannot appear at the front of the HTML string).

        +

        As of jQuery 1.4, the second argument to jQuery() can accept a plain object consisting of a superset of the properties that can be passed to the .attr() method.

        +

        Important: If the second argument is passed, the HTML string in the first argument must represent a simple element with no attributes. As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

        As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

        
         $( "
        ", { "class": "my-div", on: { touchstart: function( event ) { - // do something + // Do something } } }).appendTo( "body" );

        The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute.

        -

        While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $("<input>", {size: "4"}) calling the .size() method instead of setting the size attribute). The previous code block could thus be written instead as:

        +

        While the second argument is convenient, its flexibility can lead to unintended consequences (e.g. $( "<input>", {size: "4"} ) calling the .size() method instead of setting the size attribute). The previous code block could thus be written instead as:

        
         $( "
        " ) -.addClass( "my-div" ) -.on({ - touchstart: function( event ) { - // do something - } -}).appendTo( "body" ); -
        + .addClass( "my-div" ) + .on({ + touchstart: function( event ) { + // Do something + } + }) + .appendTo( "body" ); + Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. - + Create some DOM elements. - +}) + .appendTo( "body" ); +]]> @@ -229,20 +250,23 @@ $( "
        " )
        Binds a function to be executed when the DOM has finished loading. -

        This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn"t much use for chaining against it.

        +

        This function behaves just like $( document ).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it.

        Execute the function when the DOM is ready to be used. - Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. - +}); +]]> diff --git a/entries/jquery-2.xml b/entries/jquery-2.xml index 059e8768e..4dc645e7b 100644 --- a/entries/jquery-2.xml +++ b/entries/jquery-2.xml @@ -12,23 +12,23 @@ Determine if an object is a jQuery object
        Get the current version of jQuery running on the page - \ No newline at end of file + diff --git a/entries/keydown-shorthand.xml b/entries/keydown-shorthand.xml new file mode 100644 index 000000000..98b125b34 --- /dev/null +++ b/entries/keydown-shorthand.xml @@ -0,0 +1,36 @@ + + + .keydown() + Bind an event handler to the "keydown" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
        +

        This API is deprecated.

        +

        Instead of .keydown( handler ) or .keydown( eventData, handler ), use .on( "keydown", handler ) or .on( "keydown", eventData, handler ), respectively.

        +

        Instead of .keydown(), use .trigger( "keydown" ).

        +
        +
        + + + + +
        diff --git a/entries/keydown.xml b/entries/keydown.xml index 0988808d3..576a1ad0c 100644 --- a/entries/keydown.xml +++ b/entries/keydown.xml @@ -1,95 +1,126 @@ - - .keydown() + +Bind an event handler to the "keydown" event, or trigger that event on an element. + + + keydown event + Bind an event handler to the "keydown" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "keydown". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - - Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. -

        This method is a shortcut for .on('keydown', handler) in the first and second variations, and .trigger('keydown') in the third.

        -

        The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

        +
        +

        This page describes the keydown event. For the deprecated .keydown() method, see .keydown().

        +
        +

        The keydown event is sent to an element when the user presses a key on the keyboard. If the key is kept pressed, the event is sent every time the operating system repeats the key. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

        For example, consider the HTML:

        -
        <form>
        -  <input id="target" type="text" value="Hello there" />
        +    
        
        +<form>
        +  <input id="target" type="text" value="Hello there">
         </form>
         <div id="other">
           Trigger the handler
        -</div>
        +</div> +

        The event handler can be bound to the input field:

        -
        $('#target').keydown(function() {
        -  alert('Handler for .keydown() called.');
        -});
        +
        
        +$( "#target" ).on( "keydown", function() {
        +  alert( "Handler for `keydown` called." );
        +} );
        +    

        Now when the insertion point is inside the field, pressing a key displays the alert:

        - Handler for .keydown() called. + Handler for `keydown` called.

        -

        To trigger the event manually, apply .keydown() without an argument:

        -
        $('#other').click(function() {
        -  $('#target').keydown();
        -});
        -

        After this code executes, clicks on Trigger the handler will also alert the message.

        +

        To trigger the event manually, use .trigger( "keydown" ):

        +
        
        +$( "#other" ).on( "click", function() {
        +  $( "#target" ).trigger( "keydown" );
        +} );
        +    
        +

        After this code executes, clicks on Trigger the handler will also alert the message.

        If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. Because of event bubbling, all key presses will make their way up the DOM to the document object unless explicitly stopped.

        -

        To determine which key was pressed, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.

        +

        To determine which key was pressed, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.

        Show the event object for the keydown handler when a key is pressed in the input. +$( "#other" ).on( "click", function() { + $( "#target" ).trigger( "keydown" ); +} ); +]]> 460 - + +]]> - + +
        + + + keydown event + Trigger the "keydown" event on an element. + + 1.0 + + The string "keydown". + + + +

        See the description for .on( "keydown", ... ).

        +
        + +
        + +
        diff --git a/entries/keypress-shorthand.xml b/entries/keypress-shorthand.xml new file mode 100644 index 000000000..56a0d1d85 --- /dev/null +++ b/entries/keypress-shorthand.xml @@ -0,0 +1,36 @@ + + + .keypress() + Bind an event handler to the "keypress" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
        +

        This API is deprecated.

        +

        Instead of .keypress( handler ) or .keypress( eventData, handler ), use .on( "keypress", handler ) or .on( "keypress", eventData, handler ), respectively.

        +

        Instead of .keypress(), use .trigger( "keypress" ).

        +
        +
        + + + + +
        diff --git a/entries/keypress.xml b/entries/keypress.xml index 3a1f8a09e..089765bfa 100644 --- a/entries/keypress.xml +++ b/entries/keypress.xml @@ -1,101 +1,131 @@ - - .keypress() - Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "keypress" event, or trigger that event on an element. + + + keypress event + Bind an event handler to the "keypress" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "keypress". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - +
        +

        This page describes the keypress event. For the deprecated .keypress() method, see .keypress().

        +

        Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

        -

        This method is a shortcut for .on('keypress', handler) in the first two variations, and .trigger('keypress') in the third.

        -

        The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

        -

        A keypress event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

        +

        The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

        +

        A keypress event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form controls can always get focus so are reasonable candidates for this event type.

        For example, consider the HTML:

        -
        <form>
        +    
        
        +<form>
           <fieldset>
        -    <input id="target" type="text" value="Hello there" />
        +    <input id="target" type="text" value="Hello there">
           </fieldset>
         </form>
         <div id="other">
           Trigger the handler
        -</div>
        +</div> +

        The event handler can be bound to the input field:

        -
        $("#target").keypress(function() {
        -  alert("Handler for .keypress() called.");
        -});
        -

        Now when the insertion point is inside the field, pressing a key displays the alert:

        +
        
        +$( "#target" ).on( "keypress", function() {
        +  console.log( "Handler for `keypress` called." );
        +} );
        +    
        +

        Now when the insertion point is inside the field, pressing a key displays the log:

        - Handler for .keypress() called. + Handler for `keypress` called.

        -

        The message repeats if the key is held down. To trigger the event manually, apply .keypress() without an argument::

        -
        $('#other').click(function() {
        -  $("#target").keypress();
        -});
        -

        After this code executes, clicks on Trigger the handler will also alert the message.

        +

        To trigger the event manually, use .trigger( "keypress" ):

        +
        
        +$( "#other" ).on( "click", function() {
        +  $( "#target" ).trigger( "keypress" );
        +} );
        +    
        +

        After this code executes, clicks on the Trigger the handler div will also log the message.

        If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. Because of event bubbling, all key presses will make their way up the DOM to the document object unless explicitly stopped.

        To determine which character was entered, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the character code.

        Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

        - Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (http://api.jquery.com/resources/events.js) for the event object's output. + Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (https://api.jquery.com/resources/events.js) for the event object's output. +$( "#other" ).on( "click", function() { + $( "#target" ).trigger( "keypress" ); +} ); +]]> 460 - + +]]> - + +
        + + + keypress event + Trigger the "keypress" event on an element. + + 1.0 + + The string "keypress". + + + +

        See the description for .on( "keypress", ... ).

        +
        + +
        + +
        diff --git a/entries/keyup-shorthand.xml b/entries/keyup-shorthand.xml new file mode 100644 index 000000000..965dbeb84 --- /dev/null +++ b/entries/keyup-shorthand.xml @@ -0,0 +1,36 @@ + + + .keyup() + Bind an event handler to the "keyup" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
        +

        This API is deprecated.

        +

        Instead of .keyup( handler ) or .keyup( eventData, handler ), use .on( "keyup", handler ) or .on( "keyup", eventData, handler ), respectively.

        +

        Instead of .keyup(), use .trigger( "keyup" ).

        +
        +
        + + + + +
        diff --git a/entries/keyup.xml b/entries/keyup.xml index 92874d134..b0d6399f4 100644 --- a/entries/keyup.xml +++ b/entries/keyup.xml @@ -1,49 +1,54 @@ - - .keyup() - Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "keyup" event, or trigger that event on an element. + + + keyup event + Bind an event handler to the "keyup" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "keyup". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

        This method is a shortcut for .on('keyup', handler) in the first two variations, and .trigger('keyup') in the third.

        +
        +

        This page describes the keyup event. For the deprecated .keyup() method, see .keyup().

        +

        The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

        For example, consider the HTML:

        -
        <form>
        -  <input id="target" type="text" value="Hello there" />
        +    
        
        +<form>
        +  <input id="target" type="text" value="Hello there">
         </form>
         <div id="other">
           Trigger the handler
        -</div>
        +</div> +

        The event handler can be bound to the input field:

        -
        $('#target').keyup(function() {
        -  alert('Handler for .keyup() called.');
        -});
        -
        +
        
        +$( "#target" ).on( "keyup", function() {
        +  alert( "Handler for `keyup` called." );
        +} );
        +    

        Now when the insertion point is inside the field and a key is pressed and released, the alert is displayed:

        - Handler for .keyup() called. + Handler for `keyup` called.

        -

        To trigger the event manually, apply .keyup() without arguments:

        -
        $('#other').click(function() {
        -  $('#target').keyup();
        -});
        -

        After this code executes, clicks on Trigger the handler will also alert the message.

        +

        To trigger the event manually, use .trigger( "keyup" ):

        +
        
        +$( "#other" ).on( "click", function() {
        +  $( "#target" ).trigger( "keyup" );
        +} );
        +    
        +

        After this code executes, clicks on Trigger the handler will also alert the message.

        If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. Because of event bubbling, all key presses will make their way up the DOM to the document object unless explicitly stopped.

        To determine which key was pressed, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows. For catching actual text entry, .keypress() may be a better choice.

        @@ -51,47 +56,72 @@ Show the event object for the keyup handler (using a simple $.print plugin) when a key is released in the input. +$( "#other").on( "click", function() { + $( "#target" ).trigger( "keyup" ); +} ); +]]> 460 - + +]]> - + +
        + + + keyup event + Trigger the "keyup" event on an element. + + 1.0 + + The string "keyup". + + + +

        See the description for .on( "keyup", ... ).

        +
        + +
        + +
        diff --git a/entries/lang-selector.xml b/entries/lang-selector.xml index e7431c645..fedf3c4ce 100644 --- a/entries/lang-selector.xml +++ b/entries/lang-selector.xml @@ -1,6 +1,6 @@ - :lang Selector + :lang() Selector :lang(language) 1.9 @@ -10,9 +10,9 @@ Selects all elements of the specified language. -

        The :lang selector matches elements that have a language value equal to the supplied language code or that start with the supplied language code immediately followed by "-". For example, the selector $("div:lang(en)")will match <div lang="en"> and <div lang="en-us"> (and any of their descendant <div>s), but not <div lang="fr">

        +

        The :lang() selector matches elements that have a language value equal to the supplied language code or that start with the supplied language code immediately followed by "-". For example, the selector $("div:lang(en)")will match <div lang="en"> and <div lang="en-us"> (and any of their descendant <div>s), but not <div lang="fr">

        For HTML elements, the language value is determined by the lang attribute and possibly information from meta elements or HTTP headers.

        -

        Further discussion of this usage can be found in the W3C CSS specification.

        +

        Further discussion of this usage can be found in the W3C CSS specification.

        Color div elements according to their language. @@ -35,16 +35,41 @@ $( "div:lang(es-es)" ).addClass( "spain" ); ]]> diff --git a/entries/last-child-selector.xml b/entries/last-child-selector.xml index 5b1f6f9a3..06d8e61b1 100644 --- a/entries/last-child-selector.xml +++ b/entries/last-child-selector.xml @@ -7,35 +7,38 @@ Selects all elements that are the last child of their parent. -

        While :last matches only a single element, :last-child can match more than one: one for each parent.

        +

        While .last() matches only a single element, :last-child can match more than one: one for each parent.

        Find the last span in each matched div and add some css plus a hover state. - + span.solast { + text-decoration: line-through; + } +]]> + diff --git a/entries/last-of-type-selector.xml b/entries/last-of-type-selector.xml index c4bf93655..14bad2b49 100644 --- a/entries/last-of-type-selector.xml +++ b/entries/last-of-type-selector.xml @@ -12,29 +12,33 @@ Find the last span in each matched div and add some css plus a hover state. - + span.solast { + text-decoration: line-through; + } +]]> + diff --git a/entries/last-selector.xml b/entries/last-selector.xml index 2afd3cc49..128eec49c 100644 --- a/entries/last-selector.xml +++ b/entries/last-selector.xml @@ -1,5 +1,5 @@ - + :last Selector :last @@ -7,21 +7,27 @@ Selects the last matched element. +
        +

        As of jQuery 3.4, the :last pseudo-class is deprecated. Remove it from your selectors and filter the results later using .last().

        +

        Note that :last selects a single element by filtering the current jQuery collection and matching the last element within it.

        Finds the last table row. - - + + +]]> -
        \ No newline at end of file + +
        diff --git a/entries/last.xml b/entries/last.xml index c9327b682..73ddafa5d 100644 --- a/entries/last.xml +++ b/entries/last.xml @@ -16,17 +16,32 @@ <li>list item 4</li> <li>list item 5</li> </ul> - +

        We can apply this method to the set of list items:

        -
        $('li').last().css('background-color', 'red');
        +
        
        +$( "li" ).last().css( "background-color", "red" );
        +    

        The result of this call is a red background for the final item.

        - Highlight the last span in a paragraph. - - - + Highlight the last item in a list. + + + -
        \ No newline at end of file +
        diff --git a/entries/length.xml b/entries/length.xml index 2d67f7823..37a2d54cf 100644 --- a/entries/length.xml +++ b/entries/length.xml @@ -1,31 +1,44 @@ - + .length 1.0 The number of elements in the jQuery object. -

        The number of elements currently matched. The .size() method will return the same value.

        +

        The number of elements currently matched. The .size() method will return the same value.

        Count the divs. Click to add more. - + body { + cursor: pointer; + } + div { + width: 50px; + height: 30px; + margin: 5px; + float: left; + background: green; + } + span { + color: red; + } +]]> -
        \ No newline at end of file +
        diff --git a/entries/live.xml b/entries/live.xml index 322fc9c54..0943af956 100644 --- a/entries/live.xml +++ b/entries/live.xml @@ -7,8 +7,9 @@ A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names. - + A function to execute at the time the event is triggered. + @@ -16,11 +17,12 @@ A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names. - + An object containing data that will be passed to the event handler. - + A function to execute at the time the event is triggered. + @@ -30,30 +32,42 @@ -

        As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

        -

        This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.

        +
        +

        Note: This API has been removed in jQuery 1.9; please use on() instead.

        +
        +

        This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.

        Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

        
        -$(selector).live(events, data, handler);                // jQuery 1.3+
        -$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
        -$(document).on(events, selector, data, handler);        // jQuery 1.7+
        -
        +$( selector ).live( events, data, handler ); // jQuery 1.3+ +$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+ +$( document ).on( events, selector, data, handler ); // jQuery 1.7+ +

        The events argument can either be a space-separated list of event type names and optional namespaces, or an object of event name strings and handlers. The data argument is optional and can be omitted. For example, the following three method calls are functionally equivalent (but see below for more effective and performant ways to attach delegated event handlers):

        
        -$("a.offsite").live("click", function(){ alert("Goodbye!"); });                // jQuery 1.3+
        -$(document).delegate("a.offsite", "click", function(){ alert("Goodbye!"); });  // jQuery 1.4.3+
        -$(document).on("click", "a.offsite", function(){ alert("Goodbye!"); });        // jQuery 1.7+
        -
        +$( "a.offsite" ).live( "click", function() { + alert( "Goodbye!" ); // jQuery 1.3+ +}); +$( document ).delegate( "a.offsite", "click", function() { + alert( "Goodbye!" ); // jQuery 1.4.3+ +}); +$( document ).on( "click", "a.offsite", function() { + alert( "Goodbye!" ); // jQuery 1.7+ +}); +

        Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks. In particular, the following issues arise with the use of .live():

        • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.
        • -
        • Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.
        • +
        • Chaining methods is not supported. For example, $( "a" ).find( ".offsite, .external" ).live( ... ); is not valid and does not work as expected.
        • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
        • On mobile iOS (iPhone, iPad and iPod Touch) the click event does not bubble to the document body for most elements and cannot be used with .live() without applying one of the following workarounds: -
          1. Use natively clickable elements such as a or button, as both of these do bubble to document.
          2. Use .on() or .delegate() attached to an element below the level of document.body, since mobile iOS does bubble within the body.
          3. Apply the CSS style cursor:pointer to the element that needs to bubble clicks (or a parent including document.documentElement). Note however, this will disable copy\paste on the element and cause it to be highlighted when touched.
          -
        • -
        • Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
        • -
        • The .live() method interacts with other event methods in ways that can be surprising, e.g., $(document).off("click") removes all click handlers attached by any call to .live()!
        • +
            +
          1. Use natively clickable elements such as a or button, as both of these do bubble to document.
          2. +
          3. Use .on() or .delegate() attached to an element below the level of document.body, since mobile iOS does bubble within the body.
          4. +
          5. Apply the CSS style cursor:pointer to the element that needs to bubble clicks (or a parent including document.documentElement). Note however, this will disable copy\paste on the element and cause it to be highlighted when touched.
          6. +
          + +
        • Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
        • +
        • The .live() method interacts with other event methods in ways that can be surprising, e.g., $( document ).off( "click" ) removes all click handlers attached by any call to .live()!

        For pages still using .live(), this list of version-specific differences may be helpful:

          @@ -64,44 +78,55 @@ $(document).on("click", "a.offsite", function(){ alert("Goodbye!"); }); / Cancel a default action and prevent it from bubbling up by returning false. - + Cancel only the default action by using the preventDefault method. - +}); +]]> Bind custom events with .live(). Use an object to bind multiple live event handlers. Note that .live() calls the click, mouseover, and mouseout event handlers for all paragraphs--even new ones. + + diff --git a/entries/load-event.xml b/entries/load-event.xml index 6128ccc28..f7dbc65a7 100644 --- a/entries/load-event.xml +++ b/entries/load-event.xml @@ -1,41 +1,45 @@ - - .load() - Bind an event handler to the "load" JavaScript event. + +Bind an event handler to the "load" event, or trigger that event on an element. + + + load event + Bind an event handler to the "load" event. - 1.0 - - A function to execute when the event is triggered. + 1.7 + + The string "load". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + -

          This method is a shortcut for .on('load', handler).

          +
          +

          This page describes the load event. For the .load() method removed in jQuery 3.0, see .load().

          +

          The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

          For example, consider a page with a simple image:

          -
          <img src="book.png" alt="Book" id="book" />
          +
          
          +<img src="book.png" alt="Book" id="book">
          +    

          The event handler can be bound to the image:

          -
          $('#book').load(function() {
          -  // Handler for .load() called.
          -});
          +
          
          +$( "#book" ).on( "load", function() {
          +  // Handler for `load` called.
          +} );
          +    

          As soon as the image has been loaded, the handler is called.

          In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.

          -
          -

          The Ajax module also has a method named .load(). Which one is fired depends on the set of arguments passed.

          -
          -
          +

          Caveats of the load event when used with images -

          A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

          +

          A common challenge developers attempt to solve using the load shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

          • It doesn't work consistently nor reliably cross-browser
          • It doesn't fire correctly in WebKit if the image src is set to the same src as before
          • @@ -43,26 +47,48 @@
          • Can cease to fire for images that already live in the browser's cache

          -
          -
          + +

          Note: The .live() and .delegate() methods cannot be used to detect the load event of an iframe. The load event does not correctly bubble up the parent document and the event.target isn't set by Firefox, IE9 or Chrome, which is required to do event delegation.

          -
          +
          Run a function when the page is fully loaded including graphics. - + - Add the class bigImg to all images with height greater then 100 upon each image load. - +} ); +]]> - + +
          + + + load event + Trigger the "load" event on an element. + + 1.0 + + The string "load". + + + +

          See the description for .on( "load", ... ).

          +
          + +
          + +
          diff --git a/entries/load-shorthand.xml b/entries/load-shorthand.xml new file mode 100644 index 000000000..1c5873cb0 --- /dev/null +++ b/entries/load-shorthand.xml @@ -0,0 +1,40 @@ + + + .load() + Bind an event handler to the "load" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API has been removed in jQuery 3.0.

          +

          Instead of .load( handler ) or .load( eventData, handler ), use .on( "load", handler ) or .on( "load", eventData, handler ), respectively.

          +

          Instead of .load(), use .trigger( "load" ).

          +
          +
          +

          The Ajax module also has a method named .load(). Which one is fired depends on the set of arguments passed.

          +
          +
          + + + + + +
          diff --git a/entries/load.xml b/entries/load.xml index 6a0d718da..c0f6a46fc 100644 --- a/entries/load.xml +++ b/entries/load.xml @@ -11,92 +11,114 @@ A plain object or string that is sent to the server with the request. - + + + + A callback function that is executed when the request completes. - Load data from the server and place the returned HTML into the matched element. + Load data from the server and place the returned HTML into the matched elements. -
          -

          Note: The event handling suite also has a method named .load(). jQuery determines which method to fire based on the set of arguments passed to it.

          -
          -

          This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

          -
          $('#result').load('ajax/test.html');
          +
          +

          Note: Prior to jQuery 3.0, the event handling suite also had a method named .load(). Older versions of jQuery determined which method to fire based on the set of arguments passed to it.

          +
          +

          This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched elements to the returned data. This means that most uses of the method can be quite simple:

          +
          
          +$( "#result" ).load( "ajax/test.html" );
          +    

          If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent.

          Callback Function

          If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.

          -
          $('#result').load('ajax/test.html', function() {
          -  alert('Load was performed.');
          -});
          +
          
          +$( "#result" ).load( "ajax/test.html", function() {
          +  alert( "Load was performed." );
          +});
          +    

          In the two examples above, if the current document does not contain an element with an ID of "result," the .load() method is not executed.

          Request Method

          The POST method is used if data is provided as an object; otherwise, GET is assumed.

          Loading Page Fragments

          -

          The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

          +

          The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

          We could modify the example above to use only part of the document that is fetched:

          -
          $('#result').load('ajax/test.html #container');
          +
          
          +$( "#result" ).load( "ajax/test.html #container" );
          +    

          When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

          jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

          Script Execution

          -

          When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below: -

          +

          When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

          Here, any JavaScript loaded into #a as a part of the document will successfully execute.

          
          -$('#a').load('article.html');
          -
          +$( "#a" ).load( "article.html" ); +

          However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

          
          -$('#b').load('article.html #target');
          -
          +$( "#b" ).load( "article.html #target" ); +
          - Load the main page's footer navigation into an ordered list. + Load another page's list items into an ordered list. + body { + font-size: 12px; + font-family: Arial; + } +]]> Display a notice if the Ajax request encounters an error. +]]> + body { + font-size: 12px; + font-family: Arial; + } +]]> +]]> Load the feeds.html file into the div with the ID of feeds. - - + + pass arrays of data to the server. - + Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding. - + diff --git a/entries/lt-selector.xml b/entries/lt-selector.xml index 2e158f62b..703c427f1 100644 --- a/entries/lt-selector.xml +++ b/entries/lt-selector.xml @@ -1,34 +1,49 @@ - + :lt() Selector - :lt(index) + :lt(index) 1.0 Zero-based index. + + :lt(-index) + 1.8 + + Zero-based index, counting backwards from the last element. + + Select all elements at an index less than index within the matched set. +
          +

          As of jQuery 3.4, the :lt pseudo-class is deprecated. Remove it from your selectors and filter the results later using .slice(). For example, :lt(3) can be replaced with a call to .slice( 0, 3 ).

          +

          index-related selectors

          The index-related selectors (including this "less than" selector) filter the set of elements that have matched the expressions that precede them. They narrow the set down based on the order of the elements within this matched set. For example, if elements are first selected with a class selector (.myclass) and four elements are returned, these elements are given indices 0 through 3 for the purposes of these selectors.

          -

          Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $('.myclass:lt(1)') selects the first element in the document with the class myclass, rather than selecting no elements. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

          +

          Note that since JavaScript arrays use 0-based indexing, these selectors reflect that fact. This is why $( ".myclass:lt(1)" ) selects the first element in the document with the class myclass, rather than selecting no elements. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification.

          +

          Prior to jQuery 1.8, the :lt(index) selector did not accept a negative value for index

          - Finds TDs less than the one with the 4th index (TD#4). - - + + +]]> +
          diff --git a/entries/map.xml b/entries/map.xml index 4fbe4168c..101fa001b 100644 --- a/entries/map.xml +++ b/entries/map.xml @@ -3,7 +3,10 @@ .map() 1.2 - + + + + A function object that will be invoked for each element in the current set. @@ -33,103 +36,123 @@ </div> </fieldset> </form> - +

          To get a comma-separated list of checkbox IDs:

          -
          $(':checkbox').map(function() {
          -      return this.id;
          -    }).get().join();
          +
          
          +$( ":checkbox" )
          +  .map(function() {
          +    return this.id;
          +  })
          +  .get()
          +  .join();
          +    

          The result of this call is the string, "two,four,six,eight".

          Within the callback function, this refers to the current DOM element for each iteration. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns null or undefined, no element will be inserted.

          Build a list of all the values within a form. - + p { + color: red; + } +]]> + A contrived example to show some functionality. - A"); - $(replacement[1]).append("Extra - B"); + } else if ( index === 2 ) { + + // Make two of the third item and add some text + replacement = [ replacement, $( "
        • " ).get( 0 ) ]; + $( replacement[ 0 ] ).append( " - A" ); + $( replacement[ 1 ] ).append( "Extra - B" ); } - /* replacement will be a dom element, null, - or an array of dom elements */ + // Replacement will be a dom element, null, + // or an array of dom elements return replacement; }); -$("#results").append(mappedItems); - +$( "#results" ).append( mappedItems ); ]]> - + body { + font-size: 16px; + } + ul { + float: left; + margin: 0 30px; + color: blue; + } + #results { + color: red; + } +]]> + Equalize the heights of the divs. + div { + width: 40px; + float: left; + } + input { + clear: left; + } +]]> diff --git a/entries/mousedown-shorthand.xml b/entries/mousedown-shorthand.xml new file mode 100644 index 000000000..d5de95b1b --- /dev/null +++ b/entries/mousedown-shorthand.xml @@ -0,0 +1,36 @@ + + + .mousedown() + Bind an event handler to the "mousedown" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API is deprecated.

          +

          Instead of .mousedown( handler ) or .mousedown( eventData, handler ), use .on( "mousedown", handler ) or .on( "mousedown", eventData, handler ), respectively.

          +

          Instead of .mousedown(), use .trigger( "mousedown" ).

          +
          +
          + + + + +
          diff --git a/entries/mousedown.xml b/entries/mousedown.xml index 68a4e086b..5ce0e273d 100644 --- a/entries/mousedown.xml +++ b/entries/mousedown.xml @@ -1,27 +1,27 @@ - - .mousedown() - Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "mousedown" event, or trigger that event on an element. + + + mousedown event + Bind an event handler to the "mousedown" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "mousedown". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

          This method is a shortcut for .on('mousedown', handler) in the first variation, and .trigger('mousedown') in the second.

          +
          +

          This page describes the mousedown event. For the deprecated .mousedown() method, see .mousedown().

          +

          The mousedown event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed. Any HTML element can receive this event.

          For example, consider the HTML:

          <div id="target">
          @@ -29,41 +29,67 @@
           </div>
           <div id="other">
             Trigger the handler
          -</div>
          -

          +</div> + +

          -

          +
          Figure 1 - Illustration of the rendered HTML
          +

          The event handler can be bound to any <div>:

          -
          $('#target').mousedown(function() {
          -  alert('Handler for .mousedown() called.');
          -});
          +
          
          +$( "#target" ).on( "mousedown", function() {
          +  alert( "Handler for `mousedown` called." );
          +} );
          +    

          Now if we click on this element, the alert is displayed:

          - Handler for .mousedown() called. + Handler for `mousedown` called.

          We can also trigger the event when a different element is clicked:

          -
          $('#other').click(function() {
          -  $('#target').mousedown();
          -});
          -

          After this code executes, clicks on Trigger the handler will also alert the message.

          -

          The mousedown event is sent when any mouse button is clicked. To act only on specific buttons, we can use the event object's which property. Not all browsers support this property (Internet Explorer uses button instead), but jQuery normalizes the property so that it is safe to use in any browser. The value of which will be 1 for the left button, 2 for the middle button, or 3 for the right button.

          +
          
          +$( "#other" ).on( "click", function() {
          +  $( "#target" ).trigger( "mousedown" );
          +} );
          +    
          +

          After this code executes, clicks on Trigger the handler will also alert the message.

          +

          The mousedown event is sent when any mouse button is clicked. To act only on specific buttons, we can use the event object's which property. Not all browsers support this property (Internet Explorer uses button instead), but jQuery normalizes the property so that it is safe to use in any browser. The value of which will be 1 for the left button, 2 for the middle button, or 3 for the right button.

          This event is primarily useful for ensuring that the primary button was used to begin a drag operation; if ignored, strange results can occur when the user attempts to use a context menu. While the middle and right buttons can be detected with these properties, this is not reliable. In Opera and Safari, for example, right mouse button clicks are not detectable by default.

          If the user clicks on an element, drags away from it, and releases the button, this is still counted as a mousedown event. This sequence of actions is treated as a "canceling" of the button press in most user interfaces, so it is usually better to use the click event unless we know that the mousedown event is preferable for a particular situation.

          Show texts when mouseup and mousedown event triggering. - - +
          + + + mousedown event + Trigger the "mousedown" event on an element. + + 1.0 + + The string "mousedown". + + + +

          See the description for .on( "mousedown", ... ).

          +
          + + +
          + +
          diff --git a/entries/mouseenter-shorthand.xml b/entries/mouseenter-shorthand.xml new file mode 100644 index 000000000..49b2285a3 --- /dev/null +++ b/entries/mouseenter-shorthand.xml @@ -0,0 +1,36 @@ + + + .mouseenter() + Bind an event handler to the "mouseenter" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API is deprecated.

          +

          Instead of .mouseenter( handler ) or .mouseenter( eventData, handler ), use .on( "mouseenter", handler ) or .on( "mouseenter", eventData, handler ), respectively.

          +

          Instead of .mouseenter(), use .trigger( "mouseenter" ).

          +
          +
          + + + + +
          diff --git a/entries/mouseenter.xml b/entries/mouseenter.xml index 1dc1ffb17..d22329266 100644 --- a/entries/mouseenter.xml +++ b/entries/mouseenter.xml @@ -1,30 +1,31 @@ - - .mouseenter() - Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. + +Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. + + + mouseenter event + Bind an event handler to be fired when the mouse enters an element. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "mouseenter". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

          This method is a shortcut for .on('mouseenter', handler) in the first two variations, and .trigger('mouseenter') in the third.

          +
          +

          This page describes the mouseenter event. For the deprecated .mouseenter() method, see .mouseenter().

          +

          The mouseenter JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

          For example, consider the HTML:

          -
          <div id="outer">
          +    
          
          +<div id="outer">
             Outer
             <div id="inner">
               Inner
          @@ -34,69 +35,102 @@
             Trigger the handler
           </div>
           <div id="log"></div>
          -

          +

          -

          +
          Figure 1 - Illustration of the rendered HTML
          +

          The event handler can be bound to any element:

          -
          $('#outer').mouseenter(function() {
          -  $('#log').append('<div>Handler for .mouseenter() called.</div>');
          -});
          -

          Now when the mouse pointer moves over the Outer <div>, the message is appended to <div id="log">. You can also trigger the event when another element is clicked:

          -
          $('#other').click(function() {
          -      $('#outer').mouseenter();
          -    });
          -

          After this code executes, clicks on Trigger the handler will also append the message.

          -

          The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.

          +
          
          +$( "#outer" ).on( "mouseenter", function() {
          +  $( "#log" ).append( "<div>Handler for `mouseenter` called.</div>" );
          +} );
          +    
          +

          Now when the mouse pointer moves over the Outer <div>, the message is appended to <div id="log">. You can also trigger the event when another element is clicked:

          +
          
          +$( "#other" ).on( "click", function() {
          +  $( "#outer" ).trigger( "mouseenter" );
          +} );
          +    
          +

          After this code executes, clicks on Trigger the handler will also append the message.

          +

          The mouseenter event differs from mouseover in the way it handles event bubbling. If mouseover were used in this example, then when the mouse pointer moved over the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseenter event, on the other hand, only triggers its handler when the mouse enters the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse enters the Outer element, but not the Inner element.

          Show texts when mouseenter and mouseout event triggering. mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. - + + + + mouseenter event + Trigger the "mouseenter" event on an element. + + 1.0 + + The string "mouseenter". + + + +

          See the description for .on( "mouseenter", ... ).

          +
          + + +
          + + diff --git a/entries/mouseleave-shorthand.xml b/entries/mouseleave-shorthand.xml new file mode 100644 index 000000000..9ff235eb8 --- /dev/null +++ b/entries/mouseleave-shorthand.xml @@ -0,0 +1,36 @@ + + + .mouseleave() + Bind an event handler to the "mouseleave" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API is deprecated.

          +

          Instead of .mouseleave( handler ) or .mouseleave( eventData, handler ), use .on( "mouseleave", handler ) or .on( "mouseleave", eventData, handler ), respectively.

          +

          Instead of .mouseleave(), use .trigger( "mouseleave" ).

          +
          +
          + + + + +
          diff --git a/entries/mouseleave.xml b/entries/mouseleave.xml index 1082b0409..98c1ff971 100644 --- a/entries/mouseleave.xml +++ b/entries/mouseleave.xml @@ -1,30 +1,31 @@ - - .mouseleave() - Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. + +Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. + + + mouseleave event + Bind an event handler to be fired when the mouse leaves an element. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "mouseleave". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

          This method is a shortcut for .on('mouseleave', handler) in the first two variations, and .trigger('mouseleave') in the third.

          +
          +

          This page describes the mouseleave event. For the deprecated .mouseleave() method, see .mouseleave().

          +

          The mouseleave JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser. This event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.

          For example, consider the HTML:

          -
          <div id="outer">
          +    
          
          +<div id="outer">
             Outer
             <div id="inner">
               Inner
          @@ -34,68 +35,100 @@
             Trigger the handler
           </div>
           <div id="log"></div>
          -

          +

          -

          +
          Figure 1 - Illustration of the rendered HTML
          +

          The event handler can be bound to any element:

          -
          $('#outer').mouseleave(function() {
          -  $('#log').append('<div>Handler for .mouseleave() called.</div>');
          -});
          -

          Now when the mouse pointer moves out of the Outer <div>, the message is appended to <div id="log">. You can also trigger the event when another element is clicked:

          -
          $('#other').click(function() {
          -  $('#outer').mouseleave();
          -});
          -

          After this code executes, clicks on Trigger the handler will also append the message.

          -

          The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

          +
          
          +$( "#outer" ).on( "mouseleave", function() {
          +  $( "#log" ).append( "<div>Handler for `mouseleave` called.</div>" );
          +} );
          +    
          +

          Now when the mouse pointer moves out of the Outer <div>, the message is appended to <div id="log">. You can also trigger the event when another element is clicked:

          +
          
          +$( "#other" ).on( "click", function() {
          +  $( "#outer" ).trigger( "mouseleave" );
          +} );
          +    
          +

          After this code executes, clicks on Trigger the handler will also append the message.

          +

          The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

          Show number of times mouseout and mouseleave events are triggered. mouseout fires when the pointer moves out of child element as well, while mouseleave fires only when the pointer moves out of the bound element. - + + + + mouseleave event + Trigger the "mouseleave" event on an element. + + 1.0 + + The string "mouseleave". + + + +

          See the description for .on( "mouseleave", ... ).

          +
          + + +
          + + diff --git a/entries/mousemove-shorthand.xml b/entries/mousemove-shorthand.xml new file mode 100644 index 000000000..7b5e5c314 --- /dev/null +++ b/entries/mousemove-shorthand.xml @@ -0,0 +1,36 @@ + + + .mousemove() + Bind an event handler to the "mousemove" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API is deprecated.

          +

          Instead of .mousemove( handler ) or .mousemove( eventData, handler ), use .on( "mousemove", handler ) or .on( "mousemove", eventData, handler ), respectively.

          +

          Instead of .mousemove(), use .trigger( "mousemove" ).

          +
          +
          + + + + +
          diff --git a/entries/mousemove.xml b/entries/mousemove.xml index 48d4a5340..5aaeef0b6 100644 --- a/entries/mousemove.xml +++ b/entries/mousemove.xml @@ -1,93 +1,132 @@ - - .mousemove() - Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "mousemove" event, or trigger that event on an element. + + + mousemove event + Bind an event handler to the "mousemove" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "mousemove". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

          This method is a shortcut for .on('mousemove', handler) in the first two variations, and .trigger('mousemove') in the third.

          +
          +

          This page describes the mousemove event. For the deprecated .mousemove() method, see .mousemove().

          +

          The mousemove event is sent to an element when the mouse pointer moves inside the element. Any HTML element can receive this event.

          For example, consider the HTML:

          -
          <div id="target">
          +    
          
          +<div id="target">
             Move here
           </div>
           <div id="other">
             Trigger the handler
           </div>
          -<div id="log"></div>
          +<div id="log"></div> +

          The event handler can be bound to the target:

          -
          $("#target").mousemove(function(event) {
          -  var msg = "Handler for .mousemove() called at ";
          +    
          
          +$( "#target" ).on( "mousemove", function( event ) {
          +  var msg = "Handler for `mousemove` called at ";
             msg += event.pageX + ", " + event.pageY;
          -  $("#log").append("<div>" + msg + "</div>");
          -});
          + $( "#log" ).append( "<div>" + msg + "</div>" ); +} ); +

          Now when the mouse pointer moves within the target button, the messages are appended to <div id="log">:

          - Handler for .mousemove() called at (399, 48) + Handler for `mousemove` called at (399, 48)
          - Handler for .mousemove() called at (398, 46) + Handler for `mousemove` called at (398, 46)
          - Handler for .mousemove() called at (397, 44) + Handler for `mousemove` called at (397, 44)
          - Handler for .mousemove() called at (396, 42) + Handler for `mousemove` called at (396, 42)

          -

          To trigger the event manually, apply .mousemove() without an argument:

          -
          $("#other").click(function() {
          -  $("#target").mousemove();
          -});
          +

          To trigger the event manually, use .trigger( "mousemove" ):

          +
          
          +$( "#other" ).on( "click", function() {
          +  $( "#target" ).trigger( "mousemove" );
          +} );
          +    

          After this code executes, clicks on the Trigger button will also append the message:

          - Handler for .mousemove() called at (undefined, undefined) + Handler for `mousemove` called at (undefined, undefined)

          When tracking mouse movement, you usually need to know the actual position of the mouse pointer. The event object that is passed to the handler contains some information about the mouse coordinates. Properties such as .clientX, .offsetX, and .pageX are available, but support for them differs between browsers. Fortunately, jQuery normalizes the .pageX and .pageY properties so that they can be used in all browsers. These properties provide the X and Y coordinates of the mouse pointer relative to the top-left corner of the document, as illustrated in the example output above.

          Keep in mind that the mousemove event is triggered whenever the mouse pointer moves, even for a pixel. This means that hundreds of events can be generated over a very small amount of time. If the handler has to do any significant processing, or if multiple handlers for the event exist, this can be a serious performance drain on the browser. It is important, therefore, to optimize mousemove handlers as much as possible, and to unbind them as soon as they are no longer needed.

          -

          A common pattern is to bind the mousemove handler from within a mousedown hander, and to unbind it from a corresponding mouseup handler. If implementing this sequence of events, remember that the mouseup event might be sent to a different HTML element than the mousemove event was. To account for this, the mouseup handler should typically be bound to an element high up in the DOM tree, such as <body>.

          +

          A common pattern is to bind the mousemove handler from within a mousedown handler, and to unbind it from a corresponding mouseup handler. If implementing this sequence of events, remember that the mouseup event might be sent to a different HTML element than the mousemove event was. To account for this, the mouseup handler should typically be bound to an element high up in the DOM tree, such as <body>.

          Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window, which in this case is the iframe. 300 - +
          +]]>
          - +
          + + + mousemove event + Trigger the "mousemove" event on an element. + + 1.0 + + The string "mousemove". + + + +

          See the description for .on( "mousemove", ... ).

          +
          + + +
          + +
          diff --git a/entries/mouseout-shorthand.xml b/entries/mouseout-shorthand.xml new file mode 100644 index 000000000..25761ce44 --- /dev/null +++ b/entries/mouseout-shorthand.xml @@ -0,0 +1,36 @@ + + + .mouseout() + Bind an event handler to the "mouseout" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API is deprecated.

          +

          Instead of .mouseout( handler ) or .mouseout( eventData, handler ), use .on( "mouseout", handler ) or .on( "mouseout", eventData, handler ), respectively.

          +

          Instead of .mouseout(), use .trigger( "mouseout" ).

          +
          +
          + + + + +
          diff --git a/entries/mouseout.xml b/entries/mouseout.xml index 67557c55a..3b0148287 100644 --- a/entries/mouseout.xml +++ b/entries/mouseout.xml @@ -1,30 +1,31 @@ - - .mouseout() - Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "mouseout" event, or trigger that event on an element. + + + mouseout event + Bind an event handler to the "mouseout" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "mouseout". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

          This method is a shortcut for .on('mouseout', handler) in the first two variation, and .trigger('mouseout') in the third.

          +
          +

          This page describes the mouseout event. For the deprecated .mouseout() method, see .mouseout().

          +

          The mouseout event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.

          For example, consider the HTML:

          -
          <div id="outer">
          +    
          
          +<div id="outer">
             Outer
             <div id="inner">
               Inner
          @@ -33,70 +34,104 @@
           <div id="other">
             Trigger the handler
           </div>
          -<div id="log"></div>
          -

          +<div id="log"></div> +

          +
          -

          +
          Figure 1 - Illustration of the rendered HTML
          +

          The event handler can be bound to any element:

          -
          $('#outer').mouseout(function() {
          -  $('#log').append('Handler for .mouseout() called.');
          -});
          -

          Now when the mouse pointer moves out of the Outer <div>, the message is appended to <div id="log">. To trigger the event manually, apply .mouseout() without an argument::

          -
          $('#other').click(function() {
          -  $('#outer').mouseout();
          -});
          -

          After this code executes, clicks on Trigger the handler will also append the message.

          -

          This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times. See the discussion for .mouseleave() for a useful alternative.

          +
          
          +$( "#outer" ).on( "mouseout", function() {
          +  $( "#log" ).append( "Handler for `mouseout` called." );
          +} );
          +    
          +

          Now when the mouse pointer moves out of the Outer <div>, the message is appended to <div id="log">. To trigger the event manually, use .trigger( "mouseout" ):

          +
          
          +$( "#other" ).on( "click", function() {
          +  $( "#outer" ).trigger( "mouseout" );
          +} );
          +    
          +

          After this code executes, clicks on Trigger the handler will also append the message.

          +

          This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times. See the discussion for .mouseleave() for a useful alternative.

          Show the number of times mouseout and mouseleave events are triggered. mouseout fires when the pointer moves out of the child element as well, while mouseleave fires only when the pointer moves out of the bound element. - +
          + + + mouseout event + Trigger the "mouseout" event on an element. + + 1.0 + + The string "mouseout". + + + +

          See the description for .on( "mouseout", ... ).

          +
          + + +
          + +
          diff --git a/entries/mouseover-shorthand.xml b/entries/mouseover-shorthand.xml new file mode 100644 index 000000000..25bc4c013 --- /dev/null +++ b/entries/mouseover-shorthand.xml @@ -0,0 +1,36 @@ + + + .mouseover() + Bind an event handler to the "mouseover" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
          +

          This API is deprecated.

          +

          Instead of .mouseover( handler ) or .mouseover( eventData, handler ), use .on( "mouseover", handler ) or .on( "mouseover", eventData, handler ), respectively.

          +

          Instead of .mouseover(), use .trigger( "mouseover" ).

          +
          +
          + + + + +
          diff --git a/entries/mouseover.xml b/entries/mouseover.xml index 1dfed9c69..6897db069 100644 --- a/entries/mouseover.xml +++ b/entries/mouseover.xml @@ -1,30 +1,31 @@ - - .mouseover() - Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "mouseover" event, or trigger that event on an element. + + + mouseover event + Bind an event handler to the "mouseover" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "mouseover". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

          This method is a shortcut for .on('mouseover', handler) in the first two variations, and .trigger('mouseover') in the third.

          +
          +

          This page describes the mouseover event. For the deprecated .mouseover() method, see .mouseover().

          +

          The mouseover event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

          For example, consider the HTML:

          -
          <div id="outer">
          +    
          
          +<div id="outer">
             Outer
             <div id="inner">
               Inner
          @@ -33,48 +34,70 @@
           <div id="other">
             Trigger the handler
           </div>
          -<div id="log"></div>
          -

          +<div id="log"></div> +

          +
          -

          +
          Figure 1 - Illustration of the rendered HTML
          +

          The event handler can be bound to any element:

          -
          $('#outer').mouseover(function() {
          -  $('#log').append('<div>Handler for .mouseover() called.</div>');
          -});
          -

          Now when the mouse pointer moves over the Outer <div>, the message is appended to <div id="log">. We can also trigger the event when another element is clicked:

          -
          $('#other').click(function() {
          -      $('#outer').mouseover();
          -      });
          -

          After this code executes, clicks on Trigger the handler will also append the message.

          -

          This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.

          +
          
          +$( "#outer" ).on( "mouseover", function() {
          +  $( "#log" ).append( "<div>Handler for `mouseover` called.</div>" );
          +} );
          +    
          +

          Now when the mouse pointer moves over the Outer <div>, the message is appended to <div id="log">. We can also trigger the event when another element is clicked:

          +
          
          +$( "#other" ).on( "click", function() {
          +  $( "#outer" ).trigger( "mouseover" );
          +} );
          +    
          +

          After this code executes, clicks on Trigger the handler will also append the message.

          +

          This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.

          Show the number of times mouseover and mouseenter events are triggered. mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.
          - - + + + + mouseup event + Trigger the "mouseup" event on an element. + + 1.0 + + The string "mouseup". + + + +

          See the description for .on( "mouseup", ... ).

          +
          + + +
          + + diff --git a/entries/multiple-attribute-selector.xml b/entries/multiple-attribute-selector.xml index d9fb1cc8c..01b792990 100644 --- a/entries/multiple-attribute-selector.xml +++ b/entries/multiple-attribute-selector.xml @@ -18,14 +18,16 @@ Finds all inputs that have an id attribute and whose name attribute ends with man and sets the value. - - + - \ No newline at end of file + diff --git a/entries/multiple-selector.xml b/entries/multiple-selector.xml index de7804f3f..2035e5a2b 100644 --- a/entries/multiple-selector.xml +++ b/entries/multiple-selector.xml @@ -16,55 +16,70 @@ Selects the combined results of all the specified selectors. -

          You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

          +

          You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

          Finds the elements that match any of these three selectors. - - + + +]]> Show the order in the jQuery object. - + b { + color: red; + font-size: 16px; + display: block; + clear:left; + } + div, span, p { + width: 40px; + height: 40px; + float: left; + margin: 10px; + background-color: blue; + padding: 3px; + color: white; + } +]]> + - \ No newline at end of file + diff --git a/entries/next-adjacent-Selector.xml b/entries/next-adjacent-selector.xml similarity index 76% rename from entries/next-adjacent-Selector.xml rename to entries/next-adjacent-selector.xml index 2d5ec9355..3098a397d 100644 --- a/entries/next-adjacent-Selector.xml +++ b/entries/next-adjacent-selector.xml @@ -17,19 +17,21 @@
          Finds all inputs that are next to a label. - - + + +]]> - \ No newline at end of file + diff --git a/entries/next-siblings-selector.xml b/entries/next-siblings-selector.xml index 78d0f52f4..fd5fa89fa 100644 --- a/entries/next-siblings-selector.xml +++ b/entries/next-siblings-selector.xml @@ -17,33 +17,35 @@ Finds all divs that are siblings after the element with #prev as its id. Notice the span isn't selected since it is not a div and the "niece" isn't selected since it is a child of a sibling, not an actual sibling. - + - +]]> + - \ No newline at end of file + diff --git a/entries/next.xml b/entries/next.xml index 9845b3c97..0d15a5967 100644 --- a/entries/next.xml +++ b/entries/next.xml @@ -14,38 +14,50 @@

          Consider a page with a simple list on it:

          
           <ul>
          -   <li>list item 1</li>
          -   <li>list item 2</li>
          -   <li class="third-item">list item 3</li>
          -   <li>list item 4</li>
          -   <li>list item 5</li>
          +  <li>list item 1</li>
          +  <li>list item 2</li>
          +  <li class="third-item">list item 3</li>
          +  <li>list item 4</li>
          +  <li>list item 5</li>
           </ul>
          -
          +

          If we begin at the third item, we can find the element which comes just after it:

          -
          $('li.third-item').next().css('background-color', 'red');
          +
          
          +$( "li.third-item" ).next().css( "background-color", "red" );
          +    

          The result of this call is a red background behind item 4. Since we do not supply a selector expression, this following element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.

          Find the very next sibling of each disabled button and change its text "this button is disabled". - + - + span { + color: blue; + font-weight: bold; + } + button { + width: 100px; + } +]]> + Find the very next sibling of each paragraph. Keep only the ones with a class "selected". - - + + -
          \ No newline at end of file +
          diff --git a/entries/nextAll.xml b/entries/nextAll.xml index 9999371e1..e60220934 100644 --- a/entries/nextAll.xml +++ b/entries/nextAll.xml @@ -14,52 +14,73 @@

          Consider a page with a simple list on it:

          
           <ul>
          -   <li>list item 1</li>
          -   <li>list item 2</li>
          -   <li class="third-item">list item 3</li>
          -   <li>list item 4</li>
          -   <li>list item 5</li>
          +  <li>list item 1</li>
          +  <li>list item 2</li>
          +  <li class="third-item">list item 3</li>
          +  <li>list item 4</li>
          +  <li>list item 5</li>
           </ul>
          -
          +

          If we begin at the third item, we can find the elements which come after it:

          -
          $('li.third-item').nextAll().css('background-color', 'red');
          +
          
          +$( "li.third-item" ).nextAll().css( "background-color", "red" );
          +    

          The result of this call is a red background behind items 4 and 5. Since we do not supply a selector expression, these following elements are unequivocally included as part of the object. If we had supplied one, the elements would be tested for a match before they were included.

          Locate all the divs after the first and give them a class. - + + div { + width: 80px; + height: 80px; + background: #abc; + border: 2px solid black; + margin: 10px; + float: left; + } + div.after { + border-color: red; + } +]]> 150 - + Locate all the paragraphs after the second child in the body and give them a class. 200 - +
          div
          +]]>
          -
          \ No newline at end of file +
          diff --git a/entries/nextUntil.xml b/entries/nextUntil.xml index c254d923e..619b95a24 100644 --- a/entries/nextUntil.xml +++ b/entries/nextUntil.xml @@ -12,8 +12,10 @@ 1.6 - + A DOM node or jQuery object indicating where to stop matching following sibling elements. + + A string containing a selector expression to match elements against. @@ -30,32 +32,32 @@ 250px Find the siblings that follow <dt id="term-2"> up to the next <dt> and give them a red background color. Also, find <dd> siblings that follow <dt id="term-1"> up to <dt id="term-3"> and give them a green text color. - + +]]> -
          \ No newline at end of file + diff --git a/entries/not-selector.xml b/entries/not-selector.xml index b0ffdfaef..a03a40eae 100644 --- a/entries/not-selector.xml +++ b/entries/not-selector.xml @@ -17,26 +17,24 @@ Finds all inputs that are not checked and highlights the next sibling span. Notice there is no change when clicking the checkboxes since no click events have been linked. - + +]]> - \ No newline at end of file + diff --git a/entries/not.xml b/entries/not.xml index ba20ebe68..8a41ddf1c 100644 --- a/entries/not.xml +++ b/entries/not.xml @@ -3,25 +3,25 @@ .not() 1.0 - - A string containing a selector expression to match elements against. - - - - 1.0 - - One or more DOM elements to remove from the matched set. + + A string containing a selector expression, a DOM element, or an array of elements to match against the set. + + + 1.4 - - A function used as a test for each element in the set. this is the current DOM element. + + A function used as a test for each element in the set. It accepts two arguments, index, which is the element's index in the jQuery collection, and element, which is the DOM element. Within the function, this refers to the current DOM element. + + + 1.4 - + An existing jQuery object to match the current set of elements against. @@ -37,10 +37,12 @@ <li>list item 4</li> <li>list item 5</li> </ul> - +

          We can apply this method to the set of list items:

          -
          $('li').not(':even').css('background-color', 'red');
          -

          The result of this call is a red background for items 2 and 4, as they do not match the selector (recall that :even and :odd use 0-based indexing).

          +
          
          +$( "li" ).not( ":nth-child(2n)" ).css( "background-color", "red" );
          +    
          +

          The result of this call is a red background for items 1, 3 and 5, as they do not match the selector.

          Removing Specific Elements

          The second version of the .not() method allows us to remove elements from the matched set, assuming we have found those elements previously by some other means. For example, suppose our list had an id applied to one of its items:

          
          @@ -51,34 +53,46 @@
             <li>list item 4</li>
             <li>list item 5</li>
           </ul>
          -
          +

          We can fetch the third list item using the native JavaScript getElementById() function, then remove it from a jQuery object:

          
          -$('li').not(document.getElementById('notli'))
          -  .css('background-color', 'red');
          -
          +$( "li" ).not( document.getElementById( "notli" ) ) + .css( "background-color", "red" ); +

          This statement changes the color of items 1, 2, 4, and 5. We could have accomplished the same thing with a simpler jQuery expression, but this technique can be useful when, for example, other libraries provide references to plain DOM nodes.

          As of jQuery 1.4, the .not() method can take a function as its argument in the same way that .filter() does. Elements for which the function returns true are excluded from the filtered set; all other elements are included.

          +

          Note: When a CSS selector string is passed to .not(), text and comment nodes will always be removed from the resulting jQuery object during the filtering process. When a specific node or array of nodes are provided, text or comment nodes will only be removed from the jQuery object if they match one of the nodes in the filtering array.

          Adds a border to divs that are not green or blue. - + Removes the element with the ID "selected" from the set of all paragraphs. - + Removes all elements that match "div p.selected" from the total set of all paragraphs. - + - \ No newline at end of file + diff --git a/entries/nth-child-selector.xml b/entries/nth-child-selector.xml index 959f0c209..8a5efc4c0 100644 --- a/entries/nth-child-selector.xml +++ b/entries/nth-child-selector.xml @@ -10,23 +10,29 @@ Selects all elements that are the nth-child of their parent. -

          Because jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as :eq() or :even jQuery follows JavaScript's "0-indexed" counting. Given a single <ul> containing two <li>s, $('li:nth-child(1)') selects the first <li> while $('li:eq(1)') selects the second.

          -

          The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

          -

          Further discussion of this unusual usage can be found in the W3C CSS specification.

          +

          Because jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. jQuery methods like .first() or .eq() jQuery follows JavaScript's "0-indexed" counting. Given a single <ul> containing two <li>s, $( "li:nth-child(1)" ) selects the first <li> while $( "li" ).eq( 1 ) selects the second.

          +

          The :nth-child(n) pseudo-class is easily confused with the .eq( n ) call, even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With the .eq( n ) call only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

          +

          Further discussion of this unusual usage can be found in the W3C CSS specification.

          Find the second li in each matched ul and note it. - + - + + +]]> - This is a playground to see how the selector works with different strings. Notice that this is different from the :even and :odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so... + This is a playground to see how the selector works with different strings. Notice that this is different from the even and odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so... - + - + - diff --git a/entries/nth-last-of-type-selector.xml b/entries/nth-last-of-type-selector.xml index 214b3ec87..8b517e5e7 100644 --- a/entries/nth-last-of-type-selector.xml +++ b/entries/nth-last-of-type-selector.xml @@ -8,19 +8,26 @@ The index of each child to match, starting with the last one (1), the string even or odd, or an equation ( eg. :nth-last-of-type(even), :nth-last-of-type(4n) ) - Selects all elements that are the nth-child of their parent, counting from the last element to the first. + Selects all the elements that are the nth-child of their parent in relation to siblings with the same element name, counting from the last element to the first. -

          Because jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as :eq() or :even jQuery follows JavaScript's "0-indexed" counting. Given a single <ul> containing three <li>s, $('li:nth-last-of-type(1)') selects the third, last, <li>.

          -

          Further discussion of this usage can be found in the W3C CSS specification.

          +

          Because jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1. For other selector expressions such as .first() or .eq() jQuery follows JavaScript's "0-indexed" counting. Given a single <ul> containing three <li>s, $('li:nth-last-of-type(1)') selects the third, last, <li>.

          +

          Further discussion of this usage can be found in the W3C CSS specification.

          Find the second to last li in each matched ul and note it. - + - + + +]]> This is a playground to see how the selector works with different strings. - - + +]]> diff --git a/entries/odd-selector.xml b/entries/odd-selector.xml index acbf1e18a..8b907e15d 100644 --- a/entries/odd-selector.xml +++ b/entries/odd-selector.xml @@ -1,33 +1,40 @@ - + :odd Selector :odd 1.0 - Selects odd elements, zero-indexed. See also even. + Selects odd elements, zero-indexed. See also :even. +
          +

          As of jQuery 3.4, the :odd pseudo-class is deprecated. Remove it from your selectors and filter the results later using .odd() (available in jQuery 3.5.0 or newer).

          +

          In particular, note that the 0-based indexing means that, counter-intuitively, :odd selects the second element, fourth element, and so on within the matched set.

          Finds odd table rows, matching the second, fourth and so on (index 1, 3, 5 etc.). - + - + +]]> +
          diff --git a/entries/odd.xml b/entries/odd.xml new file mode 100644 index 000000000..52fe3baf6 --- /dev/null +++ b/entries/odd.xml @@ -0,0 +1,47 @@ + + + .odd() + + 3.5 + + Reduce the set of matched elements to the odd ones in the set, numbered from zero. + +

          Given a jQuery object that represents a set of DOM elements, the .odd() method constructs a new jQuery object from the odd elements in that set. Counting starts from zero!

          +

          Consider a page with a simple list on it:

          +
          
          +<ul>
          +  <li>list item 1</li>
          +  <li>list item 2</li>
          +  <li>list item 3</li>
          +  <li>list item 4</li>
          +  <li>list item 5</li>
          +</ul>
          +    
          +

          We can apply this method to the set of list items:

          +
          
          +$( "li" ).odd().css( "background-color", "red" );
          +    
          +

          The result of this call is a red background for the second & 4th items.

          +
          + + Highlight the odd items in a list. + + + + + + +
          diff --git a/entries/off.xml b/entries/off.xml index dbad704aa..fba3925c0 100644 --- a/entries/off.xml +++ b/entries/off.xml @@ -10,8 +10,9 @@ A selector which should match the one originally passed to .on() when attaching event handlers. - + A handler function previously attached for the event(s), or the special value false. + @@ -23,71 +24,98 @@ A selector which should match the one originally passed to .on() when attaching event handlers. + + 1.7 + + A jQuery.Event object. + + + + 1.7 + -

          The off() method removes event handlers that were attached with .on(). See the discussion of delegated and directly bound events on that page for more information. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names. When multiple filtering arguments are given, all of the arguments provided must match for the event handler to be removed.

          +

          The .off() method removes event handlers that were attached with .on(). See the discussion of delegated and directly bound events on that page for more information. Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names. When multiple filtering arguments are given, all of the arguments provided must match for the event handler to be removed.

          If a simple event name such as "click" is provided, all events of that type (both direct and delegated) are removed from the elements in the jQuery set. When writing code that will be used as a plugin, or simply when working with a large code base, best practice is to attach and remove events using namespaces so that the code will not inadvertently remove event handlers attached by other code. All events of all types in a specific namespace can be removed from an element by providing just a namespace, such as ".myPlugin". At minimum, either a namespace or event name must be provided.

          To remove specific delegated event handlers, provide a selector argument. The selector string must exactly match the one passed to .on() when the event handler was attached. To remove all delegated events from an element without removing non-delegated events, use the special value "**".

          -

          A handler can also be removed by specifying the function name in the handler argument. When jQuery attaches an event handler, it assigns a unique id to the handler function. Handlers proxied by jQuery.proxy() or a similar mechanism will all have the same unique id (the proxy function), so passing proxied handlers to .off may remove more handlers than intended. In those situations it is better to attach and remove event handlers using namespaces.

          +

          A handler can also be removed by specifying the function name in the handler argument. When jQuery attaches an event handler, it assigns a unique id to the handler function. Handlers proxied by jQuery.proxy() or a similar mechanism will all have the same unique id (the proxy function), so passing proxied handlers to .off may remove more handlers than intended. In those situations it is better to attach and remove event handlers using namespaces.

          As with .on(), you can pass events as an object instead of specifying an events string and handler function as separate arguments. The keys for the events object are events and/or namespaces; the values are handler functions or the special value false.

          Add and remove event handlers on the colored button. - +
          Click!
          +]]>
          Remove all event handlers from all paragraphs: - + Remove all delegated click handlers from all paragraphs: - + Remove just one previously bound handler by passing it as the third argument: - +// ... Foo will no longer be called. +$( "body" ).off( "click", "p", foo ); +]]> Unbind all delegated event handlers by their namespace: - +// Remove event handlers in the ".validator" namespace +$( "form" ).off( ".validator" ); +]]> diff --git a/entries/offset.xml b/entries/offset.xml index 545a97979..819232879 100644 --- a/entries/offset.xml +++ b/entries/offset.xml @@ -8,50 +8,69 @@ Get the current coordinates of the first element in the set of matched elements, relative to the document. -

          The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

          +

          The .offset() method allows us to retrieve the current position of an element (specifically its border box, which excludes margins) relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is more useful.

          .offset() returns an object containing the properties top and left.

          -
          -

          Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

          +
          +

          Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for margins set on the <html> document element.

          While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined.

          -
          +
          - + + Access the offset of the second paragraph: - +p.html( "left: " + offset.left + ", top: " + offset.top ); +]]> - + p { + margin-left: 10px; + } +]]> + Click to see the offset. - + +]]> @@ -63,24 +82,35 @@ div.abs { width:50px; height:50px; position:absolute; 1.4 - An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + An object containing the properties top and left, which are numbers indicating the new top and left coordinates for the elements. 1.4 - + + + + A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. Set the current coordinates of every element in the set of matched elements, relative to the document. -

          The .offset() setter method allows us to reposition an element. The element's position is specified relative to the document. If the element's position style property is currently static, it will be set to relative to allow for this repositioning.

          +

          The .offset() setter method allows us to reposition an element. The element's border-box position is specified relative to the document. If the element's position style property is currently static, it will be set to relative to allow for this repositioning.

          Set the offset of the second paragraph: - - - + + + diff --git a/entries/offsetParent.xml b/entries/offsetParent.xml index e562c9c37..c49a7044c 100644 --- a/entries/offsetParent.xml +++ b/entries/offsetParent.xml @@ -28,13 +28,15 @@ </ul>

          If we begin at item A, we can find its positioned ancestor:

          -
          $('li.item-a').offsetParent().css('background-color', 'red');
          +
          
          +$( "li.item-a" ).offsetParent().css( "background-color", "red" );
          +    

          This will change the color of list item II, which is positioned.

          Find the offsetParent of item "A." 250 - $('li.item-a').offsetParent().css('background-color', 'red'); + $( "li.item-a" ).offsetParent().css( "background-color", "red" ); +
        +]]> -
        \ No newline at end of file + +
        diff --git a/entries/on.xml b/entries/on.xml index 93549ceae..c874c4b68 100644 --- a/entries/on.xml +++ b/entries/on.xml @@ -11,10 +11,12 @@ A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - Data to be passed to the handler in event.data when an event is triggered. + Data to be passed to the handler in event.data when an event is triggered. - + A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + + @@ -26,165 +28,257 @@ A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - Data to be passed to the handler in event.data when an event occurs. + Data to be passed to the handler in event.data when an event occurs. -

        The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

        +

        The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

        Event names and namespaces

        -

        Any event names can be used for the events argument. jQuery will pass through the browser's standard JavaScript event types, calling the handler function when the browser generates events due to user actions such as click. In addition, the .trigger() method can trigger both standard browser event names and custom event names to call attached handlers.

        -

        An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, "click.myPlugin.simple" defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin") or .off("click.simple") without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces beginning with an underscore are reserved for jQuery's use.

        +

        Any event names can be used for the events argument. jQuery will pass through the browser's standard JavaScript event types, calling the handler function when the browser generates events due to user actions such as click. In addition, the .trigger() method can trigger both standard browser event names and custom event names to call attached handlers. Event names should only contain alphanumerics, underscore, and colon characters.

        +

        An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, "click.myPlugin.simple" defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin") or .off("click.simple") without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces should contain upper/lowercase letters and digits only.

        In the second form of .on(), the events argument is a plain object. The keys are strings in the same form as the events argument with space-separated event type names and optional namespaces. The value for each key is a function (or false value) that is used as the handler instead of the final argument to the method. In other respects, the two forms are identical in their behavior as described below.

        -

        Direct and delegated events

        +

        Direct and delegated event handlers

        The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble but jQuery patches these to bubble and create consistent cross-browser behavior.

        If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

        When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

        -

        Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

        -

        Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

        -

        In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

        +

        Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated event handlers to attach event handlers.

        +

        Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

        +

        In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated event handlers is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

        
        -$("#dataTable tbody tr").on("click", function(event){
        -  alert($(this).text());
        +$( "#dataTable tbody tr" ).on( "click", function() {
        +  console.log( $( this ).text() );
         });
        -
        -

        A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

        + +

        An event-delegation approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

        
        -$("#dataTable tbody").on("click", "tr", function(event){
        -  alert($(this).text());
        +$( "#dataTable tbody" ).on( "click", "tr", function() {
        +  console.log( $( this ).text() );
         });
        -
        -

        Note: Delegated events do not work for SVG.

        + +

        Note: Delegated event handlers do not work for SVG.

        The event handler and its environment

        The handler argument is a function (or the value false, see below), and is required unless you pass an object for the events argument. You can provide an anonymous handler function at the point of the .on() call, as the examples have done above, or declare a named function and pass its name:

        
        -function notify() { alert("clicked"); }
        -$("button").on("click", notify);
        -
        -

        When the browser triggers an event or other JavaScript calls jQuery's .trigger() method, jQuery passes the handler an event object it can use to analyze and change the status of the event. This object is a normalized subset of data provided by the browser; the browser's unmodified native event object is available in event.originalEvent. For example, event.type contains the event name (e.g., "resize") and event.target indicates the deepest (innermost) element where the event occurred.

        +function notify() { + alert( "clicked" ); +} +$( "button" ).on( "click", notify ); + +

        When the browser triggers an event or other JavaScript calls jQuery's .trigger() method, jQuery passes the handler an Event object it can use to analyze and change the status of the event. This object is a normalized subset of data provided by the browser; the browser's unmodified native event object is available in event.originalEvent. For example, event.type contains the event name (e.g., "resize") and event.target indicates the deepest (innermost) element where the event occurred.

        By default, most events bubble up from the original event target to the document element. At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling event.stopPropagation(). Any other handlers attached on the current element will run however. To prevent that, call event.stopImmediatePropagation(). (Event handlers bound to an element are called in the same order that they were bound.)

        -

        Similarly, a handler can call event.preventDefault() to cancel any default action that the browser may have for this event; for example, the default action on a click event is to follow the link. Not all browser events have default actions, and not all default actions can be canceled. See the W3C Events Specification for details.

        -

        Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault(). A false value can also be passed for the handler as a shorthand for function(){ return false; }. So, $("a.disabled").on("click", false); attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.

        -

        When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $(this).

        +

        Similarly, a handler can call event.preventDefault() to cancel any default action that the browser may have for this event; for example, the default action on a click event is to follow the link. Not all browser events have default actions, and not all default actions can be canceled. See the W3C Events Specification for details.

        +

        Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault(). A false value can also be passed for the handler as a shorthand for function(){ return false; }. So, $( "a.disabled" ).on( "click", false ); attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.

        +

        When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.) To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

        Passing data to the handler

        -

        If a data argument is provided to .on() and is not null or undefined, it is passed to the handler in the event.data property each time an event is triggered. The data argument can be any type, but if a string is used the selector must either be provided or explicitly passed as null so that the data is not mistaken for a selector. Best practice is to use a plain object so that multiple values can be passed as properties.

        +

        If a data argument is provided to .on() and is not null or undefined, it is passed to the handler in the event.data property each time an event is triggered. The data argument can be any type, but if a string is used the selector must either be provided or explicitly passed as null so that the data is not mistaken for a selector. Best practice is to use a plain object so that multiple values can be passed as properties.

        As of jQuery 1.4, the same event handler can be bound to an element multiple times. This is especially useful when the event.data feature is being used, or when other unique data resides in a closure around the event handler function. For example:

        
        -function greet(event) { alert("Hello "+event.data.name); }
        -$("button").on("click", { name: "Karl" }, greet);
        -$("button").on("click", { name: "Addy" }, greet);
        -
        +function greet( event ) { + alert( "Hello " + event.data.name ); +} +$( "button" ).on( "click", { + name: "Karl" +}, greet ); +$( "button" ).on( "click", { + name: "Addy" +}, greet ); +

        The above code will generate two different alerts when the button is clicked.

        -

        As an alternative or in addition to the data argument provided to the .on() method, you can also pass data to an event handler using a second argument to .trigger() or .triggerHandler().

        +

        As an alternative or in addition to the data argument provided to the .on() method, you can also pass data to an event handler using a second argument to .trigger() or .triggerHandler(). Data provided this way is passed to the event handler as further parameters after the Event object. If an array was passed to the second argument of .trigger() or .triggerHandler(), each element in the array will be presented to the event handler as an individual parameter.

        Event performance

        In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.

        Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

        -

        jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $("body").on("click", "#commentForm .addNew", addComment) use $("#commentForm").on("click", ".addNew", addComment).

        +

        jQuery can process simple selectors of the form tag#id.class very quickly when they are used to filter delegated events. So, "#myForm", "a.external", and "button" are all fast selectors. Delegated events that use more complex selectors, particularly hierarchical ones, can be several times slower--although they are still fast enough for most applications. Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment ) use $( "#commentForm" ).on( "click", ".addNew", addComment ).

        Additional notes

        -

        There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

        -

        Deprecated as of jQuery 1.8: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

        +

        Some events have dedicated pages, describing specifics of their usage. For a complete list of those events, see the events category.

        +

        Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.

        jQuery's event system requires that a DOM element allow attaching data via a property on the element, so that events can be tracked and delivered. The object, embed, and applet elements cannot attach data, and therefore cannot have jQuery events bound to them.

        The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble. When focus and blur are used to attach delegated event handlers, jQuery maps the names and delivers them as focusin and focusout respectively. For consistency and clarity, use the bubbling event type names.

        In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

        The error event on the window object uses nonstandard arguments and return value conventions, so it is not supported by jQuery. Instead, assign a handler function directly to the window.onerror property.

        +

        The handler list for an element is set when the event is first delivered. Adding or removing event handlers on the current element won't take effect until the next time the event is handled. To prevent any further event handlers from executing on an element within an event handler, call event.stopImmediatePropagation(). This behavior goes against the W3C events specification. To better understand this case, consider the following code:

        +
        var $test = $( "#test" );
        +
        +function handler1() {
        +  console.log( "handler1" );
        +  $test.off( "click", handler2 );
        +}
        +
        +function handler2() {
        +  console.log( "handler2" );
        +}
        +
        +$test.on( "click", handler1 );
        +$test.on( "click", handler2 );
        +

        In the code above, handler2 will be executed anyway the first time even if it's removed using .off(). However, the handler will not be executed the following times the click event is triggered.

        Display a paragraph's text in an alert when it is clicked: - + Pass data to the event handler, which is specified here by name: - +$( "p" ).on( "click", { foo: "bar" }, myHandler ); +]]> Cancel a form submit action and prevent the event from bubbling up by returning false: - + - Cancel only the default action by using .preventDefault(). - +}); +]]> - Stop submit events from bubbling without preventing form submit, using .stopPropagation(). - +}); +]]> + + + Pass data to the event handler using the second argument to .trigger() + + + + Use the second argument of .trigger() to pass an array of data to the event handler + Attach and trigger custom (non-browser) events. - + +]]> Attach multiple event handlers simultaneously using a plain object. - + - +}); +]]> - Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. + Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. - + Display each paragraph's text in an alert box whenever it is clicked: - + - Cancel a link's default action using the preventDefault method. - +}); +]]> + + + Attach multiple events—one on mouseenter and one on mouseleave to the same element: + diff --git a/entries/one.xml b/entries/one.xml index 295eb6528..4b98e5f91 100644 --- a/entries/one.xml +++ b/entries/one.xml @@ -1,17 +1,18 @@ .one() - Attach a handler to an event for the elements. The handler is executed at most once per element. + Attach a handler to an event for the elements. The handler is executed at most once per element per event type. 1.1 A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - An object containing data that will be passed to the event handler. + Data to be passed to the handler in event.data when an event is triggered. - + A function to execute at the time the event is triggered. + @@ -23,10 +24,11 @@ A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
        - Data to be passed to the handler in event.data when an event is triggered. + Data to be passed to the handler in event.data when an event is triggered. - + A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + @@ -38,47 +40,61 @@ A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - Data to be passed to the handler in event.data when an event occurs. + Data to be passed to the handler in event.data when an event occurs. -

        The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation. The second two forms, introduced in jQuery 1.7, are identical to .on() except that the handler is removed after the first time the event occurs at the delegated element, whether the selector matched anything or not. For example:

        -
        $("#foo").one("click", function() {
        -  alert("This will be displayed only once.");
        +    

        The .one() method is identical to .on(), except that the handler for a given element and event type is unbound after its first invocation. For example:

        +
        
        +$( "#foo" ).one( "click", function() {
        +  alert( "This will be displayed only once." );
         });
        -$("body").one("click", "#foo", function() {
        -  alert("This displays if #foo is the first thing clicked in the body.");
        -});
        -
        +

        After the code is executed, a click on the element with ID foo will display the alert. Subsequent clicks will do nothing. This code is equivalent to:

        -
        $("#foo").on("click", function( event ) {
        -  alert("This will be displayed only once.");
        -  $(this).off( event );
        +    
        
        +$( "#foo" ).on( "click", function( event ) {
        +  alert( "This will be displayed only once." );
        +  $( this ).off( event );
         });
        -
        +

        In other words, explicitly calling .off() from within a regularly-bound handler has exactly the same effect.

        If the first argument contains more than one space-separated event types, the event handler is called once for each event type.

        +
        
        +$( "#foo" ).one( "click mouseover", function( event ) {
        +  alert( "The " + event.type + " event happened!" );
        +});
        +    
        +

        In the example above the alert could be displayed twice due to the two event types (click and mouseover).

        Tie a one-time click to each div. To display the text of all paragraphs in an alert box the first time each of them is clicked: - + + + + Event handlers will trigger once per element per event type + + diff --git a/entries/only-child-selector.xml b/entries/only-child-selector.xml index a8aff997a..3058fd9bf 100644 --- a/entries/only-child-selector.xml +++ b/entries/only-child-selector.xml @@ -12,12 +12,19 @@ Change the text and add a border for each button that is the only child of its parent. - + +]]> diff --git a/entries/only-of-type-selector.xml b/entries/only-of-type-selector.xml index b3adfda36..542e98243 100644 --- a/entries/only-of-type-selector.xml +++ b/entries/only-of-type-selector.xml @@ -12,13 +12,25 @@ Change the text and add a border for each button that is the only child button of its parent. - + +]]> diff --git a/entries/outerHeight.xml b/entries/outerHeight.xml index e46e33e20..dc53bcb38 100644 --- a/entries/outerHeight.xml +++ b/entries/outerHeight.xml @@ -1,29 +1,115 @@ - + + Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer height of every matched element. + .outerHeight() 1.2.6 - + A Boolean indicating whether to include the element's margin in the calculation. - Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements. -

        The top and bottom padding and border are always included in the .outerHeight() calculation; if the includeMargin argument is set to true, the margin (top and bottom) is also included.

        -

        This method is not applicable to window and document objects; for these, use .height() instead.

        -

        +

        Returns the height of the element, including top and bottom padding, border, and optionally margin, in pixels. If called on an empty set of elements, returns undefined (null before jQuery 3.0).

        +

        This method is not applicable to window and document objects; for these, use .height() instead. Although .outerHeight() can be used on table elements, it may give unexpected results on tables using the border-collapse: collapse CSS property.

        +
        -

        +
        Figure 1 - Illustration of the measured height
        +
        + + Get the outerHeight of a paragraph. - - - + + + -
        \ No newline at end of file +
        + + + + 1.8 + + + + A number representing the number of pixels, or a number along with an optional unit of measure appended (as a string). + + + A Boolean indicating whether to new value should account for the element's margin. + + + + 1.8 + + + + + + + + A function returning the outer height to set. Receives the index position of the element in the set and the old outer height as arguments. Within the function, this refers to the current element in the set. + + + Set the CSS outer height of each element in the set of matched elements. + +

        When calling .outerHeight(value), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used (such as 100px, 50%, or auto).

        +
        + + + Change the outer height of each div the first time it is clicked (and change its color). + + + + + + + + + +
        + diff --git a/entries/outerWidth.xml b/entries/outerWidth.xml index dcd035fa6..2c5856bea 100644 --- a/entries/outerWidth.xml +++ b/entries/outerWidth.xml @@ -1,33 +1,115 @@ - + + Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer width of every matched element. + .outerWidth() 1.2.6 - + A Boolean indicating whether to include the element's margin in the calculation. - Get the current computed width for the first element in the set of matched elements, including padding and border. + Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements. -

        Returns the width of the element, along with left and right padding, border, and optionally margin, in pixels.

        -

        If includeMargin is omitted or false, the padding and border are included in the calculation; if true, the margin is also included.

        -

        This method is not applicable to window and document objects; for these, use .width() instead.

        -

        +

        Returns the width of the element, including left and right padding, border, and optionally margin, in pixels. If called on an empty set of elements, returns undefined (null before jQuery 3.0).

        +

        This method is not applicable to window and document objects; for these, use .width() instead. Although .outerWidth() can be used on table elements, it may give unexpected results on tables using the border-collapse: collapse CSS property.

        +
        -

        +
        Figure 1 - Illustration of the measured width
        +
        + + Get the outerWidth of a paragraph. - - + -
        \ No newline at end of file +
        + + + + 1.8 + + + + A number representing the number of pixels, or a number along with an optional unit of measure appended (as a string). + + + A Boolean indicating whether to new value should account for the element's margin. + + + + 1.8 + + + + + + + + A function returning the outer width to set. Receives the index position of the element in the set and the old outer width as arguments. Within the function, this refers to the current element in the set. + + + Set the CSS outer width of each element in the set of matched elements. + +

        When calling .outerWidth(value), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used (such as 100px, 50%, or auto).

        +
        + + + Change the outer width of each div the first time it is clicked (and change its color). + + + + + + + + + +
        + diff --git a/entries/parent-selector.xml b/entries/parent-selector.xml index 34ff77323..bd3fd7436 100644 --- a/entries/parent-selector.xml +++ b/entries/parent-selector.xml @@ -5,25 +5,33 @@ 1.0 - Select all elements that that have at least one child node (either an element or text). + Select all elements that have at least one child node (either an element or text).

        This is the inverse of :empty.

        One important thing to note regarding the use of :parent (and :empty) is that child nodes include text nodes.

        -

        The W3C recommends that the <p> element have at least one child node, even if that child is merely text (see http://www.w3.org/TR/html401/struct/text.html#edef-P). Some other elements, on the other hand, are empty (i.e. have no children) by definition: <input>, <img>, <br>, and <hr>, for example.

        +

        The W3C recommends that the <p> element have at least one child node, even if that child is merely text (see https://www.w3.org/TR/html401/struct/text.html#edef-P). Some other elements, on the other hand, are empty (i.e. have no children) by definition: <input>, <img>, <br>, and <hr>, for example.

        +

        To obtain the parents or ancestors of an existing jQuery set, see the .parent() and .parents() methods.

        Finds all tds with children, including text. - + - + + +]]> - \ No newline at end of file + diff --git a/entries/parent.xml b/entries/parent.xml index fea18d6eb..4c375255d 100644 --- a/entries/parent.xml +++ b/entries/parent.xml @@ -9,7 +9,8 @@ Get the parent of each element in the current set of matched elements, optionally filtered by a selector. -

        Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

        +

        Given a jQuery object that represents a set of DOM elements, the parent() method traverses to the immediate parent of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.

        +

        This method is similar to .parents(), except .parent() only travels a single level up the DOM tree. Also, $( "html" ).parent() method returns a set containing document whereas $( "html" ).parents() returns an empty set.

        The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.

        Consider a page with a basic nested list on it:

        
        @@ -32,49 +33,57 @@
         </ul>
             

        If we begin at item A, we can find its parents:

        -
        $('li.item-a').parent().css('background-color', 'red');
        +
        
        +$( "li.item-a" ).parent().css( "background-color", "red" );
        +    

        The result of this call is a red background for the level-2 list. Since we do not supply a selector expression, the parent element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.

        Shows the parent of each element as (parent > child). Check the View Source to see the raw html. - + +
        div, + strong, + span, + em, + b, + + + b +
        +]]>
        Find the parent element of each paragraph with a class "selected". - - + - \ No newline at end of file + diff --git a/entries/parents.xml b/entries/parents.xml index 34aa0d33d..ab51cde99 100644 --- a/entries/parents.xml +++ b/entries/parents.xml @@ -9,7 +9,8 @@ Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. -

        Given a jQuery object that represents a set of DOM elements, the .parents() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones. The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

        +

        Given a jQuery object that represents a set of DOM elements, the .parents() method allows us to search through the ancestors of these elements in the DOM tree and construct a new jQuery object from the matching elements ordered from immediate parent on up; the elements are returned in order from the closest parent to the outer ones. When multiple DOM elements are in the original set, the resulting set will be in reverse order of the original elements as well, with duplicates removed.

        +

        The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $( "html" ).parent() method returns a set containing document whereas $( "html" ).parents() returns an empty set.

        The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.

        Consider a page with a basic nested list on it:

        
        @@ -30,73 +31,96 @@
           </li>
           <li class="item-iii">III</li>
         </ul>
        -
        +

        If we begin at item A, we can find its ancestors:

        -
        $('li.item-a').parents().css('background-color', 'red');
        +
        
        +$( "li.item-a" ).parents().css( "background-color", "red" );
        +    

        The result of this call is a red background for the level-2 list, item II, and the level-1 list (and on up the DOM tree all the way to the <html> element). Since we do not supply a selector expression, all of the ancestors are part of the returned jQuery object. If we had supplied one, only the matching items among these would be included.

        Find all parent elements of each b. - + b { + color: blue; + } + strong { + color: red; + } +]]> + Click to find all unique div parent elements of each span. +}); +]]> - + + Click Hellos to toggle their parents. +]]> - \ No newline at end of file + diff --git a/entries/parentsUntil.xml b/entries/parentsUntil.xml index a7974b76d..93e5e1fa5 100644 --- a/entries/parentsUntil.xml +++ b/entries/parentsUntil.xml @@ -12,7 +12,9 @@ 1.6 - + + + A DOM node or jQuery object indicating where to stop matching ancestor elements. @@ -30,12 +32,13 @@ 220px Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color. Also, find ancestors of <li class="item-2"> that have a class of "yes" up to <ul class="level-1"> and give them a green border. +
      +]]> - \ No newline at end of file + diff --git a/entries/password-selector.xml b/entries/password-selector.xml index 2ee175a20..053e0dc29 100644 --- a/entries/password-selector.xml +++ b/entries/password-selector.xml @@ -7,43 +7,52 @@ Selects all elements of type password. -

      $(':password') is equivalent to $('[type=password]'). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':password') is equivalent to $('*:password'), so $('input:password') should be used instead.

      +

      $( ":password" ) is equivalent to $( "[type=password]" ). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ( "*" ) is implied. In other words, the bare $( ":password" ) is equivalent to $( "*:password" ), so $( "input:password" ) should be used instead.

      Finds all password inputs. - + textarea { + height: 45px; + } +]]> + - \ No newline at end of file + diff --git a/entries/position.xml b/entries/position.xml index 52c1d16cc..565f64afe 100644 --- a/entries/position.xml +++ b/entries/position.xml @@ -6,24 +6,28 @@ Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. -

      The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

      +

      The .position() method allows us to retrieve the current position of an element (specifically its margin box) relative to the offset parent (specifically its padding box, which excludes margins and borders). Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.

      Returns an object containing the properties top and left.

      -
      -

      Note: jQuery does not support getting the position coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

      -
      +
      +

      Note: jQuery does not support getting the position coordinates of hidden elements or accounting for margins set on the <html> document element.

      +
      - + + Access the position of the second paragraph: + div { + padding: 15px; + } + p { + margin-left: 10px; + } +]]> -

      Since .prepend() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $('body').prepend($newdiv1, newdiv2, existingdiv1). The type and number of arguments will largely depend on how you collect the elements in your code.

      +$( "body" ).prepend( $newdiv1, [ newdiv2, existingdiv1 ] ); + +

      Since .prepend() can accept any number of additional arguments, the same result can be achieved by passing in the three <div>s as three separate arguments, like so: $( "body" ).prepend( $newdiv1, newdiv2, existingdiv1 ). The type and number of arguments will largely depend on how you collect the elements in your code.

      + + Prepends some HTML to all paragraphs. - - - + + + Prepends a DOM Element to all paragraphs. - - - + + + Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. - - - + + + diff --git a/entries/prependTo.xml b/entries/prependTo.xml index 8a9bd66eb..d7a086446 100644 --- a/entries/prependTo.xml +++ b/entries/prependTo.xml @@ -7,23 +7,29 @@ + - A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.
      Insert every element in the set of matched elements to the beginning of the target. -

      The .prepend() and .prependTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

      +

      The .prepend() and .prependTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

      Consider the following HTML:

      -
      <h2>Greetings</h2>
      +    
      
      +<h2>Greetings</h2>
       <div class="container">
         <div class="inner">Hello</div>
         <div class="inner">Goodbye</div>
      -</div>
      +</div> +

      We can create content and insert it into several elements at once:

      -
      $('<p>Test</p>').prependTo('.inner');
      +
      
      +$( "<p>Test</p>" ).prependTo( ".inner" );
      +    

      Each inner <div> element gets this new content:

      -
      <h2>Greetings</h2>
      +    
      
      +<h2>Greetings</h2>
       <div class="container">
         <div class="inner">
           <p>Test</p>
      @@ -33,26 +39,38 @@
           <p>Test</p>
           Goodbye
         </div>
      -</div>
      +</div> +

      We can also select an element on the page and insert it into another:

      -
      $('h2').prependTo($('.container'));
      +
      
      +$( "h2" ).prependTo( $( ".container" ) );
      +    

      If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):

      -
      <div class="container">
      +    
      
      +<div class="container">
         <h2>Greetings</h2>
         <div class="inner">Hello</div>
         <div class="inner">Goodbye</div>
      -</div>
      -

      If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

      +</div> +
      +

      If there is more than one target element, however, cloned copies of the inserted element will be created for each target except the last.

      + + Prepend all spans to the element with the ID "foo" (Check .prepend() documentation for more examples) - + - + diff --git a/entries/prev.xml b/entries/prev.xml index 107e18d87..11a03f94e 100644 --- a/entries/prev.xml +++ b/entries/prev.xml @@ -7,65 +7,79 @@ A string containing a selector expression to match elements against.
      - Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

      Given a jQuery object that represents a set of DOM elements, the .prev() method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.

      The method optionally accepts a selector expression of the same type that can be passed to the $() function. If the selector is supplied, the preceding element will be filtered by testing whether it match the selector.

      Consider a page with a simple list on it:

      
       <ul>
      -   <li>list item 1</li>
      -   <li>list item 2</li>
      -   <li class="third-item">list item 3</li>
      -   <li>list item 4</li>
      -   <li>list item 5</li>
      +  <li>list item 1</li>
      +  <li>list item 2</li>
      +  <li class="third-item">list item 3</li>
      +  <li>list item 4</li>
      +  <li>list item 5</li>
       </ul>
           

      To select the element that comes immediately before item three:

      -
      $('li.third-item').prev().css('background-color', 'red');
      +
      
      +$( "li.third-item" ).prev().css( "background-color", "red" );
      +    

      The result of this call is a red background behind item 2. Since no selector expression is supplied, this preceding element is unequivocally included as part of the object. If one had been supplied, the element would be tested for a match before it was included.

      If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.

      -

      To select all preceding sibling elements, rather than just the preceding adjacent sibling, use the .prevAll() method.

      +

      To select all preceding sibling elements, rather than just the preceding adjacent sibling, use the .prevAll() method.

      Find the very previous sibling of each div. - + div { + width: 40px; + height: 40px; + margin: 10px; + float: left; + border: 2px blue solid; + padding: 2px; + } + span { + font-size: 14px; + } + p { + clear: left; + margin: 10px; + } +]]> + For each paragraph, find the very previous sibling that has a class "selected". - - + + - \ No newline at end of file + diff --git a/entries/prevAll.xml b/entries/prevAll.xml index 0d49d912d..d3eeca031 100644 --- a/entries/prevAll.xml +++ b/entries/prevAll.xml @@ -7,38 +7,151 @@ A string containing a selector expression to match elements against.
      - Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector, in the reverse document order.

      Given a jQuery object that represents a set of DOM elements, the .prevAll() method searches through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements; the elements are returned in order beginning with the closest sibling.

      The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.

      Consider a page with a simple list on it:

      
       <ul>
      -   <li>list item 1</li>
      -   <li>list item 2</li>
      -   <li class="third-item">list item 3</li>
      -   <li>list item 4</li>
      -   <li>list item 5</li>
      +  <li>list item 1</li>
      +  <li>list item 2</li>
      +  <li class="third-item">list item 3</li>
      +  <li>list item 4</li>
      +  <li>list item 5</li>
       </ul>
      -
      +

      If we begin at the third item, we can find the elements which come before it:

      -
      $('li.third-item').prevAll().css('background-color', 'red');
      +
      
      +$( "li.third-item" ).prevAll().css( "background-color", "red" );
      +    

      The result of this call is a red background behind items 1 and 2. Since we do not supply a selector expression, these preceding elements are unequivocally included as part of the object. If we had supplied one, the elements would be tested for a match before they were included.

      +

      Note: Many APIs, like append or wrapAll process node in the order in which they appear in the jQuery object. This can pose issues with APIs like .prevAll() in which the reverse document order is used. Consider the following example:

      +
      
      +<div>
      +  <div>First</div>
      +  <div>Second</div>
      +  <div class="last-item">Last</div>
      +</div>
      +    
      +

      The following call:

      +
      
      +$( ".last-item" )
      +  .prevAll()
      +  .wrapAll( "<div class='wrapper'></div>" );
      +    
      +

      would result in the following HTML:

      +
      
      +<div>
      +  <div class="wrapper">
      +    <div>Second</div>
      +    <div>First</div>
      +  </div>
      +  <div class="last-item">Last</div>
      +</div>
      +    
      +

      because "Item 2" gets appended to the wrapper div first. To work around the issue, you may use .uniqueSort() on the .prevAll() output first:

      +
      
      +$( ".last-item" )
      +  .prevAll()
      +  .uniqueSort()
      +  .wrapAll( "<div class='wrapper'></div>" );
      +    
      +

      Note that the .uniqueSort() method is only available in jQuery 3.7.0 or newer. In older versions, you will need to use $.uniqueSort() to achieve a similar effect:

      +
      
      +var prevSiblings = $( ".last-item" ).prevAll();
      +$.uniqueSort( prevSiblings );
      +prevSiblings.wrapAll( "<div class='wrapper'></div>" );
      +    
      Locate all the divs preceding the last div and give them a class. - + + + + + + Locate all the divs preceding the last item and wrap them with a div with class wrapper - with or without .uniqueSort(). + + - +
      +
      1
      +
      2
      +
      3
      +
      +]]>
      - \ No newline at end of file + diff --git a/entries/prevUntil.xml b/entries/prevUntil.xml index 1fca21bfa..5e6effb01 100644 --- a/entries/prevUntil.xml +++ b/entries/prevUntil.xml @@ -12,7 +12,9 @@ 1.6 - + + + A DOM node or jQuery object indicating where to stop matching preceding sibling elements. @@ -22,7 +24,7 @@ Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.

      Given a selector expression that represents a set of DOM elements, the .prevUntil() method searches through the predecessors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all previous siblings up to but not including the one matched by the .prevUntil() selector; the elements are returned in order from the closest sibling to the farthest.

      -

      If the selector is not matched or is not supplied, all previous siblings will be selected; in these cases it selects the same elements as the .prevAll() method does when no filter selector is provided.

      +

      If the selector is not matched or is not supplied, all previous siblings will be selected; in these cases it selects the same elements as the .prevAll() method does when no filter selector is provided.

      As of jQuery 1.6, A DOM node or jQuery object, instead of a selector, may be used for the first .prevUntil() argument.

      The method optionally accepts a selector expression for its second argument. If this argument is supplied, the elements will be filtered by testing whether they match it.

      @@ -30,14 +32,15 @@ 250px Find the siblings that precede <dt id="term-2"> up to the preceding <dt> and give them a red background color. Also, find previous <dd> siblings of <dt id="term-3"> up to <dt id="term-1"> and give them a green text color. - + +]]> - \ No newline at end of file + diff --git a/entries/promise.xml b/entries/promise.xml index 7f18a0b47..9fd1118bd 100644 --- a/entries/promise.xml +++ b/entries/promise.xml @@ -16,17 +16,17 @@

      By default, type is "fx", which means the returned Promise is resolved when all animations of the selected elements have completed.

      Resolve context and sole argument is the collection onto which .promise() has been called.

      If target is provided, .promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

      -
      +

      Note: The returned Promise is linked to a Deferred object stored on the .data() for an element. Since the.remove() method removes the element's data as well as the element itself, it will prevent any of the element's unresolved Promises from resolving. If it is necessary to remove an element from the DOM before its Promise is resolved, use .detach() instead and follow with .removeData() after resolution.

      -
      + Using .promise() on a collection with no active animation returns a resolved Promise: @@ -34,11 +34,14 @@ div.promise().done(function( arg1 ) { Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on): - \ No newline at end of file + diff --git a/entries/prop.xml b/entries/prop.xml index c93d80188..5506d40b9 100644 --- a/entries/prop.xml +++ b/entries/prop.xml @@ -1,7 +1,8 @@ Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element. - + + .prop() 1.6 @@ -12,10 +13,14 @@ Get the value of a property for the first element in the set of matched elements.

      The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

      -

      The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

      +
      +

      Note: Attempting to change the type property (or attribute) of an input element created via HTML or already in an HTML document will result in an error being thrown by Internet Explorer 6, 7, or 8.

      +
      +

      Attributes vs. Properties

      +

      The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

      For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

      Concerning boolean attributes, consider a DOM element defined by the HTML markup <input type="checkbox" checked="checked" />, and assume it is in a JavaScript variable named elem:

      - +
      - - - -
      elem.checked @@ -24,67 +29,66 @@
      - $(elem).prop("checked") + $( elem ).prop( "checked" ) true (Boolean) Will change with checkbox state
      - elem.getAttribute("checked") + elem.getAttribute( "checked" ) "checked" (String) Initial state of the checkbox; does not change
      - $(elem).attr("checked") - (1.6) + $( elem ).attr( "checked" ) + (1.6+) "checked" (String) Initial state of the checkbox; does not change
      - $(elem).attr("checked") - (1.6.1+) - "checked" (String) Will change with checkbox state
      - $(elem).attr("checked") + $( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state
      -

      -According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or an empty string value. The preferred cross-browser-compatible way to determine if a checkbox is checked is to check for a "truthy" value on the element's property using one of the following:

      +
      +

      According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false". This is true of all boolean attributes.

      +

      Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:

      • if ( elem.checked )
      • - if ( $(elem).prop("checked") ) + if ( $( elem ).prop( "checked" ) )
      • - if ( $(elem).is(":checked") ) + if ( $( elem ).is( ":checked" ) )
      -

      If using jQuery 1.6, the code if ( $(elem).attr("checked") ) will retrieve the actual content attribute, which does not change as the checkbox is checked and unchecked. It is meant only to store the default or initial value of the checked property. To maintain backwards compatability, the .attr() method in jQuery 1.6.1+ will retrieve and update the property for you so no code for boolean attributes is required to be changed to .prop(). Nevertheless, the preferred way to retrieve a checked value is with one of the options listed above. To see how this works in the latest jQuery, check/uncheck the checkbox in the example below.

      +

      The same is true for other dynamic attributes, such as selected and value.

      Display the checked property and attribute of a checkbox as it changes. +$( "input[type='checkbox']" ).prop( "checked", function( i, val ) { return !val; -}); -

      Note: If nothing is returned in the setter function (ie. function(index, prop){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

      +}); +
      +

      Note: If nothing is returned in the setter function (ie. function( index, prop ){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

      Disable all checkboxes on the page. diff --git a/entries/pushStack.xml b/entries/pushStack.xml index 9299f7167..a777d11a3 100644 --- a/entries/pushStack.xml +++ b/entries/pushStack.xml @@ -23,12 +23,14 @@ Add some elements onto the jQuery stack, then pop back off again. - + - \ No newline at end of file + diff --git a/entries/queue.xml b/entries/queue.xml index 0cd3f514f..ec66c39fd 100644 --- a/entries/queue.xml +++ b/entries/queue.xml @@ -14,36 +14,51 @@ Show the length of the queue. - + +

      The queue length is:

      +
      +]]>
      @@ -65,87 +80,121 @@ showIt(); A string containing the name of the queue. Defaults to fx, the standard effects queue. - + + The new function to add to the queue, with a function to call that will dequeue the next item.
      Manipulate the queue of functions to be executed, once for each matched element.

      Every element can have one to many queues of functions attached to it by jQuery. In most applications, only one queue (called fx) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. The typical example of this is calling multiple animation methods on an element. For example:

      -
      $('#foo').slideUp().fadeIn();
      +
      
      +$( "#foo" ).slideUp().fadeIn();
      +      

      When this statement is executed, the element begins its sliding animation immediately, but the fading transition is placed on the fx queue to be called only once the sliding transition is complete.

      The .queue() method allows us to directly manipulate this queue of functions. Calling .queue() with a callback is particularly useful; it allows us to place a new function at the end of the queue. The callback function is executed once for each element in the jQuery set.

      This feature is similar to providing a callback function with an animation method, but does not require the callback to be given at the time the animation is performed.

      -
      $('#foo').slideUp();
      -$('#foo').queue(function() {
      -  alert('Animation complete.');
      -  $(this).dequeue();
      -});
      +
      
      +$( "#foo" ).slideUp();
      +$( "#foo" ).queue(function() {
      +  alert( "Animation complete." );
      +  $( this ).dequeue();
      +});
      +      

      This is equivalent to:

      -
      $('#foo').slideUp(function() {
      -  alert('Animation complete.');
      -});
      +
      
      +$( "#foo" ).slideUp(function() {
      +  alert( "Animation complete." );
      +});
      +      

      Note that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.

      As of jQuery 1.4, the function that's called is passed another function as the first argument. When called, this automatically dequeues the next item and keeps the queue moving. We use it as follows:

      -
      $("#test").queue(function(next) {
      +      
      
      +$( "#test" ).queue(function( next ) {
           // Do some stuff...
           next();
      -});
      +}); +
      Queue a custom function. - + - + div { + margin: 3px; + width: 40px; + height: 40px; + position: absolute; + left: 0px; + top: 30px; + background: green; + display: none; + } + div.newcolor { + background: blue; + } +]]> + Set a queue array to delete the queue. - + - + div { + margin: 3px; + width: 40px; + height: 40px; + position: absolute; + left: 0px; + top: 30px; + background: green; + display: none; + } + div.newcolor { + background: blue; + } +]]> + diff --git a/entries/radio-selector.xml b/entries/radio-selector.xml index 22f58673d..6b508d86e 100644 --- a/entries/radio-selector.xml +++ b/entries/radio-selector.xml @@ -7,50 +7,58 @@ Selects all elements of type radio. -

      $(':radio') is equivalent to $('[type=radio]'). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':radio') is equivalent to $('*:radio'), so $('input:radio') should be used instead.

      -

      To select a set of associated radio buttons, you might use: $('input[name=gender]:radio')

      +

      $( ":radio" ) is equivalent to $( "[type=radio]" ). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $( ":radio" ) is equivalent to $( "*:radio" ), so $( "input:radio" ) should be used instead.

      +

      To select a set of associated radio buttons, you might use: $( "input[name=gender]:radio" )

      Finds all radio inputs. - + +
      +]]>
      - \ No newline at end of file + diff --git a/entries/ready.xml b/entries/ready.xml index e9c0f892e..20cdafa60 100644 --- a/entries/ready.xml +++ b/entries/ready.xml @@ -9,47 +9,65 @@
      -

      While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

      -

      In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

      -
      -

      The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images. -

      -
      -

      All three of the following syntaxes are equivalent:

      +

      The .ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins. When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added. As of jQuery 3.0, jQuery ensures that an exception occuring in one handler does not prevent subsequently added handlers from executing.

      + +

      Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.

      + +

      Browsers also provide the load event on the window object. When this event fires it indicates that all assets on the page have loaded, including images. This event can be watched in jQuery using $( window ).on( "load", handler ). In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

      + +

      Note that although the DOM always becomes ready before the page is fully loaded, it is usually not safe to attach a load event listener in code executed during a .ready() handler. For example, scripts can be loaded dynamically long after the page has loaded using methods such as $.getScript(). Although handlers added by .ready() will always be executed in a dynamically loaded script, the window's load event has already occurred and those listeners will never run.

      + +

      jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

      +
        -
      • - $(document).ready(handler) -
      • -
      • $().ready(handler) (this is not recommended)
      • -
      • - $(handler) -
      • +
      • $( handler )
      • +
      • $( document ).ready( handler )
      • +
      • $( "document" ).ready( handler )
      • +
      • $( "img" ).ready( handler )
      • +
      • $().ready( handler )
      -

      There is also $(document).on("ready", handler), deprecated as of jQuery 1.8. This behaves similarly to the ready method but if the ready event has already fired and you try to .on("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.

      -

      The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

      + +

      As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with "document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.

      + +

      There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.

      +

      The .ready() method is typically used with an anonymous function:

      -
      $(document).ready(function() {
      +    
      
      +$( document ).ready(function() {
         // Handler for .ready() called.
      -});
      -

      Which is equivalent to calling:

      -
      $(function() {
      -     // Handler for .ready() called.
      -    });
      -

      If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

      -

      Aliasing the jQuery Namespace

      -

      When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:

      -
      jQuery(document).ready(function($) {
      -  // Code using $ as usual goes here.
      -});
      +}); +
      +

      Which is equivalent to the recommended way of calling:

      +
      
      +$(function() {
      +  // Handler for .ready() called.
      +});
      +    
      +

      Aliasing the jQuery Object

      +

      When $.noConflict() is used to avoid namespace conflicts, the $ shortcut is no longer available. However, the .ready() handler is passed a reference to the jQuery object that called the method. This allows the handler to use a jQuery object, for example as $, without knowing its aliased name:

      +
      
      +jq2 = jQuery.noConflict();
      +jq2(function( $ ) {
      +  // Code using $ as usual goes here; the actual jQuery object is jq2
      +});
      +    
      Display a message when the DOM is loaded. - - - + + + - \ No newline at end of file + diff --git a/entries/remove.xml b/entries/remove.xml index 2fa959244..4a7ab41cb 100644 --- a/entries/remove.xml +++ b/entries/remove.xml @@ -9,53 +9,76 @@ Remove the set of matched elements from the DOM. -

      Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

      +

      Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

      Consider the following HTML:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="hello">Hello</div>
         <div class="goodbye">Goodbye</div>
      -</div>
      +</div> +

      We can target any element for removal:

      -
      $('.hello').remove();
      +
      
      +$( ".hello" ).remove();
      +    

      This will result in a DOM structure with the <div> element deleted:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="goodbye">Goodbye</div>
      -</div>
      +</div> +

      If we had any number of nested elements inside <div class="hello">, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

      We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:

      -
      $('div').remove('.hello');
      +
      
      +$( "div" ).remove( ".hello" );
      +    

      This would result in the same DOM structure:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="goodbye">Goodbye</div>
      -</div>
      +</div> +
      Removes all paragraphs from the DOM - - + + Removes all paragraphs that contain "Hello" from the DOM. Analogous to doing $("p").filter(":contains('Hello')").remove(). - - + + - \ No newline at end of file + diff --git a/entries/removeAttr.xml b/entries/removeAttr.xml index 7f4a3c902..6df348209 100644 --- a/entries/removeAttr.xml +++ b/entries/removeAttr.xml @@ -10,32 +10,34 @@ Remove an attribute from each element in the set of matched elements.

      The .removeAttr() method uses the JavaScript removeAttribute() function, but it has the advantage of being able to be called directly on a jQuery object and it accounts for different attribute naming across browsers.

      -

      Note: Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 6, 7, or 8. To avoid potential problems, use .prop() instead:

      +

      Note: Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 8, 9 and 11. To avoid potential problems, use .prop() instead:

      
      -$element.prop("onclick", null);
      -console.log("onclick property: ", $element[0].onclick);
      +$element.prop( "onclick", null );
      +console.log( "onclick property: ", $element[ 0 ].onclick );
           
      +
      - Clicking the button enables the input next to it. + Clicking the button changes the title of the input next to it. Move the mouse pointer over the text input to see the effect of adding and removing the title attribute. - @@ -44,4 +46,4 @@ console.log("onclick property: ", $element[0].onclick); - \ No newline at end of file + diff --git a/entries/removeClass.xml b/entries/removeClass.xml index 086cf5b90..d66b98919 100644 --- a/entries/removeClass.xml +++ b/entries/removeClass.xml @@ -1,83 +1,195 @@ - - .removeClass() - - 1.0 - - One or more space-separated classes to be removed from the class attribute of each matched element. - - - - 1.4 - - A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. - - + Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - -

      If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

      -

      More than one class may be removed at a time, separated by a space, from the set of matched elements, like so:

      -
      $('p').removeClass('myClass yourClass')
      -

      This method is often used with .addClass() to switch elements' classes from one to another, like so:

      -
      $('p').removeClass('myClass noClass').addClass('yourClass');
      -

      Here, the myClass and noClass classes are removed from all paragraphs, while yourClass is added.

      -

      To replace all existing classes with another class, we can use .attr('class', 'newClass') instead.

      -

      As of jQuery 1.4, the .removeClass() method allows us to indicate the class to be removed by passing in a function.

      -
      $('li:last').removeClass(function() {
      -  return $(this).prev().attr('class');
      -});
      -

      This example removes the class name of the penultimate <li> from the last <li>.

      -
      - - Remove the class 'blue' from the matched elements. - - + - - - - Remove the class 'blue' and 'under' from the matched elements. - - + + + Remove the class 'blue' and 'under' from the matched elements. + + - - - - Remove all the classes from the matched elements. - - + + + Remove the class 'blue' and 'under' from the matched elements (3.3+ syntax). + + - + + + + + + + + +
      -

      Goodbye

      ]]> - - - - - - - \ No newline at end of file + + + 1.0 + + Remove all classes from each matched element. + +

      Before jQuery version 1.12/2.2, the .removeClass() method manipulated the className property of the selected elements, not the class attribute. Once the property was changed, it was the browser that updated the attribute accordingly. This means that when the class attribute was updated and the last class name was removed, the browser might have set the attribute's value to an empty string instead of removing the attribute completely. An implication of this behavior was that this method only worked for documents with HTML DOM semantics (e.g., not pure XML documents).

      +

      As of jQuery 1.12/2.2, this behavior is changed to improve the support for XML documents, including SVG. Starting from this version, the class attribute is used instead. So, .removeClass() can be used on XML or SVG documents.

      +
      + + Remove all the classes from the matched elements. + + + + + + + + + +
      + diff --git a/entries/removeData.xml b/entries/removeData.xml index 2b9ca4095..e4dd08b1f 100644 --- a/entries/removeData.xml +++ b/entries/removeData.xml @@ -17,33 +17,40 @@ Remove a previously-stored piece of data. -

      The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value; when called with no arguments, all values are removed. Removing data from jQuery's internal .data() cache does not effect any HTML5 data- attributes in a document; use .removeAttr() to remove those.

      -

      When using .removeData("name"), jQuery will attempt to locate a data- attribute on the element if no property by that name is in the internal data cache. To avoid a re-query of the data- attribute, set the name to a value of either null or undefined (e.g. .data("name", undefined)) rather than using .removeData().

      +

      The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value. When called with no arguments, .removeData() removes all values.

      +

      + Note that .removeData() will only remove data from jQuery's internal .data() cache, and any corresponding data- attributes on the element will not be removed. A later call to data() + will therefore re-retrieve the value from the data- attribute. To prevent this, use .removeAttr() alongside .removeData() to remove the data- attribute as well. Prior to jQuery 1.4.3, + as data() did not use data- attributes, this was not an issue. +

      As of jQuery 1.7, when called with an array of keys or a string of space-separated keys, .removeData() deletes the value of each key in that array or string.

      -

      As of jQuery 1.4.3, calling .removeData() will cause the value of the property being removed to revert to the value of the data attribute of the same name in the DOM, rather than being set to undefined.

      Set a data store for 2 names then remove one of them. - + div { + margin: 2px; + color: blue; + } + span { + color: red; + } +]]> + diff --git a/entries/removeProp.xml b/entries/removeProp.xml index 2bfa478d5..cc918d297 100644 --- a/entries/removeProp.xml +++ b/entries/removeProp.xml @@ -9,24 +9,29 @@ Remove a property for the set of matched elements. -

      The .removeProp() method removes properties set by the .prop() method.

      -

      With some built-in properties of a DOM element or window object, browsers may generate an error if an attempt is made to remove the property. jQuery first assigns the value undefined to the property and ignores any error the browser generates. In general, it is only necessary to remove custom properties that have been set on an object, and not built-in (native) properties.

      -

      Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.

      +

      The .removeProp() method removes properties set by the .prop() method.

      +

      Note:This method should not be used to remove built-in (native) properties such as "checked", "disabled", "selected", or others. This can lead to unexpected behavior.

      +

      It's almost always better to use .prop() to set native properties to false instead of removing them.

      Set a numeric property on a paragraph and then remove it. - + + diff --git a/entries/replaceWith.xml b/entries/replaceWith.xml index bb7c92393..219e3e640 100644 --- a/entries/replaceWith.xml +++ b/entries/replaceWith.xml @@ -4,9 +4,10 @@ 1.2 - The content to insert. May be an HTML string, DOM element, or jQuery object. + The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + @@ -19,56 +20,74 @@ Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.

      The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner first">Hello</div>
         <div class="inner second">And</div>
         <div class="inner third">Goodbye</div>
      -</div>
      +</div> +

      The second inner <div> could be replaced with the specified HTML:

      -
      $('div.second').replaceWith('<h2>New heading</h2>');
      +
      
      +$( "div.second" ).replaceWith( "<h2>New heading</h2>" );
      +    

      This results in the structure:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner first">Hello</div>
         <h2>New heading</h2>
         <div class="inner third">Goodbye</div>
      -</div>
      +</div> +

      All inner <div> elements could be targeted at once:

      -
      $('div.inner').replaceWith('<h2>New heading</h2>');
      +
      
      +$( "div.inner" ).replaceWith( "<h2>New heading</h2>" );
      +    

      This causes all of them to be replaced:

      <div class="container">
         <h2>New heading</h2>
         <h2>New heading</h2>
         <h2>New heading</h2>
      -</div>
      +</div> +

      An element could also be selected as the replacement:

      -
      $('div.third').replaceWith($('.first'));
      +
      
      +$( "div.third" ).replaceWith( $( ".first" ) );
      +    

      This results in the DOM structure:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner second">And</div>
         <div class="inner first">Hello</div>
      -</div>
      +</div> +

      This example demonstrates that the selected element replaces the target by being moved from its old location, not by being cloned.

      The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

      -

      As of jQuery 1.4, .replaceWith() can also work on disconnected DOM nodes. For example, with the following code, .replaceWith() returns a jQuery set containing only a paragraph.:

      -
      $("<div/>").replaceWith("<p></p>");
      -

      The .replaceWith() method can also take a function as its argument:

      -
      $('div.container').replaceWith(function() {
      -  return $(this).contents();
      -});
      -

      This results in <div class="container"> being replaced by its three child <div>s. The return value of the function may be an HTML string, DOM element, or jQuery object.

      + + On click, replace the button with a div containing the same word. + button { + display: block; + margin: 3px; + color: red; + width: 200px; + } + div { + color: red; + border: 2px solid blue; + width: 200px; + margin: 3px; + text-align: center; + } +]]> + div { + border: 2px solid blue; + color: red; + margin: 3px; + } + p { + border: 2px solid red; + color: blue; + margin: 3px; + cursor: pointer; + } +]]> On button click, replace the containing div with its child divs and append the class name of the selected element to the paragraph. + .container { + background-color: #991; + } + .inner { + color: #911; + } +]]> - + textarea { + height: 45px; + } +]]> + - \ No newline at end of file + diff --git a/entries/resize-shorthand.xml b/entries/resize-shorthand.xml new file mode 100644 index 000000000..31f69a5d0 --- /dev/null +++ b/entries/resize-shorthand.xml @@ -0,0 +1,36 @@ + + + .resize() + Bind an event handler to the "resize" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
      +

      This API is deprecated.

      +

      Instead of .resize( handler ) or .resize( eventData, handler ), use .on( "resize", handler ) or .on( "resize", eventData, handler ), respectively.

      +

      Instead of .resize(), use .trigger( "resize" ).

      +
      +
      + + + + +
      diff --git a/entries/resize.xml b/entries/resize.xml index c5d424949..74cc61fe8 100644 --- a/entries/resize.xml +++ b/entries/resize.xml @@ -1,31 +1,32 @@ - - .resize() - Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. + + +Bind an event handler to the "resize" event, or trigger that event on an element. + + resize event + Bind an event handler to the "resize" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "resize". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

      This method is a shortcut for .on('resize', handler) in the first and second variations, and .trigger('resize') in the third.

      +
      +

      This page describes the resize event. For the deprecated .resize() method, see .resize().

      +

      The resize event is sent to the window element when the size of the browser window changes:

      -
      $(window).resize(function() {
      -  $('#log').append('<div>Handler for .resize() called.</div>');
      -});
      +    
      
      +$( window ).on( "resize", function() {
      +  $( "#log" ).append( "<div>Handler for `resize` called.</div>" );
      +} );
           

      Now whenever the browser window's size is changed, the message is appended to <div id="log"> one or more times, depending on the browser.

      Code in a resize handler should never rely on the number of times the handler is called. Depending on implementation, resize events can be sent continuously as the resizing is in progress (the typical behavior in Internet Explorer and WebKit-based browsers such as Safari and Chrome), or only once at the end of the resize operation (the typical behavior in some other browsers such as Opera).

      @@ -33,11 +34,30 @@ To see the window width while (or after) it is resized, try: +$( window ).on( "resize", function() { + $( "body" ).prepend( "
      " + $( window ).width() + "
      " ); +} ); +]]>
      - + + + + + resize event + Trigger the "resize" event on an element. + + 1.0 + + The string "resize". + + + +

      See the description for .on( "resize", ... ).

      +
      + +
      + + diff --git a/entries/root-selector.xml b/entries/root-selector.xml index 76a6acec1..5ed93b2cf 100644 --- a/entries/root-selector.xml +++ b/entries/root-selector.xml @@ -4,9 +4,6 @@ :root 1.9 - - The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-last-child(even), :nth-last-child(4n) ) - Selects the element that is the root of the document. @@ -15,15 +12,19 @@ Display the tag name of the root element. " ).html( $( ":root" )[ 0 ].nodeName ).appendTo( "#log" ); ]]> - + span.fot { + color: red; + font-size: 120%; + font-style: italic; + } +]]> + - - diff --git a/entries/scroll-shorthand.xml b/entries/scroll-shorthand.xml new file mode 100644 index 000000000..67b7997ed --- /dev/null +++ b/entries/scroll-shorthand.xml @@ -0,0 +1,36 @@ + + + .scroll() + Bind an event handler to the "scroll" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
      +

      This API is deprecated.

      +

      Instead of .scroll( handler ) or .scroll( eventData, handler ), use .on( "scroll", handler ) or .on( "scroll", eventData, handler ), respectively.

      +

      Instead of .scroll(), use .trigger( "scroll" ).

      +
      +
      + + + + +
      diff --git a/entries/scroll.xml b/entries/scroll.xml index c70b9545e..5f46ddfe0 100644 --- a/entries/scroll.xml +++ b/entries/scroll.xml @@ -1,30 +1,31 @@ - - .scroll() - Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. + + +Bind an event handler to the "scroll" event, or trigger that event on an element. + + scroll event + Bind an event handler to the "scroll" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "scroll". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

      This method is a shortcut for .on('scroll', handler) in the first and second variations, and .trigger('scroll') in the third.

      +
      +

      This page describes the scroll event. For the deprecated .scroll() method, see .scroll().

      +

      The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element's explicit height or width is less than the height or width of its contents).

      For example, consider the HTML:

      -
      <div id="target" style="overflow: scroll; width: 200px; height: 100px;">
      +    
      
      +<div id="target" style="overflow: scroll; width: 200px; height: 100px;">
         Lorem ipsum dolor sit amet, consectetur adipisicing elit,
         sed do eiusmod tempor incididunt ut labore et dolore magna
         aliqua. Ut enim ad minim veniam, quis nostrud exercitation
      @@ -37,45 +38,78 @@
       <div id="other">
         Trigger the handler
       </div>
      -<div id="log"></div>
      +<div id="log"></div> +

      The style definition is present to make the target element small enough to be scrollable:

      -

      +

      -

      +
      Figure 1 - Illustration of the rendered HTML
      +

      The scroll event handler can be bound to this element:

      -
      $('#target').scroll(function() {
      -  $('#log').append('<div>Handler for .scroll() called.</div>');
      -});
      +
      
      +$( "#target" ).on( "scroll", function() {
      +  $( "#log" ).append( "<div>Handler for `scroll` called.</div>" );
      +} );
      +    

      Now when the user scrolls the text up or down, one or more messages are appended to <div id="log"></div>:

      - Handler for .scroll() called. + Handler for `scroll` called.

      -

      To trigger the event manually, apply .scroll() without an argument:

      -
      $('#other').click(function() {
      -  $('#target').scroll();
      -});
      -

      After this code executes, clicks on Trigger the handler will also append the message.

      +

      To trigger the event manually, use .trigger( "scroll" ):

      +
      
      +$( "#other" ).on( "click", function() {
      +  $( "#target" ).trigger( "scroll" );
      +} );
      +    
      +

      After this code executes, clicks on Trigger the handler will also append the message.

      A scroll event is sent whenever the element's scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse's scroll wheel could cause this event.

      To do something when your page is scrolled: - + div { + color: blue; + } + p { + color: green; + } + span { + color: red; + display: none; + } +]]> + - + +
      + + + scroll event + Trigger the "scroll" event on an element. + + 1.0 + + The string "scroll". + + + +

      See the description for .on( "scroll", ... ).

      +
      + +
      + +
      diff --git a/entries/scrollLeft.xml b/entries/scrollLeft.xml index bd65f6ae7..7fe21491a 100644 --- a/entries/scrollLeft.xml +++ b/entries/scrollLeft.xml @@ -9,19 +9,26 @@ Get the current horizontal position of the scroll bar for the first element in the set of matched elements.

      The horizontal scroll position is the same as the number of pixels that are hidden from view to the left of the scrollable area. If the scroll bar is at the very left, or if the element is not scrollable, this number will be 0.

      -
      +

      Note:.scrollLeft(), when called directly or animated as a property using .animate(), will not work if the element it is being applied to is hidden.

      -
      +
      Get the scrollLeft of a paragraph. - - + @@ -41,22 +48,31 @@ $("p:last").text( "scrollLeft:" + p.scrollLeft() );
      Set the scrollLeft of a div. - - +]]> + diff --git a/entries/scrollTop.xml b/entries/scrollTop.xml index 82bbe43fb..18250efae 100644 --- a/entries/scrollTop.xml +++ b/entries/scrollTop.xml @@ -1,6 +1,6 @@ - + .scrollTop() 1.2.6 @@ -11,13 +11,20 @@ Get the scrollTop of a paragraph. - - + p { + margin: 10px; + padding: 5px; + border: 2px solid #666; + } +]]> + @@ -28,7 +35,7 @@ $("p:last").text( "scrollTop:" + p.scrollTop() ); 1.2.6 - An integer indicating the new position to set the scroll bar to. + A number indicating the new position to set the scroll bar to. Set the current vertical position of the scroll bar for each of the set of matched elements. @@ -37,22 +44,31 @@ $("p:last").text( "scrollTop:" + p.scrollTop() ); Set the scrollTop of a div. - - + div.demo { + background: #ccc none repeat scroll 0 0; + border: 3px solid #666; + margin: 5px; + padding: 5px; + position: relative; + width: 200px; + height: 100px; + overflow: auto; + } + p { + margin: 10px; + padding: 5px; + border: 2px solid #666; + width: 1000px; + height: 1000px; + } +]]> + diff --git a/entries/select-shorthand.xml b/entries/select-shorthand.xml new file mode 100644 index 000000000..e3fb02279 --- /dev/null +++ b/entries/select-shorthand.xml @@ -0,0 +1,36 @@ + + + .select() + Bind an event handler to the "select" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
      +

      This API is deprecated.

      +

      Instead of .select( handler ) or .select( eventData, handler ), use .on( "select", handler ) or .on( "select", eventData, handler ), respectively.

      +

      Instead of .select(), use .trigger( "select" ).

      +
      +
      + + + + +
      diff --git a/entries/select.xml b/entries/select.xml index 01043375c..605738810 100644 --- a/entries/select.xml +++ b/entries/select.xml @@ -1,78 +1,105 @@ - - .select() - Bind an event handler to the "select" JavaScript event, or trigger that event on an element. + +Bind an event handler to the "select" event, or trigger that event on an element. + + + select event + Bind an event handler to the "select" event. - 1.0 - - A function to execute each time the event is triggered. + 1.7 + + The string "select". - - - 1.4.3 - + An object containing data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - - 1.0 - -

      This method is a shortcut for .on('select', handler) in the first two variations, and .trigger('select') in the third.

      +
      +

      This page describes the select event. For the deprecated .select() method, see .select().

      +

      The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.

      For example, consider the HTML:

      -
      <form>
      -  <input id="target" type="text" value="Hello there" />
      +    
      
      +<form>
      +  <input id="target" type="text" value="Hello there">
       </form>
       <div id="other">
         Trigger the handler
       </div>

      The event handler can be bound to the text input:

      -
      $('#target').select(function() {
      -  alert('Handler for .select() called.');
      -});
      -

      Now when any portion of the text is selected, the alert is displayed. Merely setting the location of the insertion point will not trigger the event. To trigger the event manually, apply .select() without an argument:

      -
      $('#other').click(function() {
      -  $('#target').select();
      -});
      +
      
      +$( "#target" ).on( "select", function() {
      +  alert( "Handler for `select` called." );
      +} );
      +    
      +

      Now when any portion of the text is selected, the alert is displayed. Merely setting the location of the insertion point will not trigger the event. To trigger the event manually, use .trigger( "select" ):

      +
      
      +$( "#other").on( "click", function() {
      +  $( "#target" ).trigger( "select" );
      +} );
      +    

      After this code executes, clicks on the Trigger button will also alert the message:

      - Handler for .select() called. + Handler for `select` called.

      In addition, the default select action on the field will be fired, so the entire text field will be selected.

      -
      +

      The method for retrieving the current selected text differs from one browser to another. A number of jQuery plug-ins offer cross-platform solutions.

      -
      + To do something when text in input boxes is selected: + p { + color: blue; + } + div { + color: red; + } +]]> +

      Click and drag the mouse to select text in the inputs.

      + + +
      + ]]>
      To trigger the select event on all input elements, try: - + - + + + + select event + Trigger the "select" event on an element. + + 1.0 + + The string "select". + + + +

      See the description for .on( "select", ... ).

      +
      + + +
      + + diff --git a/entries/selected-selector.xml b/entries/selected-selector.xml index b54a0de44..5eb6cef8d 100644 --- a/entries/selected-selector.xml +++ b/entries/selected-selector.xml @@ -13,31 +13,34 @@ Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw. - + div { + color: red; + } +]]> + - \ No newline at end of file + diff --git a/entries/selector.xml b/entries/selector.xml index 8abe05bf1..229e674b9 100644 --- a/entries/selector.xml +++ b/entries/selector.xml @@ -1,14 +1,18 @@ - + .selector 1.3 - A selector representing selector originally passed to jQuery(). + A selector representing selector passed to jQuery(), if any, when creating the original set. -

      Should be used in conjunction with context to determine the exact query used.

      -

      The .live() method for binding event handlers uses this property to determine how to perform its searches. Plug-ins which perform similar tasks may also find the property useful. This property contains a string representing the matched set of elements, but if DOM traversal methods have been called on the object, the string may not be a valid jQuery selector expression. For this reason, the value of .selector is generally most useful immediately following the original creation of the object. Consequently, the .live() method should only be used in this scenario.

      +
      +

      Note: This API has been removed in jQuery 3.0. The property was never a reliable indicator of the selector that could be used to obtain the set of elements currently contained in the jQuery set where it was a property, since subsequent traversal methods may have changed the set. Plugins that need to use a selector string within their plugin can require it as a parameter of the method. For example, a "foo" plugin could be written as $.fn.foo = function( selector, options ) { /* plugin code goes here */ };, and the person using the plugin would write $( "div.bar" ).foo( "div.bar", {dog: "bark"} ); with the "div.bar" selector repeated as the first argument of .foo().

      +
      - + + + +
      diff --git a/entries/serialize.xml b/entries/serialize.xml index e55b6699c..55dd099ff 100644 --- a/entries/serialize.xml +++ b/entries/serialize.xml @@ -6,88 +6,76 @@ Encode a set of form elements as a string for submission. -

      The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

      -
      <form>
      -  <div><input type="text" name="a" value="1" id="a" /></div>
      -  <div><input type="text" name="b" value="2" id="b" /></div>
      -  <div><input type="hidden" name="c" value="3" id="c" /></div>
      -  <div>
      -    <textarea name="d" rows="8" cols="40">4</textarea>
      -  </div>
      -  <div><select name="e">
      -    <option value="5" selected="selected">5</option>
      -    <option value="6">6</option>
      -    <option value="7">7</option>
      -  </select></div>
      -  <div>
      -    <input type="checkbox" name="f" value="8" id="f" />
      -  </div>
      -  <div>
      -    <input type="submit" name="g" value="Submit" id="g" />
      -  </div>
      -</form>
      -

      The .serialize() method can act on a jQuery object that has selected individual form elements, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> tag itself for serialization:

      -
      $('form').submit(function() {
      -  alert($(this).serialize());
      -  return false;
      -});
      -

      This produces a standard-looking query string:

      -
      a=1&b=2&c=3&d=4&e=5
      -

      Warning: selecting both the form and its children will cause duplicates in the serialized string.

      -

      Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

      +

      The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>: $( "input, textarea, select" ).serialize();

      +

      It is typically easier, however, to select the <form> itself for serialization:

      +
      
      +$( "form" ).on( "submit", function( event ) {
      +  event.preventDefault();
      +  console.log( $( this ).serialize() );
      +});
      +    
      +

      In this case, jQuery serializes the successful controls within the form. Only form elements are examined for inputs they contain, in all other cases the input elements to be serialized should be part of the set passed to the .serialize() method. Selecting both the form and its children in a set will cause duplicates in the serialized string.

      +

      Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

      - Serialize a form to a query string, that could be sent to a server in an Ajax request. + Serialize a form to a query string that could be sent to a server in an Ajax request. + body, select { + font-size: 12px; + } + form { + margin: 5px; + } + p { + color: red; + margin: 5px; + font-size: 14px; + } + b { + color: blue; + } +]]> 200 + +

      +]]>
      -
      \ No newline at end of file + diff --git a/entries/serializeArray.xml b/entries/serializeArray.xml index bd90e0ac5..09125d062 100644 --- a/entries/serializeArray.xml +++ b/entries/serializeArray.xml @@ -6,11 +6,12 @@ Encode a set of form elements as an array of names and values. -

      The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

      -
      <form>
      -  <div><input type="text" name="a" value="1" id="a" /></div>
      -  <div><input type="text" name="b" value="2" id="b" /></div>
      -  <div><input type="hidden" name="c" value="3" id="c" /></div>
      +    

      The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types:

      +
      
      +<form>
      +  <div><input type="text" name="a" value="1" id="a"></div>
      +  <div><input type="text" name="b" value="2" id="b"></div>
      +  <div><input type="hidden" name="c" value="3" id="c"></div>
         <div>
           <textarea name="d" rows="8" cols="40">4</textarea>
         </div>
      @@ -20,20 +21,24 @@
           <option value="7">7</option>
         </select></div>
         <div>
      -    <input type="checkbox" name="f" value="8" id="f" />
      +    <input type="checkbox" name="f" value="8" id="f">
         </div>
         <div>
      -    <input type="submit" name="g" value="Submit" id="g" />
      +    <input type="submit" name="g" value="Submit" id="g">
         </div>
      -</form>
      -

      The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.

      -

      This method can act on a jQuery object that has selected individual form elements, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> tag itself for serialization:

      -
      $('form').submit(function() {
      -  console.log($(this).serializeArray());
      -  return false;
      -});
      +</form> +
      +

      The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized. Elements that do not contain a value attribute are represented with the empty string value.

      +

      This method can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> element itself for serialization:

      +
      
      +$( "form" ).on( "submit", function( event ) {
      +  console.log( $( this ).serializeArray() );
      +  event.preventDefault();
      +} );
      +    

      This produces the following data structure (provided that the browser supports console.log):

      -
      [
      +    
      
      +[
         {
           name: "a",
           value: "1"
      @@ -54,58 +59,64 @@
           name: "e",
           value: "5"
         }
      -]
      +] +
      Get the values from a form, iterate through them, and append them to a results display. - + body, select { + font-size: 14px; + } + form { + margin: 5px; + } + p { + color: red; + margin: 5px; + } + b { + color: blue; + } +]]> + - \ No newline at end of file + diff --git a/entries/show.xml b/entries/show.xml index e94ce3217..2ce1c4a4c 100644 --- a/entries/show.xml +++ b/entries/show.xml @@ -29,105 +29,129 @@

      With no parameters, the .show() method is the simplest way to display an element:

      -
      $('.target').show();
      +    
      
      +$( ".target" ).show();
           
      -

      The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

      -

      Note: If using !important in your styles, such as - display: none !important, - it is necessary to override the style using .css('display', 'block !important') should you wish for .show() to function correctly.

      +

      The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css( "display", "block" ), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

      +

      Note: If using !important in your styles, such as display: none !important, .show() will not override !important. + It is recommended to use different classes with .addClass(), .removeClass() or .toggleClass(). Another approach is using .attr( "style", "display: block !important;" ); be careful, though, as it overwrites the style attribute of the element.

      When a duration, a plain object, or a "complete" function is provided, .show() becomes an animation method. The .show() method animates the width, height, and opacity of the matched elements simultaneously.

      Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

      -

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      +

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

      +
      +

      Note: This method may cause performance issues, especially when used on many elements. If you're encountering such issues, use performance testing tools to determine whether this method is causing them. Moreover, this method can cause problems with responsive layouts if the display value differs at different viewport sizes.

      +

      We can animate any element, such as a simple image:

      -
      <div id="clickme">
      +    
      
      +<div id="clickme">
         Click here
       </div>
      -<img id="book" src="book.png" alt="" width="100" height="123" />
      +<img id="book" src="book.png" alt="" width="100" height="123">
       With the element initially hidden, we can show it slowly:
      -$('#clickme').click(function() {
      -  $('#book').show('slow', function() {
      +$( "#clickme" ).on( "click", function() {
      +  $( "#book" ).show( "slow", function() {
           // Animation complete.
         });
      -});
      -

      - - - - -

      +}); +
      +
      + + + + +
      Figure 1 - Illustration of the show() effect
      +
      Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds. - + Show the first div, followed by each next adjacent sibling div in order, with a 200ms animation. Each animation starts when the previous sibling div's animation ends. + div { + background: #def3ca; + margin: 3px; + width: 80px; + display: none; + float: left; + text-align: center; + } +]]> + + +
      Hello 3,
      +
      how
      +
      are
      +
      you?
      +]]>
      Show all span and input elements with an animation. Change the text once the animation is done. + span { + display: none; + } + div { + display: none; + } + p { + font-weight: bold; + background-color: #fcd; + } +]]>
      - + +

      Unique siblings:

      +]]> Find all siblings with a class "selected" of each div. - - + + - \ No newline at end of file + diff --git a/entries/size.xml b/entries/size.xml index 6e9fd145a..a6e03e46f 100644 --- a/entries/size.xml +++ b/entries/size.xml @@ -1,14 +1,16 @@ - + .size() 1.0 Return the number of elements in the jQuery object. -

      The .size() method is deprecated as of jQuery 1.8. Use the .length property instead.

      +
      +

      Note: This method has been removed in jQuery 3.0. Use the .length property instead.

      +
      -

      The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

      +

      The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

      Given a simple unordered list on the page:

      
       <ul>
      @@ -17,39 +19,34 @@
       </ul>
           

      Both .size() and .length identify the number of items:

      -
      alert( "Size: " + $("li").size() );
      -alert( "Size: " + $("li").length );
      +
      
      +alert( "Size: " + $( "li" ).size() );
      +alert( "Size: " + $( "li" ).length );
      +    

      This results in two alerts:

      - Size: 2 + Size: 2

      - Size: 2 + Size: 2

      - Count the divs. Click to add more. + Count the divs. - - + +
      diff --git a/entries/slice.xml b/entries/slice.xml index 031da20c3..8f94ce16a 100644 --- a/entries/slice.xml +++ b/entries/slice.xml @@ -24,80 +24,106 @@ </ul>

      We can apply this method to the set of list items:

      -
      $('li').slice(2).css('background-color', 'red');
      +
      
      +$( "li" ).slice( 2 ).css( "background-color", "red" );
      +    

      The result of this call is a red background for items 3, 4, and 5. Note that the supplied index is zero-based, and refers to the position of elements within the jQuery object, not within the DOM tree.

      The end parameter allows us to limit the selected range even further. For example:

      -
      $('li').slice(2, 4).css('background-color', 'red');
      +
      
      +$( "li" ).slice( 2, 4 ).css( "background-color", "red" );
      +    

      Now only items 3 and 4 are selected. The index is once again zero-based; the range extends up to but not including the specified index.

      Negative Indices

      The jQuery .slice() method is patterned after the JavaScript .slice() method for arrays. One of the features that it mimics is the ability for negative numbers to be passed as either the start or end parameter. If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning. For example:

      -
      $('li').slice(-2, -1).css('background-color', 'red');
      +
      
      +$( "li" ).slice( -2, -1 ).css( "background-color", "red" );
      +    

      This time only list item 4 is turned red, since it is the only item in the range between two from the end (-2) and one from the end (-1).

      Turns divs yellow based on a random slice. + div { + width: 40px; + height: 40px; + margin: 10px; + float: left; + border: 2px solid blue; + } + span { + color: red; + font-weight: bold; + } + button { + margin: 5px; + } +]]> 240 - +
      + ]]>
      Selects all paragraphs, then slices the selection to include only the first element. - + Selects all paragraphs, then slices the selection to include only the first and second element. - + Selects all paragraphs, then slices the selection to include only the second element. - + Selects all paragraphs, then slices the selection to include only the second and third element. - + Selects all paragraphs, then slices the selection to include only the third element. - + diff --git a/entries/slideDown.xml b/entries/slideDown.xml index 0ffeadf98..e70c81f79 100644 --- a/entries/slideDown.xml +++ b/entries/slideDown.xml @@ -22,78 +22,106 @@

      The .slideDown() method animates the height of the matched elements. This causes lower parts of the page to slide down, making way for the revealed items.

      Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.

      We can animate any element, such as a simple image:

      -
      <div id="clickme">
      +    
      
      +<div id="clickme">
         Click here
       </div>
      -<img id="book" src="book.png" alt="" width="100" height="123" />
      +<img id="book" src="book.png" alt="" width="100" height="123"> +

      With the element initially hidden, we can show it slowly:

      -
      $('#clickme').click(function() {
      -  $('#book').slideDown('slow', function() {
      +    
      
      +$( "#clickme" ).on( "click", function() {
      +  $( "#book" ).slideDown( "slow", function() {
           // Animation complete.
         });
      -});
      -

      - - - - -

      +}); +
      +
      + + + + +
      Figure 1 - Illustration of the slideDown() effect
      +

      Easing

      -

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      +

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      Callback Function

      If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

      -

      As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

      +

      As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

      Animates all divs to slide down and show themselves over 600 milliseconds. - +]]> Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus. - + diff --git a/entries/slideToggle.xml b/entries/slideToggle.xml index 2283c5ead..9a91bed87 100644 --- a/entries/slideToggle.xml +++ b/entries/slideToggle.xml @@ -22,76 +22,99 @@

      The .slideToggle() method animates the height of the matched elements. This causes lower parts of the page to slide up or down, appearing to reveal or conceal the items. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline. When the height reaches 0 after a hiding animation, the display style property is set to none to ensure that the element no longer affects the layout of the page.

      Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

      We can animate any element, such as a simple image:

      -
      <div id="clickme">
      +    
      
      +<div id="clickme">
         Click here
       </div>
      -<img id="book" src="book.png" alt="" width="100" height="123" />
      +<img id="book" src="book.png" alt="" width="100" height="123"> +

      We will cause .slideToggle() to be called when another element is clicked:

      -
      $('#clickme').click(function() {
      -  $('#book').slideToggle('slow', function() {
      +    
      
      +$( "#clickme" ).on( "click", function() {
      +  $( "#book" ).slideToggle( "slow", function() {
           // Animation complete.
         });
      -});
      -
      +}); +

      With the element initially shown, we can hide it slowly with the first click:

      -

      - - - - -

      +
      + + + + +
      Figure 1 - Illustration of the slideToggle() effect when hiding the image
      +

      A second click will show the element once again:

      -

      - - - - -

      +
      + + + + +
      Figure 2 - Illustration of the slideToggle() effect when showing the image
      +

      Easing

      -

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      +

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      Callback Function

      If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

      -

      As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

      +

      As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

      Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds. - + p { + width: 400px; + } +]]> + Animates divs between dividers with a toggle that makes some appear and some disappear. - + +

      There have been 0 toggled divs.

      +]]>
      diff --git a/entries/slideUp.xml b/entries/slideUp.xml index bfc3d62d0..c0d5f8ebf 100644 --- a/entries/slideUp.xml +++ b/entries/slideUp.xml @@ -22,84 +22,96 @@

      The .slideUp() method animates the height of the matched elements. This causes lower parts of the page to slide up, appearing to conceal the items. Once the height reaches 0 (or, if set, to whatever the CSS min-height property is), the display style property is set to none to ensure that the element no longer affects the layout of the page.

      Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.

      We can animate any element, such as a simple image:

      -
      <div id="clickme">
      +    
      
      +<div id="clickme">
         Click here
       </div>
      -<img id="book" src="book.png" alt="" width="100" height="123" />
      +<img id="book" src="book.png" alt="" width="100" height="123"> +

      With the element initially shown, we can hide it slowly:

      -
      $('#clickme').click(function() {
      -  $('#book').slideUp('slow', function() {
      +    
      
      +$( "#clickme" ).on( "click", function() {
      +  $( "#book" ).slideUp( "slow", function() {
           // Animation complete.
         });
       });
      -  
      -

      - - - - -

      +
      +
      + + + + +
      Figure 1 - Illustration of the slideUp() effect
      +

      Easing

      -

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      +

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      Callback Function

      If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

      -

      As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

      +

      As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

      Animates all divs to slide up, completing the animation within 400 milliseconds. +$( document.body ).on( "click", function() { + if ( $( "div" ).first().is( ":hidden" ) ) { + $( "div" ).show( "slow" ); + } else { + $( "div" ).slideUp(); + } +} ); +]]> - + div { + background: #3d9a44; + margin: 3px; + width: 80px; + height: 40px; + float: left; + } +]]> + Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert. - + +
      +]]>
      diff --git a/entries/stop.xml b/entries/stop.xml index 2f0f87218..60062614a 100644 --- a/entries/stop.xml +++ b/entries/stop.xml @@ -4,10 +4,10 @@ Stop the currently-running animation on the matched elements. 1.2 - + A Boolean indicating whether to remove queued animation as well. Defaults to false. - + A Boolean indicating whether to complete the current animation immediately. Defaults to false. @@ -16,10 +16,10 @@ The name of the queue in which to stop animations. - + A Boolean indicating whether to remove queued animation as well. Defaults to false. - + A Boolean indicating whether to complete the current animation immediately. Defaults to false. @@ -29,77 +29,87 @@

      If the jumpToEnd argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above .slideUp() example, the element would be immediately hidden. The callback function is then immediately called, if provided.

      As of jQuery 1.7, if the first argument is provided as a string, only the animations in the queue represented by that string will be stopped.

      The usefulness of the .stop() method is evident when we need to animate an element on mouseenter and mouseleave:

      -
      <div id="hoverme">
      +    
      
      +<div id="hoverme">
         Hover me
      -  <img id="hoverme" src="book.png" alt="" width="100" height="123" />
      -</div>
      + <img id="hoverme" src="book.png" alt="" width="100" height="123"> +</div> +

      We can create a nice fade effect without the common problem of multiple queued animations by adding .stop(true, true) to the chain:

      -
      $('#hoverme-stop-2').hover(function() {
      -  $(this).find('img').stop(true, true).fadeOut();
      +    
      
      +$( "#hoverme-stop-2" ).hover(function() {
      +  $( this ).find( "img" ).stop( true, true ).fadeOut();
       }, function() {
      -  $(this).find('img').stop(true, true).fadeIn();
      -});
      + $( this ).find( "img" ).stop( true, true ).fadeIn(); +}); +

      Toggling Animations

      As of jQuery 1.7, stopping a toggled animation prematurely with .stop() will trigger jQuery's internal effects tracking. In previous versions, calling the .stop() method before a toggled animation was completed would cause the animation to lose track of its state (if jumpToEnd was false). Any subsequent animations would start at a new "half-way" state, sometimes resulting in the element disappearing. To observe the new behavior, see the final example below.

      -
      +

      Animations may be stopped globally by setting the property $.fx.off to true. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

      -
      + Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one. - - + Click the slideToggle button to start the animation, then click again before the animation is completed. The animation will toggle the other direction from the saved starting point. - - + - \ No newline at end of file + diff --git a/entries/submit-selector.xml b/entries/submit-selector.xml index 6b39224f0..f6c48b8ff 100644 --- a/entries/submit-selector.xml +++ b/entries/submit-selector.xml @@ -7,32 +7,39 @@ Selects all elements of type submit. -

      The :submit selector typically applies to button or input elements. Note that some browsers treat <button> element as type="default" implicitly while others (such as Internet Explorer) do not.

      +

      The :submit selector typically applies to button or input elements. Note that some browsers treat <button> element as type="submit" implicitly while others (such as Internet Explorer) do not. To ensure that markup works consistently across all browsers and guarantee that it is possible to consistently select buttons that will submit a form, always specify a type property.

      - + Finds all submit elements that are descendants of a td element. '); -}) +// Extra JS to make the HTML easier to edit (None of this is relevant to the ':submit' selector) +$( "#exampleTable" ).find( "td" ).each(function( i, el ) { + var inputEl = $( el ).children(), + inputType = inputEl.attr( "type" ) ? " type='" + inputEl.attr( "type" ) + "'" : "" ; + $( el ).before( "" + inputEl[ 0 ].nodeName + inputType + "" ); +} ); ]]> + textarea { + height: 45px; + } +]]> - + p { + margin: 0; + color: blue; + } + div,p { + margin-left: 10px; + } + span { + color: red; + } +]]> + If you'd like to prevent forms from being submitted unless a flag variable is set, try: - +} ); +]]> To trigger the submit event on the first form on the page, try: - + - + + + + submit event + Trigger the "submit" event on an element. + + 1.0 + + The string "submit". + + + +

      See the description for .on( "submit", ... ).

      +
      + + +
      + + diff --git a/entries/target-selector.xml b/entries/target-selector.xml index 5d60f3dab..b010a5ced 100644 --- a/entries/target-selector.xml +++ b/entries/target-selector.xml @@ -7,8 +7,8 @@ Selects the target element indicated by the fragment identifier of the document's URI. -

      If the document's URI contains a fragment identifier, or hash, then the :target selector will match the element with an ID that matches the identifier. For example, given a document with a URI of http://example.com/#foo, $( "p:target" ) will select the <p id="foo"> element.

      -

      Further discussion of this usage can be found in the W3C CSS specification.

      +

      If the document's URI contains a fragment identifier, or hash, then the :target selector will match the element with an ID that matches the identifier. For example, given a document with a URI of https://example.com/#foo, $( "p:target" ) will select the <p id="foo"> element.

      +

      Further discussion of this usage can be found in the W3C CSS specification.

      diff --git a/entries/text-selector.xml b/entries/text-selector.xml index 833b0a10d..4886c3a50 100644 --- a/entries/text-selector.xml +++ b/entries/text-selector.xml @@ -5,50 +5,61 @@ 1.0 - Selects all elements of type text. + Selects all input elements of type text. -

      $(':text') allows us to select all <input type="text"> elements. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare $(':text') is equivalent to $('*:text'), so $('input:text') should be used instead.

      +

      $( ":text" ) allows us to select all <input type="text"> elements. As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector ( "*" ) is implied. In other words, the bare $( ":text" ) is equivalent to $( "*:text" ), so $( "input:text" ) should be used instead.

      Note: As of jQuery 1.5.2, :text selects input elements that have no specified type attribute (in which case type="text" is implied).

      -

      This difference in behavior between $(':text') and $('[type=text]'), can be seen below:

      -
      $('<input>').is('[type=text]'); // false
      -$('<input>').is(':text'); // true
      -
      +

      This difference in behavior between $( ":text" ) and $( "[type=text]" ), can be seen below:

      +
      
      +$( "<input>" ).is( "[type=text]" ); // false
      +$( "<input>" ).is( ":text" ); // true
      +    
      Finds all text inputs. - - +// Prevent form submission +$( "form" ).on( "submit", function( event ) { + event.preventDefault(); +} ); +]]> + + - \ No newline at end of file + diff --git a/entries/text.xml b/entries/text.xml index 947cf9a39..616b8a2cf 100644 --- a/entries/text.xml +++ b/entries/text.xml @@ -9,33 +9,41 @@ Get the combined text contents of each element in the set of matched elements, including their descendants.

      Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.) Consider the following HTML:

      -
      <div class="demo-container">
      -      <div class="demo-box">Demonstration Box</div>
      +      
      
      +<div class="demo-container">
      +  <div class="demo-box">Demonstration Box</div>
         <ul>
      -  <li>list item 1</li>
      -  <li>list <strong>item</strong> 2</li>
      +    <li>list item 1</li>
      +    <li>list <strong>item</strong> 2</li>
         </ul>
      -  </div>
      -
      -

      The code $('div.demo-container').text() would produce the following result:

      +</div> +
      +

      The code $( "div.demo-container" ).text() would produce the following result:

      Demonstration Box list item 1 list item 2

      -

      The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

      +

      The .text() method should not be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method.

      As of jQuery 1.4, the .text() method returns the value of text and CDATA nodes as well as element nodes.

      Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone). - + p { + color: blue; + margin: 8px; + } + b { + color: red; + } +]]> + @@ -44,55 +52,75 @@ $("p:last").html(str); 1.0 - - A string of text to set as the content of each matched element. + + + + + The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. 1.4 - + + + + A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. Set the content of each element in the set of matched elements to the specified text.

      Unlike the .html() method, .text() can be used in both XML and HTML documents.

      -

      We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <). Consider the following HTML:

      -
      <div class="demo-container">
      +      

      We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML. Consider the following HTML:

      +
      
      +<div class="demo-container">
         <div class="demo-box">Demonstration Box</div>
         <ul>
           <li>list item 1</li>
           <li>list <strong>item</strong> 2</li>
         </ul>
       </div>
      -
      -

      The code $('div.demo-container').text('<p>This is a test.</p>'); will produce the following DOM output:

      -
      <div class="demo-container">
      -&lt;p&gt;This is a test.&lt;/p&gt;
      -</div>
      +
      +

      The code $( "div.demo-container" ).text( "<p>This is a test.</p>" ); will produce the following DOM output:

      +
      
      +<div class="demo-container">
      +  &lt;p&gt;This is a test.&lt;/p&gt;
      +</div>
      +      

      It will appear on a rendered page as though the tags were exposed, like this:

      -
      <p>This is a test</p>
      -

      The .text() method cannot be used on input elements. For input field text, use the .val() method.

      +
      
      +<p>This is a test</p>
      +      
      +

      The .text() method should not be used on input elements. For input field text, use the .val() method.

      As of jQuery 1.4, the .text() method allows us to set the text content by passing in a function.

      -
      $('ul li').text(function(index) {
      -  return 'item number ' + (index + 1);
      -});
      +
      
      +$( "ul li" ).text(function( index ) {
      +  return "item number " + ( index + 1 );
      +});
      +      

      Given an unordered list with three <li> elements, this example will produce the following DOM output:

      -
      <ul>
      +      
      
      +<ul>
         <li>item number 1</li>
         <li>item number 2</li>
         <li>item number 3</li>
       </ul>
      -
      +
      Add text to the paragraph (notice the bold tag is escaped). - + - + p { + color: blue; + margin: 8px; + } +]]> + diff --git a/entries/toArray.xml b/entries/toArray.xml index 9c98f424d..dc57da06c 100644 --- a/entries/toArray.xml +++ b/entries/toArray.xml @@ -4,37 +4,43 @@ 1.4 - Retrieve all the DOM elements contained in the jQuery set, as an array. + Retrieve all the elements contained in the jQuery set, as an array.

      .toArray() returns all of the elements in the jQuery set:

      -
      alert($('li').toArray());
      +
      
      +alert( $( "li" ).toArray() );
      +    

      All of the matched DOM nodes are returned by this call, contained in a standard array:

      [<li id="foo">, <li id="bar">]

      - Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array. + Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. - + +
      One
      +
      Two
      +
      Three
      ]]> +
      -
      \ No newline at end of file + diff --git a/entries/toggle-event.xml b/entries/toggle-event.xml index 55f001923..a095eace7 100644 --- a/entries/toggle-event.xml +++ b/entries/toggle-event.xml @@ -4,58 +4,67 @@ Bind two or more handlers to the matched elements, to be executed on alternate clicks. 1.0 - + A function to execute every even time the element is clicked. + - + A function to execute every odd time the element is clicked. + - + Additional handlers to cycle through after clicks. + -
      -

      Note: jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

      -
      +
      +

      Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

      +

      The .toggle() method binds a handler for the click event, so the rules outlined for the triggering of click apply here as well.

      -
      For example, consider the HTML:
      +    

      For example, consider the HTML:

      +
      
       <div id="target">
         Click here
      -</div>
      +</div> +

      Event handlers can then be bound to the <div>:

      -
      $('#target').toggle(function() {
      -  alert('First handler for .toggle() called.');
      +    
      
      +$( "#target" ).toggle(function() {
      +  alert( "First handler for .toggle() called." );
       }, function() {
      -  alert('Second handler for .toggle() called.');
      -});
      + alert( "Second handler for .toggle() called." ); +}); +

      As the element is clicked repeatedly, the messages alternate:

      - First handler for .toggle() called. + First handler for .toggle() called.
      - Second handler for .toggle() called. + Second handler for .toggle() called.
      - First handler for .toggle() called. + First handler for .toggle() called.
      - Second handler for .toggle() called. + Second handler for .toggle() called.
      - First handler for .toggle() called. + First handler for .toggle() called.

      If more than two handlers are provided, .toggle() will cycle among all of them. For example, if there are three handlers, then the first handler will be called on the first click, the fourth click, the seventh click, and so on.

      The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

      Toggle a style on table cells. (Not recommended. Use .toggleClass() instead.): - +); +]]> + diff --git a/entries/toggle.xml b/entries/toggle.xml index 8127ff367..7d74577fe 100644 --- a/entries/toggle.xml +++ b/entries/toggle.xml @@ -24,102 +24,117 @@ 1.3 - - A Boolean indicating whether to show or hide the elements. + + Use true to show the element or false to hide it. -
      -

      Note: The event handling suite also has a method named .toggle(). Which one is fired depends on the set of arguments passed.

      -
      +
      +

      Note: The event handling suite also has a method named .toggle(). Which one is fired depends on the set of arguments passed.

      +

      With no parameters, the .toggle() method simply toggles the visibility of elements:

      -
      $('.target').toggle();
      +
      
      +$( ".target" ).toggle();
      +    

      The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

      When a duration, a plain object, or a single "complete" function is provided, .toggle() becomes an animation method. The .toggle() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0 after a hiding animation, the display style property is set to none to ensure that the element no longer affects the layout of the page.

      Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

      -

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      +

      As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

      If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

      We can animate any element, such as a simple image:

      -
      <div id="clickme">
      +    
      
      +<div id="clickme">
         Click here
       </div>
      -<img id="book" src="book.png" alt="" width="100" height="123" />
      -
      +<img id="book" src="book.png" alt="" width="100" height="123"> +

      We will cause .toggle() to be called when another element is clicked:

      -
      $('#clickme').click(function() {
      -  $('#book').toggle('slow', function() {
      +    
      
      +$( "#clickme" ).on( "click", function() {
      +  $( "#book" ).toggle( "slow", function() {
           // Animation complete.
         });
       });
      -
      +

      With the element initially shown, we can hide it slowly with the first click:

      -

      - - - - -

      +
      + + + + +
      Figure 1 - Illustration of the toggle() effect when hiding the image
      +

      A second click will show the element once again:

      -

      - - - - -

      +
      + + + + +
      Figure 2 - Illustration of the toggle() effect when showing the image
      +

      The second version of the method accepts a Boolean parameter. If this parameter is true, then the matched elements are shown; if false, the elements are hidden. In essence, the statement:

      -
      $('#foo').toggle(showOrHide);
      +
      
      +$( "#foo" ).toggle( display );
      +    

      is equivalent to:

      -
      if ( showOrHide == true ) {
      -  $('#foo').show();
      -} else if ( showOrHide == false ) {
      -  $('#foo').hide();
      +    
      
      +if ( display === true ) {
      +  $( "#foo" ).show();
      +} else if ( display === false ) {
      +  $( "#foo" ).hide();
       }
      -
      +
      Toggles all paragraphs. - +

      Good Bye

      +]]>
      Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds. - +

      Such interesting text, eh?

      +]]>
      Shows all paragraphs, then hides them all, back and forth. - +

      Good Bye

      +]]>
      diff --git a/entries/toggleClass.xml b/entries/toggleClass.xml index ee20f07dd..b42f23290 100644 --- a/entries/toggleClass.xml +++ b/entries/toggleClass.xml @@ -1,124 +1,185 @@ - - .toggleClass() - - 1.0 - - One or more class names (separated by spaces) to be toggled for each element in the matched set. - - - - 1.3 - - One or more class names (separated by spaces) to be toggled for each element in the matched set. - - - A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - - - - 1.4 - - A boolean value to determine whether the class should be added or removed. - - - - 1.4 - - A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. - - - A boolean value to determine whether the class should be added or removed. - - - Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - -

      This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to a simple <div>:

      -
      <div class="tumble">Some text.</div>
      -    
      -

      The first time we apply $('div.tumble').toggleClass('bounce'), we get the following:

      -
      <div class="tumble bounce">Some text.</div>
      -    
      -

      The second time we apply $('div.tumble').toggleClass('bounce'), the <div> class is returned to the single tumble value:

      -
      <div class="tumble">Some text.</div>
      -

      Applying .toggleClass('bounce spin') to the same <div> alternates between <div class="tumble bounce spin"> and <div class="tumble">.

      -

      The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:

      -
      $('#foo').toggleClass(className, addOrRemove);
      -

      is equivalent to:

      -
      if (addOrRemove) {
      -    $('#foo').addClass(className);
      -  }
      -  else {
      -    $('#foo').removeClass(className);
      -  }
      -  
      -

      As of jQuery 1.4, if no arguments are passed to .toggleClass(), all class names on the element the first time .toggleClass() is called will be toggled. Also as of jQuery 1.4, the class name to be toggled can be determined by passing in a function.

      -
      $('div.foo').toggleClass(function() {
      -  if ($(this).parent().is('.bar')) {
      -    return 'happy';
      +
      +  
      +    .toggleClass()
      +    
      +      1.0
      +      
      +        One or more classes (separated by spaces) to be toggled for each element in the matched set.
      +      
      +    
      +    
      +      1.3
      +      
      +        One or more classes (separated by spaces) to be toggled for each element in the matched set.
      +      
      +      
      +        A boolean (not just truthy/falsy) value to determine whether the class should be added or removed.
      +      
      +    
      +    
      +      3.3
      +      
      +        An array of classes to be toggled for each element in the matched set.
      +      
      +    
      +    
      +      3.3
      +      
      +        An array of classes to be toggled for each element in the matched set.
      +      
      +      
      +        A boolean (not just truthy/falsy) value to determine whether the class should be added or removed.
      +      
      +    
      +    
      +      1.4
      +      
      +        
      +        
      +        
      +        
      +        A function returning one or more space-separated class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the state as arguments.
      +      
      +      
      +        A boolean value to determine whether the class should be added or removed.
      +      
      +    
      +    
      +      3.3
      +      
      +        
      +        
      +        
      +        
      +        
      +        A function returning one or more space-separated class names or an array of class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the state as arguments.
      +      
      +      
      +        A boolean value to determine whether the class should be added or removed.
      +      
      +    
      +    Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.
      +    
      +      

      This method takes one or more classes as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to a simple <div>:

      +
      
      +<div class="tumble">Some text.</div>
      +      
      +

      The first time we apply $( "div.tumble" ).toggleClass( "bounce" ), we get the following:

      +
      
      +<div class="tumble bounce">Some text.</div>
      +      
      +

      The second time we apply $( "div.tumble" ).toggleClass( "bounce" ), the <div> class is returned to the single tumble value:

      +
      <div class="tumble">Some text.</div>
      +

      Applying .toggleClass( "bounce spin" ) to the same <div> alternates between <div class="tumble bounce spin"> and <div class="tumble">.

      +

      The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:

      +
      
      +$( "#foo" ).toggleClass( className, addOrRemove );
      +      
      +

      is equivalent to:

      +
      
      +if ( addOrRemove ) {
      +  $( "#foo" ).addClass( className );
      +} else {
      +  $( "#foo" ).removeClass( className );
      +}
      +      
      +

      As of jQuery 1.4, if no arguments are passed to .toggleClass(), all classes on the element the first time .toggleClass() is called will be toggled. Also as of jQuery 1.4, the class name to be toggled can be determined by passing in a function.

      +
      
      +$( "div.foo" ).toggleClass(function() {
      +  if ( $( this ).parent().is( ".bar" ) ) {
      +    return "happy";
         } else {
      -    return 'sad';
      +    return "sad";
         }
      -});
      -

      This example will toggle the happy class for <div class="foo"> elements if their parent element has a class of bar; otherwise, it will toggle the sad class.

      -
      - - Toggle the class 'highlight' when a paragraph is clicked. - - - - - - Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click. - + + + + Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click. + - - - - - Toggle the class name(s) indicated on the buttons for each div. - - + + + + Toggle the class name(s) indicated on the buttons for each div. + - - ' + (this.className || 'none') + ''; + return "
      " + ( this.className || "none" ) + "
      "; }); }; appendClass(); -$('button').on('click', function() { +$( "button" ).on( "click", function() { var tc = this.className || undefined; - divs.toggleClass(tc); + divs.toggleClass( tc ); appendClass(); }); -$('a').on('click', function(event) { +$( "a" ).on( "click", function( event ) { event.preventDefault(); - divs.empty().each(function(i) { - this.className = cls[i]; + divs.empty().each(function( i ) { + this.className = cls[ i ]; }); appendClass(); }); ]]>
      -
      - - - - - - -
      \ No newline at end of file + + + + + + + + + + + + + 1.4 + + A boolean value to determine whether the class should be added or removed. + + + +
      This signature (only!) is deprecated as of jQuery 3.0.
      +
      + +
      +
      diff --git a/entries/trigger.xml b/entries/trigger.xml index 32c304f1a..caff8cb8f 100644 --- a/entries/trigger.xml +++ b/entries/trigger.xml @@ -16,7 +16,7 @@ 1.3 - A jQuery.Event object. + A jQuery.Event object. @@ -26,87 +26,109 @@

      Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:

      -
      $('#foo').on('click', function() {
      -      alert($(this).text());
      -    });
      -    $('#foo').trigger('click');
      -

      As of jQuery 1.3, .trigger()ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the .stopPropagation() method on the event object passed into the event. Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

      -

      To trigger handlers bound via jQuery without also triggering the native event, use .triggerHandler() instead.

      +
      
      +$( "#foo" ).on( "click", function() {
      +  alert( $( this ).text() );
      +});
      +$( "#foo" ).trigger( "click" );
      +   
      +

      As of jQuery 1.3, .trigger()ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the .stopPropagation() method on the event object passed into the event. Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

      +

      To trigger handlers bound via jQuery without also triggering the native event, use .triggerHandler() instead.

      When we define a custom event type using the .on() method, the second argument to .trigger() can become useful. For example, suppose we have bound a handler for the custom event to our element instead of the built-in click event as we did above:

      -
      $('#foo').on('custom', function(event, param1, param2) {
      -  alert(param1 + "\n" + param2);
      +    
      
      +$( "#foo" ).on( "custom", function( event, param1, param2 ) {
      +  alert( param1 + "\n" + param2 );
       });
      -$('#foo').trigger('custom', ['Custom', 'Event']);
      -
      -

      The event object is always passed as the first parameter to an event handler, but if additional parameters are specified during a .trigger() call, these parameters will be passed along to the handler as well. To pass more than one parameter, use an array as shown here. As of jQuery 1.6.2, a single parameter can be passed without using an array.

      -

      Note the difference between the extra parameters we're passing here and the eventData parameter to the .on() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .on() requires the information to be already computed at the time the handler is bound.

      +$( "#foo").trigger( "custom", [ "Custom", "Event" ] ); +
      +

      The event object is always passed as the first parameter to an event handler. An array of arguments can also be passed to the .trigger() call, and these parameters will be passed along to the handler as well following the event object. As of jQuery 1.6.2, single string or numeric argument can be passed without being wrapped in an array.

      +

      Note the difference between the extra parameters passed here and the eventData parameter to the .on() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .on() requires the information to be already computed at the time the handler is bound.

      The .trigger() method can be used on jQuery collections that wrap plain JavaScript objects similar to a pub/sub mechanism; any event handlers bound to the object will be called when the event is triggered.

      -
      Note: For both plain objects and DOM objects, if a triggered event name matches the name of a property on the object, jQuery will attempt to invoke the property as a method if no event handler calls event.preventDefault(). If this behavior is not desired, use .triggerHandler() instead.
      +
      Note: For both plain objects and DOM objects other than window, if a triggered event name matches the name of a property on the object, jQuery will attempt to invoke the property as a method if no event handler calls event.preventDefault(). If this behavior is not desired, use .triggerHandler() instead.
      +
      Note: As with .triggerHandler(), when calling .trigger() with an event name matches the name of a property on the object, prefixed by on (e.g. triggering click on window that has a non null onclick method), jQuery will attempt to invoke that property as a method.
      +
      Note: When triggering with a plain object that is not array-like but still contains a length property, you should pass the object in an array (e.g. [ { length: 1 } ]).
      Clicks to button #2 also trigger a click for button #1. - +
      0 button #2 clicks.
      +]]>
      To submit the first form without using the submit() function, try: - + To submit the first form without using the submit() function, try: - + // Perform an action... +} +]]>
      To pass arbitrary data to an event: - + To pass arbitrary data through an event object: - +$( "body" ).trigger( event ); +]]> Alternative way to pass data through an event object: - + diff --git a/entries/triggerHandler.xml b/entries/triggerHandler.xml index b3d462e5d..83b2a576f 100644 --- a/entries/triggerHandler.xml +++ b/entries/triggerHandler.xml @@ -7,40 +7,53 @@ A string containing a JavaScript event type, such as click or submit. - - An array of additional parameters to pass along to the event handler. + + + + Additional parameters to pass along to the event handler. + + + + 1.3 + + A jQuery.Event object. + + + + + Additional parameters to pass along to the event handler. -

      The .triggerHandler() method behaves similarly to .trigger(), with the following exceptions:

      +

      .triggerHandler( eventType ) executes all handlers bound with jQuery for the event type. It will also execute any method called on{eventType}() found on the element. The behavior of this method is similar to .trigger(), with the following exceptions:

        -
      • The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).
      • +
      • The .triggerHandler( "event" ) method will not call .event() on the element it is triggered on. This means .triggerHandler( "submit" ) on a form will not call .submit() on the form.
      • While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.
      • -
      • Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
      • +
      • Events triggered with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
      • Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined
      -

      For more information on this method, see the discussion for .trigger().

      +

      For more information on this method, see the discussion for .trigger().

      If you called .triggerHandler() on a focus event - the browser's default focus action would not be triggered, only the event handlers bound to the focus event. - + +]]> - \ No newline at end of file + diff --git a/entries/unbind.xml b/entries/unbind.xml index 59aec250e..6a85004ec 100644 --- a/entries/unbind.xml +++ b/entries/unbind.xml @@ -1,20 +1,21 @@ - + .unbind() Remove a previously-attached event handler from the elements. 1.0 - - A string containing a JavaScript event type, such as click or submit. + + A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - + The function that is to be no longer executed. + 1.4.3 - A string containing a JavaScript event type, such as click or submit. + A string containing one or more DOM event types, such as "click" or "submit," or custom event names. Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). @@ -22,56 +23,76 @@ 1.0 - - A JavaScript event object as passed to an event handler. + + A jQuery.Event object. + + 1.0 + -

      Event handlers attached with .bind() can be removed with .unbind(). (As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.) In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements:

      -
      $('#foo').unbind();
      +

      As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.

      +

      Event handlers attached with .bind() can be removed with .unbind(). In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements:

      +
      
      +$( "#foo" ).unbind();
      +    

      This version removes the handlers regardless of type. To be more precise, we can pass an event type:

      -
      $('#foo').unbind('click');
      +
      
      +$( "#foo").unbind( "click" );
      +    

      By specifying the click event type, only handlers for that event type will be unbound. This approach can still have negative ramifications if other scripts might be attaching behaviors to the same element, however. Robust and extensible applications typically demand the two-argument version for this reason:

      -
      var handler = function() {
      -  alert('The quick brown fox jumps over the lazy dog.');
      +    
      
      +var handler = function() {
      +  alert( "The quick brown fox jumps over the lazy dog." );
       };
      -$('#foo').bind('click', handler);
      -$('#foo').unbind('click', handler);
      -
      +$( "#foo" ).bind( "click", handler ); +$( "#foo" ).unbind( "click", handler ); +

      By naming the handler, we can be assured that no other functions are accidentally removed. Note that the following will not work:

      -
      $('#foo').bind('click', function() {
      -  alert('The quick brown fox jumps over the lazy dog.');
      +    
      
      +$( "#foo" ).bind( "click", function() {
      +  alert( "The quick brown fox jumps over the lazy dog." );
       });
       
      -// will NOT work
      -$('#foo').unbind('click', function() {
      -  alert('The quick brown fox jumps over the lazy dog.');
      -});
      +// Will NOT work +$( "#foo" ).unbind( "click", function() { + alert( "The quick brown fox jumps over the lazy dog." ); +}); +

      Even though the two functions are identical in content, they are created separately and so JavaScript is free to keep them as distinct function objects. To unbind a particular handler, we need a reference to that function and not a different one that happens to do the same thing.

      -
      +

      Note: Using a proxied function to unbind an event on an element will unbind all proxied functions on that element, as the same proxy function is used for all proxied events. To allow unbinding a specific event, use unique class names on the event (e.g. click.proxy1, click.proxy2) when attaching them.

      -
      +

      Using Namespaces

      Instead of maintaining references to handlers in order to unbind them, we can namespace the events and use this capability to narrow the scope of our unbinding actions. As shown in the discussion for the .bind() method, namespaces are defined by using a period (.) character when binding a handler:

      -
      $('#foo').bind('click.myEvents', handler);
      +
      
      +$( "#foo" ).bind( "click.myEvents", handler );
      +    

      When a handler is bound in this fashion, we can still unbind it the normal way:

      -
      $('#foo').unbind('click');
      +
      
      +$( "#foo" ).unbind( "click" );
      +    

      However, if we want to avoid affecting other handlers, we can be more specific:

      -
      $('#foo').unbind('click.myEvents');
      +
      
      +$( "#foo" ).unbind( "click.myEvents" );
      +    

      We can also unbind all of the handlers in a namespace, regardless of event type:

      -
      $('#foo').unbind('.myEvents');
      +
      
      +$( "#foo" ).unbind( ".myEvents" );
      +    

      It is particularly useful to attach namespaces to event bindings when we are developing plug-ins or otherwise writing code that may interact with other event-handling code in the future.

      Using the Event Object

      The third form of the .unbind() method is used when we wish to unbind a handler from within itself. For example, suppose we wish to trigger an event handler only three times:

      -
      var timesClicked = 0;
      -$('#foo').bind('click', function(event) {
      -  alert('The quick brown fox jumps over the lazy dog.');
      +    
      
      +var timesClicked = 0;
      +$( "#foo" ).bind( "click", function( event ) {
      +  alert( "The quick brown fox jumps over the lazy dog." );
         timesClicked++;
      -  if (timesClicked >= 3) {
      -    $(this).unbind(event);
      +  if ( timesClicked >= 3 ) {
      +    $( this ).unbind( event );
         }
       });
      -
      +

      The handler in this case must take a parameter, so that we can capture the event object and use it to unbind the handler after the third click. The event object contains the context necessary for .unbind() to know which handler to remove. This example is also an illustration of a closure. Since the handler refers to the timesClicked variable, which is defined outside the function, incrementing the variable has an effect even between invocations of the handler.

      @@ -79,48 +100,61 @@ This example is also an illustration of a closure. Since the handler refers to t Can bind and unbind events to the colored button. - +
      Click!
      +]]> To unbind all events from all paragraphs, write: - + To unbind all click events from all paragraphs, write: - + To unbind just one previously bound handler, pass the function in as the second argument: - +$( "p" ).unbind( "click", foo ); // ... foo will no longer be called. +]]> -
      \ No newline at end of file + +
      diff --git a/entries/undelegate.xml b/entries/undelegate.xml index b853b570f..f3a985963 100644 --- a/entries/undelegate.xml +++ b/entries/undelegate.xml @@ -1,5 +1,5 @@ - + .undelegate() Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. @@ -22,8 +22,9 @@ A string containing a JavaScript event type, such as "click" or "keydown" - + A function to execute at the time the event is triggered. + @@ -42,70 +43,87 @@
      -

      The .undelegate() method is a way of removing event handlers that have been bound using .delegate(). As of jQuery 1.7, the .on() and .off() methods are preferred for attaching and removing event handlers.

      +

      As of jQuery 3.0, .undelegate() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.

      +

      The .undelegate() method is a way of removing event handlers that have been bound using .delegate().

      Can bind and unbind events to the colored button. - +
      Click!
      +]]>
      To unbind all delegated events from all paragraphs, write: - + To unbind all delegated click events from all paragraphs, write: - + To undelegate just one previously bound handler, pass the function in as the third argument: - +$( "body" ).undelegate( "p", "click", foo ); +]]> To unbind all delegated events by their namespace: - +// Unbind all events delegated under the ".whatever" namespace +$( "form" ).undelegate( ".whatever" ); +]]> + diff --git a/entries/uniqueSort.xml b/entries/uniqueSort.xml new file mode 100644 index 000000000..999f15b0f --- /dev/null +++ b/entries/uniqueSort.xml @@ -0,0 +1,112 @@ + + + .uniqueSort() + + 3.7 + + Sorts a jQuery object of DOM elements, in place, with the duplicates removed. Note that this only works on jQuery objects consisting of DOM elements, not strings or numbers. + +

      The .uniqueSort() function searches through a jQuery object, sorting it in document order, and removing any duplicate nodes. A node is considered a duplicate if it is the exact same node as one already in the jQuery object; two different nodes with identical attributes are not considered to be duplicates. This function only works on jQuery objects consisting of DOM elements.

      +
      + + Removes any duplicate elements from the jQuery object of divs. + + + + + + Locate all the divs preceding the last item and wrap them with a div with class wrapper - with or without .uniqueSort(). + + + + + + +
      diff --git a/entries/unload-shorthand.xml b/entries/unload-shorthand.xml new file mode 100644 index 000000000..693768ecd --- /dev/null +++ b/entries/unload-shorthand.xml @@ -0,0 +1,37 @@ + + + .unload() + Bind an event handler to the "unload" event, or trigger that event on an element. + + 1.0 + + A function to execute each time the event is triggered. + + + + + 1.4.3 + + An object containing data that will be passed to the event handler. + + + A function to execute each time the event is triggered. + + + + + 1.0 + + +
      +

      This API has been removed in jQuery 3.0.

      +

      Instead of .unload( handler ) or .unload( eventData, handler ), use .on( "unload", handler ) or .on( "unload", eventData, handler ), respectively.

      +

      Instead of .unload(), use .trigger( "unload" ).

      +
      +
      + + + + + +
      diff --git a/entries/unload.xml b/entries/unload.xml index dd7389e0b..05d1c27a4 100644 --- a/entries/unload.xml +++ b/entries/unload.xml @@ -1,42 +1,66 @@ - - .unload() + +Bind an event handler to the "unload" event, or trigger that event on an element. + + + unload event + Bind an event handler to the "unload" event. - 1.0 - - A function to execute when the event is triggered. + 1.7 + + The string "unload". - - - 1.4.3 - + A plain object of data that will be passed to the event handler. - + A function to execute each time the event is triggered. + - Bind an event handler to the "unload" JavaScript event. -

      This method is a shortcut for .on('unload', handler).

      +
      +

      This page describes the unload event. For the .unload() method removed in jQuery 3.0, see .unload().

      +

      The unload event is sent to the window element when the user navigates away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

      -
      -

      The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

      -
      +
      +

      The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers and contrasted with the similar beforeunload event.

      +

      Any unload event handler should be bound to the window object:

      -
      $(window).unload(function() {
      -  alert('Handler for .unload() called.');
      -});
      -
      -

      After this code executes, the alert will be displayed whenever the browser leaves the current page. -It is not possible to cancel the unload event with .preventDefault(). This event is available so that scripts can perform cleanup when the user leaves the page. -

      +
      
      +$( window ).on( "unload", function() {
      +  return "Handler for `unload` called.";
      +} );
      +    
      +

      This event is available so that scripts can perform cleanup when the user leaves the page. Most browsers will ignore calls to alert(), confirm() and prompt() inside the event handler. The string you return may be used in a confirmation dialog, but not all browsers support this. It is not possible to cancel the unload event with .preventDefault().

      To display an alert when a page is unloaded: - + - + +
      + + + unload event + Trigger the "unload" event on an element. + + 1.0 + + The string "unload". + + + +

      See the description for .on( "unload", ... ).

      +
      + +
      + +
      diff --git a/entries/unwrap.xml b/entries/unwrap.xml index 28e2ae94a..b2dde6046 100644 --- a/entries/unwrap.xml +++ b/entries/unwrap.xml @@ -4,25 +4,37 @@ 1.4 + + 3.0 + + A selector to check the parent element against. If an element's parent does not match the selector, the element won't be unwrapped. + + Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. -

      The .unwrap() method removes the element's parent. This is effectively the inverse of the .wrap() method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.

      +

      The .unwrap() method removes the element's parent and returns the unwrapped content. This is effectively the inverse of the .wrap() method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.

      Wrap/unwrap a div around each of the paragraphs. +}); +]]> + div { + border: 2px solid blue; + } + p { + background: yellow; + margin: 4px; + } +]]>
      -
      -

      Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:

      -
      +

      The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

      +

      When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .val() returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null.

      +

      For selects, checkboxes and radio buttons, you can use :checked to select the right elements. For example:

      +
      
      +// Get the value from the selected option in a dropdown
      +$( "select#foo option:checked" ).val();
      +
      +// Get the value from a dropdown select directly
      +$( "select#foo" ).val();
      +
      +// Get the value from a checked checkbox
      +$( "input[type=checkbox][name=bar]:checked" ).val();
      +
      +// Get the value from a set of radio buttons
      +$( "input[type=radio][name=baz]:checked" ).val();
      +      
      +
      +

      Note: At present, using .val() on <textarea> elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR, however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:

      +
      
       $.valHooks.textarea = {
         get: function( elem ) {
           return elem.value.replace( /\r?\n/g, "\r\n" );
         }
       };
      -
      +
      Get the single value from a single select and an array of values from a multiple select and display their values. Single: " + - singleValues + - " Multiple: " + - multipleValues.join(", ")); - } - - $("select").change(displayVals); - displayVals(); +function displayVals() { + var singleValues = $( "#single" ).val(); + var multipleValues = $( "#multiple" ).val() || []; + // When using jQuery 3: + // var multipleValues = $( "#multiple" ).val(); + $( "p" ).html( "Single: " + singleValues + + " Multiple: " + multipleValues.join( ", " ) ); +} +$( "select" ).on( "change", displayVals ); +displayVals(); ]]> - + Find the value of an input box. - + p { + color: blue; + margin: 8px; + } +]]> + @@ -85,86 +109,104 @@ $.valHooks.textarea = { 1.0 + - A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.
      1.4 - + + + + A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. Set the value of each element in the set of matched elements.

      This method is typically used to set the values of form fields.

      -

      Passing an array of element values allows matching <input type="checkbox">, <input type="radio"> and <option>s inside of n <select multiple="multiple"> to be selected. In the case of <input type="radio">s that are part of a radio group and <select multiple="multiple"> the other elements will be deselected.

      -

      The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:

      -
      $('input:text.items').val(function( index, value ) {
      -  return value + ' ' + this.className;
      +      

      val() allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>. In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type. In the case of <input type="radio">s that are part of a radio group and <select>s, any previously selected element will be deselected.

      +

      Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

      +

      The .val() method allows setting the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:

      +
      
      +$( "input[type=text].tags" ).val(function( index, value ) {
      +  return value.trim();
       });
      -
      -

      This example appends the string " items" to the text inputs' values.

      +
      +

      This example removes leading and trailing whitespace from the values of text inputs with a "tags" class.

      Set the value of an input box. - + button { + margin: 4px; + cursor: pointer; + } + input { + margin: 4px; + color: blue; + } +]]> + Use the function argument to modify the value of an input box. +}); +]]> Set a single select, a multiple select, checkboxes and a radio button . - + +
      + check1 + check2 + radio1 + radio2 +]]>
      diff --git a/entries/visible-selector.xml b/entries/visible-selector.xml index 6d205f864..b315cc15e 100644 --- a/entries/visible-selector.xml +++ b/entries/visible-selector.xml @@ -8,34 +8,48 @@ Selects all elements that are visible.

      Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

      -

      Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation.

      -

      How :visible is calculated was changed in jQuery 1.3.2. The release notes outline the changes in more detail.

      +

      Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

      +

      Elements that are not in a document are considered hidden; jQuery does not have a way to know if they will be visible when appended to a document since it depends on the applicable styles.

      +

      This selector is the opposite of the :hidden selector. So, every element selected by :visible isn't selected by :hidden and vice versa.

      +

      All option elements are considered hidden, regardless of their selected state.

      +

      During animations that hide an element, the element is considered visible until the end of the animation. During animations to show an element, the element is considered visible at the start at the animation.

      +

      How :visible is calculated was changed in jQuery 1.3.2. The release notes outline the changes in more detail.

      +

      jQuery 3 slightly modifies the meaning of :visible (and therefore of :hidden). Starting with this version, elements will be considered :visible if they have any layout boxes, including those of zero width and/or height. For example, br elements and inline elements with no content will be selected by the :visible selector.

      + Make all visible divs turn yellow on click. - + div { + width: 50px; + height: 40px; + margin: 5px; + border: 3px outset green; + float: left; + } + .starthidden { + display: none; + } +]]> + -
      \ No newline at end of file +
      diff --git a/entries/width.xml b/entries/width.xml index 648bee5bd..c8afa4224 100644 --- a/entries/width.xml +++ b/entries/width.xml @@ -1,54 +1,75 @@ Get the current computed width for the first element in the set of matched elements or set the width of every matched element. - + .width() 1.0 Get the current computed width for the first element in the set of matched elements. -

      The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

      -

      +

      The difference between .css( "width" ) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

      +
      -

      +
      Figure 1 - Illustration of the measured width
      +

      This method is also able to find the width of the window and document.

      -
      $(window).width();   // returns width of browser viewport
      -      $(document).width(); // returns width of HTML document
      -

      Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property.

      +
      
      +// Returns width of browser viewport
      +$( window ).width();
      +
      +// Returns width of HTML document
      +$( document ).width();
      +      
      +

      Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width().

      +
      +

      Note: Although style and script tags will report a value for .width() or height() when absolutely positioned and given display:block, it is strongly discouraged to call those methods on these tags. In addition to being a bad practice, the results may also prove unreliable.

      +
      + + Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. - + body { + background: yellow; + } + button { + font-size: 12px; + margin: 2px; + } + p { + width: 150px; + border: 1px red solid; + } + div { + color: red; + font-weight: bold; + } +]]> + @@ -67,7 +88,13 @@ $("#getw").click(function () { 1.4.1 - + + + + + + + A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. @@ -80,25 +107,32 @@ $("#getw").click(function () { Change the width of each div the first time it is clicked (and change its color). + div { + width: 70px; + height: 50px; + float: left; + margin: 5px; + background: red; + cursor: pointer; + } + .mod { + background: blue; + cursor: default; + } +]]> diff --git a/entries/wrap.xml b/entries/wrap.xml index 4db0e15a9..d6258d707 100644 --- a/entries/wrap.xml +++ b/entries/wrap.xml @@ -8,98 +8,155 @@ - A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. When you pass a jQuery collection containing more than one element, or a selector matching more than one element, the first element will be used. 1.4 - + A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + + + + + Wrap an HTML structure around each element in the set of matched elements.

      The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.

      Consider the following HTML:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner">Hello</div>
         <div class="inner">Goodbye</div>
      -</div>
      +</div> +

      Using .wrap(), we can insert an HTML structure around the inner <div> elements like so:

      -
      $('.inner').wrap('<div class="new" />');
      +
      
      +$( ".inner" ).wrap( "<div class='new'></div>" );
      +    

      The new <div> element is created on the fly and added to the DOM. The result is a new <div> wrapped around each matched element:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="new">
           <div class="inner">Hello</div>
         </div>
         <div class="new">
           <div class="inner">Goodbye</div>
         </div>
      -</div>
      +</div> +

      The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the corresponding element. For example:

      -
      $('.inner').wrap(function() {
      -  return '<div class="' + $(this).text() + '" />';
      -});
      +
      
      +$( ".inner" ).wrap(function() {
      +  return "<div class='" + $( this ).text() + "'></div>";
      +});
      +    

      This will cause each <div> to have a class corresponding to the text it wraps:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="Hello">
           <div class="inner">Hello</div>
         </div>
         <div class="Goodbye">
           <div class="inner">Goodbye</div>
         </div>
      -</div>
      +</div> +
      Wrap a new div around all of the paragraphs. - + - + div { + border: 2px solid blue; + } + p { + background: yellow; + margin: 4px; + } +]]> + - - + Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.> + - + div { + border: 2px blue solid; + margin: 2px; + padding: 2px; + } + p { + background: yellow; + margin: 2px; + padding: 2px; + } + strong { + color: red; + } +]]> + Wrap a new div around all of the paragraphs. - + - + div { + border: 2px solid blue; + } + p { + background: yellow; + margin: 4px; + } +]]> + Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target. - + - + div { + border: 2px solid blue; + margin: 2px; + padding: 2px; + } + .doublediv { + border-color: red; + } + p { + background: yellow; + margin: 4px; + font-size: 14px; + } +]]> + diff --git a/entries/wrapAll.xml b/entries/wrapAll.xml index 20b224460..7d8c741dc 100644 --- a/entries/wrapAll.xml +++ b/entries/wrapAll.xml @@ -11,74 +11,132 @@ A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + + 1.4 + + A callback function returning the HTML content or jQuery object to wrap around all the matched elements. Within the function, this refers to the first element in the set. Prior to jQuery 3.0, the callback was incorrectly called for every element in the set and received the index position of the element in the set as an argument. + + + + + + Wrap an HTML structure around all elements in the set of matched elements.

      The .wrapAll() function can take any string or object that could be passed to the $() function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around all of the elements in the set of matched elements, as a single group.

      Consider the following HTML:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner">Hello</div>
         <div class="inner">Goodbye</div>
      -</div>
      +</div> +

      Using .wrapAll(), we can insert an HTML structure around the inner <div> elements like so:

      -
      $('.inner').wrapAll('<div class="new" />');
      +
      
      +$( ".inner" ).wrapAll( "<div class='new' />");
      +    

      The new <div> element is created on the fly and added to the DOM. The result is a new <div> wrapped around all matched elements:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="new">
           <div class="inner">Hello</div>
           <div class="inner">Goodbye</div>
         </div>
      -</div>
      +</div> +
      Wrap a new div around all of the paragraphs. - + - + div { + border: 2px solid blue; + } + p { + background: yellow; + margin: 4px; + } +]]> + Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html. - + - + div { + border: 2px blue solid; + margin: 2px; + padding: 2px; + } + p { + background: yellow; + margin: 2px; + padding: 2px; + } + strong { + color: red; + } +]]> + Wrap a new div around all of the paragraphs. - + - + div { + border: 2px solid blue; + } + p { + background: yellow; + margin: 4px; + } +]]> + Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target. - + - + div { + border: 2px solid blue; + margin: 2px; + padding: 2px; + } + .doublediv { + border-color: red; + } + p { + background: yellow; + margin: 4px; + font-size: 14px; + } +]]> + diff --git a/entries/wrapInner.xml b/entries/wrapInner.xml index 4484bf6c4..42e0101aa 100644 --- a/entries/wrapInner.xml +++ b/entries/wrapInner.xml @@ -3,96 +3,143 @@ .wrapInner() 1.2 - + An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + + + + 1.4 - + A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + + Wrap an HTML structure around the content of each element in the set of matched elements.

      The .wrapInner() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. The structure will be wrapped around the content of each of the elements in the set of matched elements.

      Consider the following HTML:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner">Hello</div>
         <div class="inner">Goodbye</div>
      -</div>
      +</div> +

      Using .wrapInner(), we can insert an HTML structure around the content of each inner <div> elements like so:

      -
      $('.inner').wrapInner('<div class="new" />');
      +
      
      +$( ".inner" ).wrapInner( "<div class='new'></div>");
      +    

      The new <div> element is created on the fly and added to the DOM. The result is a new <div> wrapped around the content of each matched element:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner">
           <div class="new">Hello</div>
         </div>
         <div class="inner">
           <div class="new">Goodbye</div>
         </div>
      -</div>
      +</div> +

      The second version of this method allows us to instead specify a callback function. This callback function will be called once for every matched element; it should return a DOM element, jQuery object, or HTML snippet in which to wrap the content of the corresponding element. For example:

      -
      $('.inner').wrapInner(function() {
      -  return '<div class="' + this.nodeValue + '" />';
      -});
      +
      
      +$( ".inner" ).wrapInner(function() {
      +  return "<div class='" + this.nodeValue + "'></div>";
      +});
      +    

      This will cause each <div> to have a class corresponding to the text it wraps:

      -
      <div class="container">
      +    
      
      +<div class="container">
         <div class="inner">
           <div class="Hello">Hello</div>
         </div>
         <div class="inner">
           <div class="Goodbye">Goodbye</div>
         </div>
      -</div>
      +</div> +

      Note: When passing a selector string to the .wrapInner() function, the expected input is well formed HTML with correctly closed tags. Examples of valid input include:

      
      -$(elem).wrapInner("<div class='test' />");
      -$(elem).wrapInner("<div class='test'></div>");
      -$(elem).wrapInner("<div class=\"test\"></div>");
      +$( elem ).wrapInner( "<div class='test'></div>" );
      +$( elem ).wrapInner( "<div class=\"test\"></div>" );
           
      Selects all paragraphs and wraps a bold tag around each of its contents. - - - + + + Wraps a newly created tree of objects around the inside of the body. - + - + div { + border: 2px green solid; + margin: 2px; + padding: 2px; + } + p { + background: yellow; + margin: 2px; + padding: 2px; + } +]]> + Selects all paragraphs and wraps a bold tag around each of its contents. - - - + + + Selects all paragraphs and wraps a jQuery object around each of its contents. - + - + p { + background: #9f9; + } + .red { + color: red; + } +]]> + -
      \ No newline at end of file +
      diff --git a/entries2html.xsl b/entries2html.xsl index 94773604c..a1a199827 100755 --- a/entries2html.xsl +++ b/entries2html.xsl @@ -6,22 +6,24 @@ -<!DOCTYPE html> -<html> -<head> - <style></style> - <script src="http://code.jquery.com/jquery-latest.js"></script> +<!doctype html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title> demo</title> + <style> </style> + <script src="https://code.jquery.com/jquery-3.7.1.js"></script> <script> - + </script> </head> <body> - + -<script></script> +<script></script> </body> diff --git a/grunt.js b/grunt.js deleted file mode 100644 index ea16b4694..000000000 --- a/grunt.js +++ /dev/null @@ -1,44 +0,0 @@ -/*jshint node:true */ -module.exports = function( grunt ) { -"use strict"; - -var entryFiles = grunt.file.expandFiles( "entries/*.xml" ); - -grunt.loadNpmTasks( "grunt-clean" ); -grunt.loadNpmTasks( "grunt-wordpress" ); -grunt.loadNpmTasks( "grunt-jquery-content" ); -grunt.loadNpmTasks( "grunt-check-modules" ); - -grunt.initConfig({ - clean: { - folder: "dist" - }, - lint: { - grunt: "grunt.js" - }, - xmllint: { - all: [].concat( entryFiles, "categories.xml", "entries2html.xsl", "notes.xsl" ) - }, - xmltidy: { - all: [].concat( entryFiles, "categories.xml" ) - }, - "build-pages": { - all: grunt.file.expandFiles( "pages/**" ) - }, - "build-xml-entries": { - all: entryFiles - }, - "build-resources": { - all: grunt.file.expandFiles( "resources/**" ) - }, - wordpress: grunt.utils._.extend({ - dir: "dist/wordpress" - }, grunt.file.readJSON( "config.json" ) ) -}); - -grunt.registerTask( "default", "build-wordpress" ); -grunt.registerTask( "build", "build-pages build-xml-entries build-xml-categories build-xml-full build-resources" ); -grunt.registerTask( "build-wordpress", "check-modules clean lint xmllint build" ); -grunt.registerTask( "tidy", "xmllint xmltidy" ); - -}; diff --git a/includes/complete-argument.xml b/includes/complete-argument.xml index 042fdf453..4ef06fa39 100644 --- a/includes/complete-argument.xml +++ b/includes/complete-argument.xml @@ -1,4 +1,4 @@ - A function to call once the animation is complete. + A function to call once the animation is complete, called once per matched element. diff --git a/includes/duration-argument.xml b/includes/duration-argument.xml index 1a1c5c5e3..8fcfb7f30 100644 --- a/includes/duration-argument.xml +++ b/includes/duration-argument.xml @@ -1,6 +1,6 @@ - A string or number determining how long the animation will run. - - + A string or number determining how long the animation will run. + + diff --git a/includes/easing-argument.xml b/includes/easing-argument.xml index b64835515..127057afe 100644 --- a/includes/easing-argument.xml +++ b/includes/easing-argument.xml @@ -1,4 +1,4 @@ - A string indicating which easing function to use for the transition. + A string indicating which easing function to use for the transition. diff --git a/includes/options-argument.xml b/includes/options-argument.xml index 99bbf34cd..cacb3286f 100644 --- a/includes/options-argument.xml +++ b/includes/options-argument.xml @@ -1,73 +1,81 @@ - A map of additional options to pass to the method. - - A string or number determining how long the animation will run. - - - - - A string indicating which easing function to use for the transition. - - - A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. - - - A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. - + A map of additional options to pass to the method. + + A string or number determining how long the animation will run. + + + + + A string indicating which easing function to use for the transition. + + + A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. + + + + + An object containing one or more of the CSS properties defined by the properties argument and their corresponding easing functions. + - - A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. - - The numeric value of the property being animated at each step - - - An object of properties related to the animation and the element being animated. For information about the tween object and its properties, see jQuery.Tween - - + + A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. + + The numeric value of the property being animated at each step + + + An object of properties related to the animation and the element being animated. For information about the tween object and its properties, see jQuery.Tween + + - - A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. - - An enhanced Promise oject with additional properties for the animation - - - A number from 0 to 1 indicating the progress of the animation - - - A number indicating the remaining number of milliseconds until the scheduled end of the animation - - - - A function to call once the animation is complete. - - - - A function to be called when the animation completes (its Promise object is resolved). - - An enhanced Promise oject with additional properties for the animation - - - Indicates whether the animation jumped to the end - - - - A function to be called when the animation fails to complete (its Promise object is rejected). - - An enhanced Promise oject with additional properties for the animation - - - Indicates whether the animation jumped to the end - - - - A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). - - An enhanced Promise oject with additional properties for the animation - - - Indicates whether the animation jumped to the end - - + + A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. + + An enhanced Promise object with additional properties for the animation + + + A number from 0 to 1 indicating the progress of the animation + + + A number indicating the remaining number of milliseconds until the scheduled end of the animation + + + + A function that is called once the animation on an element is complete. + + + + A function to call when the animation on an element begins. + + An enhanced Promise object with additional properties for the animation + + + + A function to be called when the animation on an element completes (its Promise object is resolved). + + An enhanced Promise object with additional properties for the animation + + + Indicates whether the animation jumped to the end + + + + A function to be called when the animation on an element fails to complete (its Promise object is rejected). + + An enhanced Promise object with additional properties for the animation + + + Indicates whether the animation jumped to the end + + + + A function to be called when the animation on an element completes or stops without completing (its Promise object is either resolved or rejected). + + An enhanced Promise object with additional properties for the animation + + + Indicates whether the animation jumped to the end + + diff --git a/notes.xsl b/notes.xsl index bec2e8da2..6963dad28 100644 --- a/notes.xsl +++ b/notes.xsl @@ -1,45 +1,75 @@ + + undefined is not recognized as a data value. Calls such as ( , undefined ) will return the jQuery object that it was called on, allowing for chaining. + + + undefined is not recognized as a data value. Calls such as ( , undefined ) will return the corresponding data for "name", and is therefore the same as ( ). + + + The number returned by dimensions-related APIs, including , may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition. + + + Prior to jQuery 1.9, would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9, .after(), .before(), and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed. + Selected elements are in the order of their appearance in the document. - Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint. + Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint. + + + The value reported by is not guaranteed to be accurate when the element or its parent is hidden. To get an accurate value, ensure the element is visible before using . jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery. - Because is a jQuery extension and not part of the CSS specification, queries using cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using to select elements, first select the elements using a pure CSS selector, then use .filter(""). + Because is a jQuery extension and not part of the CSS specification, queries using cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using to select elements, first select the elements using a pure CSS selector, then use .filter(""). Because is a jQuery extension and not part of the CSS specification, queries using cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use instead. - All jQuery effects, including , can be turned off globally by setting jQuery.fx.off = true, which effectively sets the duration to 0. For more information, see jQuery.fx.off. + All jQuery effects, including , can be turned off globally by setting jQuery.fx.off = true, which effectively sets the duration to 0. For more information, see jQuery.fx.off. Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties. - In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data(). + In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data(). - Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false. + Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false. + + + The method removes all data and event handlers associated with the removed nodes. - Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol. + Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol. Script and JSONP requests are not subject to the same origin policy restrictions. - If a request with returns an error code, it will fail silently unless the script has also called the global .ajaxError() method. Alternatively, as of jQuery 1.5, the .error() method of the jqXHR object returned by is also available for error handling. + If a request with returns an error code, it will fail silently unless the script has also called the global ajaxError event. Alternatively, as of jQuery 1.5, the .error() method of the jqXHR object returned by is also available for error handling. - If $.ajax() or $.ajaxSetup() is called with the global option set to false, the method will not fire. + If $.ajax() or $.ajaxSetup() is called with the global option set to false, the event will not fire. If is called on an unordered list (<ul>) and its <li> elements have position (relative, absolute, or fixed), the effect may not work properly in IE6 through at least IE9 unless the <ul> has "layout." To remedy the problem, add the position: relative; and zoom: 1; CSS declarations to the ul. + + By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document. + + + Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance. + + + As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with .on( "", ... ), must be attached to document. + + + jQuery doesn't officially support SVG. Using jQuery methods on SVG documents, unless explicitly documented for that method, might cause unexpected behaviors. Examples of methods that support SVG as of jQuery 3.0 are addClass and removeClass. + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..d81d50e00 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1292 @@ +{ + "name": "api.jquery.com", + "version": "3.3.13", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "api.jquery.com", + "version": "3.3.13", + "dependencies": { + "grunt": "1.6.1", + "grunt-jquery-content": "3.3.2" + } + }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/argparse/node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" + }, + "node_modules/array-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/array-each/-/array-each-1.0.1.tgz", + "integrity": "sha1-p5SvDAWrF1KEbudTofIRoFugxE8=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-slice": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-1.1.0.tgz", + "integrity": "sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/async": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.4.tgz", + "integrity": "sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ==" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==" + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cheerio": { + "version": "1.0.0-rc.12", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz", + "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "htmlparser2": "^8.0.1", + "parse5": "^7.0.0", + "parse5-htmlparser2-tree-adapter": "^7.0.0" + }, + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/cheerio-select": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", + "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", + "dependencies": { + "boolbase": "^1.0.0", + "css-select": "^5.1.0", + "css-what": "^6.1.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/colors": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.1.2.tgz", + "integrity": "sha1-FopHAXVran9RoSzgyXv6KMCE7WM=", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "node_modules/css-select": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz", + "integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", + "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/dateformat": { + "version": "4.6.3", + "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", + "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", + "engines": { + "node": "*" + } + }, + "node_modules/detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ] + }, + "node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.1.0.tgz", + "integrity": "sha512-H78uMmQtI2AhgDJjWeQmHwJJ2bLPD3GMmO7Zja/ZZh84wkm+4ut+IUnUdRa8uCGX88DiVx1j6FRe1XfxEgjEZA==", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/eventemitter2": { + "version": "0.4.14", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-0.4.14.tgz", + "integrity": "sha1-j2G3XN4BKy6esoTUVFWDtWQ7Yas=" + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "dependencies": { + "homedir-polyfill": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/findup-sync": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-5.0.0.tgz", + "integrity": "sha512-MzwXju70AuyflbgeOhzvQWAvvQdo1XL0A9bVvlXsYcFEBM87WR4OakL4OfZq+QRmr+duJubio+UtNQCPsVESzQ==", + "dependencies": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.3", + "micromatch": "^4.0.4", + "resolve-dir": "^1.0.1" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/fined": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/fined/-/fined-1.2.0.tgz", + "integrity": "sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng==", + "dependencies": { + "expand-tilde": "^2.0.2", + "is-plain-object": "^2.0.3", + "object.defaults": "^1.1.0", + "object.pick": "^1.2.0", + "parse-filepath": "^1.0.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/flagged-respawn": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/flagged-respawn/-/flagged-respawn-1.0.1.tgz", + "integrity": "sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/for-own": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz", + "integrity": "sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=", + "dependencies": { + "for-in": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/getobject": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/getobject/-/getobject-1.0.2.tgz", + "integrity": "sha512-2zblDBaFcb3rB4rF77XVnuINOE2h2k/OnqXAiy0IrTxUfV1iFp3la33oAQVY9pCpWU268WFYVt2t71hlMuLsOg==", + "engines": { + "node": ">=10" + } + }, + "node_modules/gilded-wordpress": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/gilded-wordpress/-/gilded-wordpress-1.0.7.tgz", + "integrity": "sha512-w8g4jfs1TWywX2hZ4+LlzQoz2z/JRX/8S6OgelD3IUsNnGHxXQ1FgExoIqomwZVPAmxYs0vEu2BeA1Y4KciZlw==", + "dependencies": { + "async": "^0.9.0", + "wordpress": "^1.4.2" + } + }, + "node_modules/gilded-wordpress/node_modules/async": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha512-l6ToIJIotphWahxxHyzK9bnLR6kM4jJIIgLShZeqLY7iboHoGkdgFl7W2/Ivi4SkMJYGKqW8vSuk0uKUj6qsSw==" + }, + "node_modules/glob": { + "version": "7.1.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz", + "integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "dependencies": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", + "dependencies": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/grunt": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/grunt/-/grunt-1.6.1.tgz", + "integrity": "sha512-/ABUy3gYWu5iBmrUSRBP97JLpQUm0GgVveDCp6t3yRNIoltIYw7rEj3g5y1o2PGPR2vfTRGa7WC/LZHLTXnEzA==", + "dependencies": { + "dateformat": "~4.6.2", + "eventemitter2": "~0.4.13", + "exit": "~0.1.2", + "findup-sync": "~5.0.0", + "glob": "~7.1.6", + "grunt-cli": "~1.4.3", + "grunt-known-options": "~2.0.0", + "grunt-legacy-log": "~3.0.0", + "grunt-legacy-util": "~2.0.1", + "iconv-lite": "~0.6.3", + "js-yaml": "~3.14.0", + "minimatch": "~3.0.4", + "nopt": "~3.0.6" + }, + "bin": { + "grunt": "bin/grunt" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/grunt-check-modules": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/grunt-check-modules/-/grunt-check-modules-1.1.0.tgz", + "integrity": "sha1-fBZB28ZlSGdqbVl5Ga35C3s11kQ=", + "engines": { + "node": ">=0.6.0" + }, + "peerDependencies": { + "grunt": ">=0.4.0" + } + }, + "node_modules/grunt-jquery-content": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/grunt-jquery-content/-/grunt-jquery-content-3.3.2.tgz", + "integrity": "sha512-b6w8GBe022BG8O7BkhAKBFcBBAldoIiwAUZ2WI+A8HIouXy8XS8Cwp2RuUPEACg3g2/wHOarmjrsFKFPmmZ55Q==", + "dependencies": { + "cheerio": "^1.0.0-rc.12", + "gilded-wordpress": "1.0.7", + "grunt-check-modules": "^1.1.0", + "he": "^1.2.0", + "highlight.js": "^10.7.2", + "marked": "^4.0.0", + "which": "^4.0.0", + "wordpress": "^1.4.1" + } + }, + "node_modules/grunt-jquery-content/node_modules/isexe": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.1.tgz", + "integrity": "sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ==", + "engines": { + "node": ">=16" + } + }, + "node_modules/grunt-jquery-content/node_modules/which": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-4.0.0.tgz", + "integrity": "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/grunt-legacy-log": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/grunt-legacy-log/-/grunt-legacy-log-3.0.0.tgz", + "integrity": "sha512-GHZQzZmhyq0u3hr7aHW4qUH0xDzwp2YXldLPZTCjlOeGscAOWWPftZG3XioW8MasGp+OBRIu39LFx14SLjXRcA==", + "dependencies": { + "colors": "~1.1.2", + "grunt-legacy-log-utils": "~2.1.0", + "hooker": "~0.2.3", + "lodash": "~4.17.19" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/grunt-legacy-log-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/grunt-legacy-log-utils/-/grunt-legacy-log-utils-2.1.0.tgz", + "integrity": "sha512-lwquaPXJtKQk0rUM1IQAop5noEpwFqOXasVoedLeNzaibf/OPWjKYvvdqnEHNmU+0T0CaReAXIbGo747ZD+Aaw==", + "dependencies": { + "chalk": "~4.1.0", + "lodash": "~4.17.19" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/grunt-legacy-util": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/grunt-legacy-util/-/grunt-legacy-util-2.0.1.tgz", + "integrity": "sha512-2bQiD4fzXqX8rhNdXkAywCadeqiPiay0oQny77wA2F3WF4grPJXCvAcyoWUJV+po/b15glGkxuSiQCK299UC2w==", + "dependencies": { + "async": "~3.2.0", + "exit": "~0.1.2", + "getobject": "~1.0.0", + "hooker": "~0.2.3", + "lodash": "~4.17.21", + "underscore.string": "~3.3.5", + "which": "~2.0.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/grunt-legacy-util/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/grunt/node_modules/grunt-cli": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/grunt-cli/-/grunt-cli-1.4.3.tgz", + "integrity": "sha512-9Dtx/AhVeB4LYzsViCjUQkd0Kw0McN2gYpdmGYKtE2a5Yt7v1Q+HYZVWhqXc/kGnxlMtqKDxSwotiGeFmkrCoQ==", + "dependencies": { + "grunt-known-options": "~2.0.0", + "interpret": "~1.1.0", + "liftup": "~3.0.1", + "nopt": "~4.0.1", + "v8flags": "~3.2.0" + }, + "bin": { + "grunt": "bin/grunt" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/grunt/node_modules/grunt-cli/node_modules/nopt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-4.0.3.tgz", + "integrity": "sha512-CvaGwVMztSMJLOeXPrez7fyfObdZqNUK1cPAEzLHrTybIua9pMdmmPR5YwtfNftIOMv3DPUhFaxsZMNTQO20Kg==", + "dependencies": { + "abbrev": "1", + "osenv": "^0.1.4" + }, + "bin": { + "nopt": "bin/nopt.js" + } + }, + "node_modules/grunt/node_modules/grunt-known-options": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/grunt-known-options/-/grunt-known-options-2.0.0.tgz", + "integrity": "sha512-GD7cTz0I4SAede1/+pAbmJRG44zFLPipVtdL9o3vqx9IEyb7b4/Y3s7r6ofI3CchR5GvYJ+8buCSioDv5dQLiA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "bin": { + "he": "bin/he" + } + }, + "node_modules/highlight.js": { + "version": "10.7.2", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.2.tgz", + "integrity": "sha512-oFLl873u4usRM9K63j4ME9u3etNF0PLiJhSQ8rdfuL51Wn3zkD6drf9ZW0dOzjnZI22YYG24z30JcmfCZjMgYg==", + "engines": { + "node": "*" + } + }, + "node_modules/homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "dependencies": { + "parse-passwd": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/hooker": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/hooker/-/hooker-0.2.3.tgz", + "integrity": "sha1-uDT3I8xKJCqmWWNFnfbZhMXT2Vk=", + "engines": { + "node": "*" + } + }, + "node_modules/htmlparser2": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.2.tgz", + "integrity": "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "entities": "^4.4.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "node_modules/interpret": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.1.0.tgz", + "integrity": "sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=" + }, + "node_modules/is-absolute": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "dependencies": { + "is-relative": "^1.0.0", + "is-windows": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-core-module": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.4.0.tgz", + "integrity": "sha512-6A2fkfq1rfeQZjxrZJGerpLCTHRNEBiSgnu0+obeJpEPZRUooHgsizvzv0ZjJwOz3iWIHdJtVWJ/tmPr3D21/A==", + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-relative": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "dependencies": { + "is-unc-path": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-unc-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "dependencies": { + "unc-path-regex": "^0.1.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/liftup": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/liftup/-/liftup-3.0.1.tgz", + "integrity": "sha512-yRHaiQDizWSzoXk3APcA71eOI/UuhEkNN9DiW2Tt44mhYzX4joFoCZlxsSOF7RyeLlfqzFLQI1ngFq3ggMPhOw==", + "dependencies": { + "extend": "^3.0.2", + "findup-sync": "^4.0.0", + "fined": "^1.2.0", + "flagged-respawn": "^1.0.1", + "is-plain-object": "^2.0.4", + "object.map": "^1.0.1", + "rechoir": "^0.7.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/liftup/node_modules/findup-sync": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-4.0.0.tgz", + "integrity": "sha512-6jvvn/12IC4quLBL1KNokxC7wWTvYncaVUYSoxWw7YykPLuRrnv4qdHcSOywOI5RpkOVGeQRtWM8/q+G6W6qfQ==", + "dependencies": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.0", + "micromatch": "^4.0.2", + "resolve-dir": "^1.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/make-iterator": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/make-iterator/-/make-iterator-1.0.1.tgz", + "integrity": "sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw==", + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/marked": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz", + "integrity": "sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.8.tgz", + "integrity": "sha512-6FsRAQsxQ61mw+qP1ZzbL9Bc78x2p5OqNgNpnoAFLTrX8n5Kxph0CsnhmKKNXTWjXqU5L0pGPR7hYk+XWZr60Q==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/nopt": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz", + "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/object.defaults": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object.defaults/-/object.defaults-1.1.0.tgz", + "integrity": "sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8=", + "dependencies": { + "array-each": "^1.0.1", + "array-slice": "^1.0.0", + "for-own": "^1.0.0", + "isobject": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object.map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object.map/-/object.map-1.0.1.tgz", + "integrity": "sha1-z4Plncj8wK1fQlDh94s7gb2AHTc=", + "dependencies": { + "for-own": "^1.0.0", + "make-iterator": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/osenv": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz", + "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==", + "dependencies": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "node_modules/parse-filepath": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/parse-filepath/-/parse-filepath-1.0.2.tgz", + "integrity": "sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE=", + "dependencies": { + "is-absolute": "^1.0.0", + "map-cache": "^0.2.0", + "path-root": "^0.1.1" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/parse5": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", + "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", + "dependencies": { + "entities": "^4.4.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz", + "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==", + "dependencies": { + "domhandler": "^5.0.2", + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" + }, + "node_modules/path-root": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc=", + "dependencies": { + "path-root-regex": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/rechoir": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.0.tgz", + "integrity": "sha512-ADsDEH2bvbjltXEP+hTIAmeFekTFK0V2BTxMkok6qILyAJEXV0AFfoWcAq4yfll5VdIMd/RVXq0lR+wQi5ZU3Q==", + "dependencies": { + "resolve": "^1.9.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dependencies": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "dependencies": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, + "node_modules/sprintf-js": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz", + "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==" + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/underscore.string": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/underscore.string/-/underscore.string-3.3.6.tgz", + "integrity": "sha512-VoC83HWXmCrF6rgkyxS9GHv8W9Q5nhMKho+OadDJGzL2oDYbYEppBaCMH6pFlwLeqj2QS+hhkw2kpXkSdD1JxQ==", + "dependencies": { + "sprintf-js": "^1.1.1", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" + }, + "node_modules/v8flags": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-3.2.0.tgz", + "integrity": "sha512-mH8etigqMfiGWdeXpaaqGfs6BndypxusHHcv2qSHyZkGEznCd/qAXCWWRzeowtL54147cktFOC4P5y+kl8d8Jg==", + "dependencies": { + "homedir-polyfill": "^1.0.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/wordpress": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/wordpress/-/wordpress-1.4.2.tgz", + "integrity": "sha512-T+o+Af6pK7mhTz/rJEZk4PpSIyRMVhx6vZm6UsmrnlL8pVudhu1gWzn1n3wZXlcEZQz7I0AOkEvPQ5hu++L+qg==", + "dependencies": { + "xmlrpc": "1.3.2" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/xmlbuilder": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-8.2.2.tgz", + "integrity": "sha512-eKRAFz04jghooy8muekqzo8uCSVNeyRedbuJrp0fovbLIi7wlsYtdUn3vBAAPq2Y3/0xMz2WMEUQ8yhVVO9Stw==", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/xmlrpc": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/xmlrpc/-/xmlrpc-1.3.2.tgz", + "integrity": "sha512-jQf5gbrP6wvzN71fgkcPPkF4bF/Wyovd7Xdff8d6/ihxYmgETQYSuTc+Hl+tsh/jmgPLro/Aro48LMFlIyEKKQ==", + "dependencies": { + "sax": "1.2.x", + "xmlbuilder": "8.2.x" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.0.0" + } + } + } +} diff --git a/package.json b/package.json index db4a19eca..49adc96c6 100644 --- a/package.json +++ b/package.json @@ -1,32 +1,12 @@ { "name": "api.jquery.com", - "title": "jQuery API Docs", - "description": "API reference documentation for the jQuery JavaScript Library.", - "version": "1.9.1-3", - "homepage": "https://github.com/jquery/api.jquery.com", - "author": { - "name": "jQuery Foundation (http://jquery.org/)" + "version": "3.3.13", + "private": true, + "scripts": { + "test": "grunt lint" }, - "repository": { - "type": "git", - "url": "git://github.com/jquery/api.jquery.com.git" - }, - "bugs": { - "url": "https://github.com/jquery/api.jquery.com/issues" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/MIT" - } - ], "dependencies": { - "grunt": "0.3.x", - "grunt-clean": "0.3.0", - "grunt-wordpress": "1.0.5", - "grunt-jquery-content": "0.8.1", - "grunt-check-modules": "0.1.0" - }, - "devDependencies": {}, - "keywords": [] + "grunt": "1.6.1", + "grunt-jquery-content": "3.3.2" + } } diff --git a/pages/Ajax_Events.html b/pages/Ajax_Events.html index 272fdf425..6b1249be3 100644 --- a/pages/Ajax_Events.html +++ b/pages/Ajax_Events.html @@ -3,7 +3,7 @@ "title": "Ajax Events" } -

      Ajax requests produce a number of different events that you can subscribe to. Here's a full list of the events and in what order they are broadcast.

      +

      Ajax requests produce a number of different events that you can subscribe to. Here's a full list of the events and in what order they are triggered.

      There are two types of events:

      Local Events

      These are callbacks that you can subscribe to within the Ajax request object, like so:

      @@ -18,11 +18,11 @@

      Local Events

      });

      Global Events

      -

      These events are broadcast to all elements in the DOM, triggering any handlers which may be listening. You can listen for these events like so:

      -
       $("#loading").bind("ajaxSend", function(){
      -   $(this).show();
      - }).bind("ajaxComplete", function(){
      -   $(this).hide();
      +

      These events are triggered on the document, calling any handlers which may be listening. You can listen for these events like so:

      +
       $(document).on("ajaxSend", function(){
      +   $("#loading").show();
      + }).on("ajaxComplete", function(){
      +   $("#loading").hide();
        });
       

      Global events can be disabled for a particular Ajax request by passing in the global option, like so:

      @@ -33,10 +33,10 @@

      Global Events

      });

      Events

      -

      This is the full list of Ajax events that are broadcast, and in the order in which they are broadcast. The indented events are broadcast for each and every Ajax request (unless a global option has been set). The ajaxStart and ajaxStop events are events that relate to all Ajax requests together. +

      This is the full list of Ajax events, and in the order in which they are triggered. The indented events are triggered for each and every Ajax request (unless a global option has been set). The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.

        -
      • ajaxStart (Global Event)
        This event is broadcast if an Ajax request is started and no other Ajax requests are currently running. +
      • ajaxStart (Global Event)
        This event is triggered if an Ajax request is started and no other Ajax requests are currently running.
        • beforeSend (Local Event)
          This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
        • ajaxSend (Global Event)
          This global event is also triggered before the request is run.
        • diff --git a/pages/Types.html b/pages/Types.html index aaaec9444..16a3a7c1b 100644 --- a/pages/Types.html +++ b/pages/Types.html @@ -1,6 +1,6 @@ -

          JavaScript provides several built-in datatypes. In addition to those, this page documents virtual types like Selectors, enhanced pseudo-types like Events and all and everything you wanted to know about Functions. +

          This page documents data types appearing in jQuery function signatures, whether defined by JavaScript itself or further restricted by jQuery. Unless explicitly stated otherwise, jQuery functions require primitive values where applicable, and do not accept their Object-wrapped forms. If you want to study these concepts in depth, take a look at MDN.

          -

          You should be able to try out most of the examples below by just copying them to your browser's JavaScript Console (Chrome, Safari with Develop menu activated, IE 8+) or Firebug console (Firefox). +

          You should be able to try out most of the examples below by just copying them to your browser's JavaScript Console.

          Whenever an example mentions that a type defaults to a boolean value, the result is good to know when using that type in a boolean context:

          @@ -35,6 +35,7 @@

          Contents

            +
          1. Anything
          2. String
          3. +
          4. Array-Like Object
          5. PlainObject
          6. +
          7. Date
          8. Function
          9. +
          10. Error
          11. Selector
          12. Event
          13. Element
          14. +
          15. Text
          16. jQuery
          17. XMLHttpRequest
          18. jqXHR
          19. +
          20. Thenable
          21. Deferred Object
          22. Promise Object
          23. Callbacks Object
          24. +
          25. XML Document
          26. +
          27. Qunit's Assert Object
          -

          String

          -

          A string in JavaScript is an immutable object that contains none, one or many characters. +

          Anything

          +

          The Anything virtual type is used in jQuery documentation to indicate that any type can be used or should be expected. +

          + +

          String

          +

          A string in JavaScript is an immutable primitive value that contains none, one or many characters.

          "I'm a String in JavaScript!"
           'So am I!'
          @@ -103,15 +115,15 @@ 

          String

          typeof "some string"; // "string"
           
          -

          Quoting

          +

          Quoting

          A string can be defined using single or double quotes. You can nest single quotes inside of double quotes, and the other way around. To mix double quotes with double quotes (or single with single), the nested ones have to be escaped with a backslash.

          "You make 'me' sad."
           'That\'s "cranking" good fun!'
           "<a href=\"home\">Home</a>"
           
          -

          Built-in Methods

          -

          A string in JavaScript has some built-in methods to manipulate the string, though the result is always a new string - or something else, eg. split returns an array. +

          Built-in Methods

          +

          A string in JavaScript has some built-in methods to manipulate the string, though the result is always a new string - or something else, eg. split returns an array.

          "hello".charAt( 0 ) // "h"
           "hello".toUpperCase() // "HELLO"
          @@ -119,13 +131,13 @@ 

          Built-in Methods

          "hello".replace( /e|o/g, "x" ) // "hxllx" "1,2,3".split( "," ) // [ "1", "2", "3" ]
          -

          Length Property

          +

          Length Property

          All strings have a length property.

          "Hello".length // 5
           "".length // 0
           
          -

          Boolean Default

          +

          Boolean Default

          An empty string defaults to false:

          !"" // true
          @@ -135,8 +147,9 @@ 

          Boolean Default

          !new Boolean( false ) // false
          -

          htmlString

          -

          A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with <tag ... >) and is parsed as such until the final > character.

          +

          htmlString

          +

          A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with <tag ... >) and is parsed as such until the final > character. Prior to jQuery 1.9, a string was considered to be HTML if it contained <tag ... > anywhere within the string.

          +

          When a string is passed as an argument to a manipulation method such as .append(), it is always considered to be HTML since jQuery's other common interpretation of a string (CSS selectors) does not apply in those contexts.

          For explicit parsing of a string to HTML, the $.parseHTML() method is available as of jQuery 1.8.

          // Appends hello:
           $( "hello" ).appendTo( "body" );
          @@ -153,8 +166,8 @@ 

          htmlString

          // Appends hellowaitbye: $( "hellowaitbye" ).appendTo( "body" );
          -

          Number

          -

          Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. All operators common in c-based languages are available to work with numbers (+, -, *, /, %, =, +=, -=, *=, /=, ++, --). +

          Number

          +

          Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable primitive values, just like strings. All operators common in c-based languages are available to work with numbers (+, -, *, /, %, =, +=, -=, *=, /=, ++, --).

          12
           3.543
          @@ -164,7 +177,7 @@ 

          Number

          typeof 12 // "number"
           typeof 3.543 // "number"
           
          -

          Boolean Default

          +

          Boolean Default

          If a number is zero, it defaults to false:

          !0 // true
          @@ -176,15 +189,13 @@ 

          Boolean Default

          0.1 + 0.2 // 0.30000000000000004
           
          -


          -

          -

          Math

          +

          Math

          JavaScript provides utilities to work with numbers in the Math object:

          Math.PI // 3.141592653589793
           Math.cos( Math.PI ) // -1
           
          -

          Parsing Numbers

          +

          Parsing Numbers

          parseInt and parseFloat help parsing strings into numbers. Both do some implicit conversion if the base isn't specified:

          parseInt( "123" ) = 123 // (implicit decimal)
          @@ -194,8 +205,8 @@ 

          Parsing Numbers

          parseInt( "11", 2 ) = 3 // (explicit binary) parseFloat( "10.10" ) = 10.1
          -

          Numbers to Strings

          -

          When appending numbers to string, the result is always a string. The operator is the same, so be careful: If you want to add numbers and then append them to a string, put parentheses around them: +

          Numbers to Strings

          +

          When appending numbers to string, the result is always a string. The operator is the same, so be careful: If you want to add numbers and then append them to a string, put parentheses around the numbers:

          "" + 1 + 2; // "12"
           "" + ( 1 + 2 ); // "3"
          @@ -207,7 +218,7 @@ 

          Numbers to Strings

          String( 1 ) + String( 2 ); // "12"
           String( 1 + 2 ); // "3"
           
          -

          NaN and Infinity

          +

          NaN and Infinity

          Parsing something that isn't a number results in NaN. isNaN helps to detect those cases:

          parseInt( "hello", 10 ) // NaN
          @@ -224,27 +235,25 @@ 

          NaN and Infinity

          Note that NaN compares in a strange way:

          -
          NaN == NaN // false (!)
          +
          NaN === NaN // false (!)
           

          But:

          -
          Infinity == Infinity // true
          +
          Infinity === Infinity // true
           
          -

          Integer

          +

          Integer

          An integer is a plain Number type, but whenever explicitly mentioned, indicates that a non-floating-point number is expected.

          -

          Float

          +

          Float

          A float is a plain Number type, just as Integer, but whenever explicitly mentioned, indicates that a floating-point number is expected.

          -


          -

          -

          Boolean

          +

          Boolean

          A boolean in JavaScript can be either true or false:

          if ( true ) console.log( "always!" );
           if ( false ) console.log( "never!" );
           
          -

          Object

          +

          Object

          Everything in JavaScript is an object, though some are more objective (haha). The easiest way to create an object is the object literal:

          var x = {};
          @@ -257,7 +266,7 @@ 

          Object

          typeof {} // "object"
           
          -

          Dot Notation

          +

          Dot Notation

          You can write and read properties of an object using the dot notation:

          y.name // "Pete"
          @@ -265,7 +274,7 @@ 

          Dot Notation

          x.name = y.name + " Pan" // "Pete Pan" x.age = y.age + 1 // 16
          -

          Array Notation

          +

          Array Notation

          Or you write and read properties using the array notation, which allows you to dynamically choose the property:

          var operations = {
          @@ -276,7 +285,7 @@ 

          Array Notation

          operations[ operation ] // "++" operations[ "multiply" ] = "*"; // "*"
          -

          Iteration

          +

          Iteration

          Iterating over objects is easy with the for-in-loop:

          var obj = {
          @@ -287,9 +296,9 @@ 

          Iteration

          alert( "key is " + [ key ] + ", value is " + obj[ key ] ); }
          -

          Note that for-in-loop can be spoiled by extending Object.prototype (see Object.prototype is verboten) so take care when using other libraries. +

          Note that for-in-loop can be spoiled by extending Object.prototype (see Object.prototype is verboten) so take care when using other libraries.

          -

          jQuery provides a generic each function to iterate over properties of objects, as well as elements of arrays: +

          jQuery provides a generic each function to iterate over properties of objects, as well as elements of arrays:

          jQuery.each( obj, function( key, value ) {
             console.log( "key", key, "value", value );
          @@ -298,19 +307,19 @@ 

          Iteration

          The drawback is that the callback is called in the context of each value and you therefore lose the context of your own object if applicable. More on this below at Functions.

          -

          Boolean default

          +

          Boolean default

          An object, no matter if it has properties or not, never defaults to false:

          !{} // false
           !!{} // true
           
          -

          Prototype

          +

          Prototype

          All objects have a prototype property. Whenever the interpreter looks for a property, it also checks in the object's prototype if the property is not found on the object itself. jQuery uses the prototype extensively to add methods to jQuery instances. Internally, jQuery makes jQuery.fn an alias of jQuery.prototype so you can use either one (though plugin developers have standardized on fn).

          var form = $("#myform");
           console.log( form.clearForm ); // undefined
           
          -// jQuery.fn == jQuery.prototype
          +// jQuery.fn === jQuery.prototype
           jQuery.fn.clearForm = function() {
             return this.find( ":input" ).each(function() {
               this.value = "";
          @@ -323,7 +332,7 @@ 

          Prototype

          form.clearForm();
          -

          Array

          +

          Array

          Arrays in JavaScript are mutable lists with a few built-in methods. You can define arrays using the array literal:

          var x = [];
          @@ -339,7 +348,7 @@ 

          Array

          x[ 0 ] = 1;
           y[ 2 ] // 3
           
          -

          Iteration

          +

          Iteration

          An array has a length property that is useful for iteration:

          for ( var i = 0; i < a.length; i++ ) {
          @@ -358,7 +367,7 @@ 

          Iteration

          // Do something with item }
          -

          jQuery provides a generic each function to iterate over element of arrays, as well as properties of objects: +

          jQuery provides a generic each function to iterate over element of arrays, as well as properties of objects:

          var x = [ 1, 2, 3 ];
           jQuery.each( x, function( index, value ) {
          @@ -389,21 +398,24 @@ 

          Iteration

          Note: .unshift() method does not return a length property in Internet Explorer.

          -

          Boolean Default

          +

          Boolean Default

          An array, no matter if it has elements or not, never defaults to false:

          ![] // false
           !![] // true
           
          -

          Array<Type> Notation

          +

          Array<Type> Notation

          In the jQuery API you'll often find the notation of Array<Type>:

          dragPrevention    Array<String>
           

          This indicates that the method doesn't only expect an array as the argument, but also specifies the expected type. The notation is borrowed from Java 5's generics notation (or C++ templates).

          -

          PlainObject

          -

          The PlainObject type is a JavaScript object containing zero or more key-value pairs. The plain object is, in other words, an Object object. It is designated "plain" in jQuery documentation to distinguish it from other kinds of JavaScript objects: for example, null, user-defined arrays, and host objects such as document, all of which have a typeof value of "object." The jQuery.isPlainObject() method identifies whether the passed argument is a plain object or not, as demonstrated below: +

          Array-Like Object

          +

          Either a true JavaScript Array or a JavaScript Object that contains a nonnegative integer length property and index properties from 0 up to length - 1. This latter case includes array-like objects commonly encountered in web-based code such as the arguments object and the NodeList object returned by many DOM methods.

          +

          When a jQuery API accepts either plain Objects or Array-Like objects, a plain Object with a numeric length property will trigger the Array-Like behavior.

          +

          PlainObject

          +

          The PlainObject type is a JavaScript object containing zero or more key-value pairs. The plain object is, in other words, an Object object. It is designated "plain" in jQuery documentation to distinguish it from other kinds of JavaScript objects: for example, null, user-defined arrays, and host objects such as document, all of which have a typeof value of "object." The jQuery.isPlainObject() method identifies whether the passed argument is a plain object or not, as demonstrated below:

          
             var a = [];
          @@ -419,7 +431,22 @@ 

          PlainObject

          jQuery.isPlainObject( o ); // true
          -

          Function

          +

          Null

          +

          The null keyword is a JavaScript literal that is commonly used to express the absence of an intentional value.

          + +

          Date

          +

          The Date type is a JavaScript object that represents a single moment in time. Date objects are instantiated using their constructor function, which by default creates an object that represents the current date and time. +

          +
          
          +new Date();
          +
          +

          To create a Date object for an alternative date and time, pass numeric arguments in the following order: year, month, day, hour, minute, second, millisecond — although note that the month is zero-based, whereas the other arguments are one-based. The following creates a Date object representing January 1st, 2014, at 8:15. +

          +
          
          +new Date( 2014, 0, 1, 8, 15 );
          +
          + +

          Function

          A function in JavaScript can be either named or anonymous. Any function can be assigned to a variable or passed to a method, but passing member functions this way can cause them to be called in the context of another object (i.e. with a different "this" object).

          function named() {}
          @@ -428,7 +455,7 @@ 

          Function

          You see a lot of anonymous functions in jQuery code:

          $( document ).ready(function() {});
          -$( "a" ).click(function() {});
          +$( "a)" ).on( "click", function() {});
           $.ajax({
             url: "someurl.php",
             success: function() {}
          @@ -436,7 +463,7 @@ 

          Function

          The type of a function is "function".

          -

          Arguments

          +

          Arguments

          Inside a function a special variable "arguments" is always available. It's similar to an array in that it has a length property, but it lacks the built-in methods of an array. The elements of the pseudo-array are the argument of the function call.

          function log( x ) {
          @@ -449,9 +476,9 @@ 

          Arguments

          The arguments object also has a callee property, which refers to the function you're inside of. For instance:

          var awesome = function() { return arguments.callee; }
          -awesome() == awesome // true
          +awesome() === awesome // true
           
          -

          Context, Call and Apply

          +

          Context, Call and Apply

          In JavaScript, the variable "this" always refers to the current context. By default, "this" refers to the window object. Within a function this context can change, depending on how the function is called.

          All event handlers in jQuery are called with the handling element as the context. @@ -459,7 +486,7 @@

          Context, Call and Apply

          $( document ).ready(function() {
             // this refers to window.document
           });
          -$( "a" ).click(function() {
          +$( "a)" ).on( "click", function() {
             // this refers to an anchor DOM element
           });
           
          @@ -472,7 +499,7 @@

          Context, Call and Apply

          scope.call( "foobar", [ 1, 2 ] ); // "foobar", 1 scope.apply( "foobar", [ 1, 2 ] ); // "foobar", 2
          -

          Scope

          +

          Scope

          In JavaScript, all variables defined inside a function are only visible inside that function scope. Consider the following example:

          // global
          @@ -486,7 +513,7 @@ 

          Scope

          It defines a variable x in the global scope, then defines an anonymous function and executes it immediately (the additional parentheses are required for immediate execution). Inside the function another variable x is defined with a different value. It is only visible within that function and doesn't overwrite the global variable.

          -

          Closures

          +

          Closures

          Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. In the following example, the variable counter is visible within the create, increment, and print functions, but not outside of them.

          function create() {
          @@ -506,7 +533,7 @@ 

          Closures

          The pattern allows you to create objects with methods that operate on data that isn't visible to the outside—the very basis of object-oriented programming.

          -

          Proxy Pattern

          +

          Proxy Pattern

          Combining the above knowledge gives you as a JavaScript developer quite a lot of power. One way to combine that is to implement a proxy pattern in JavaScript, enabling the basics of aspect-oriented programming (AOP):

          (function() {
          @@ -520,10 +547,10 @@ 

          Proxy Pattern

          The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.

          -

          Callback

          +

          Callback

          A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. jQuery's event system uses such callbacks everywhere:

          -
          $( "body" ).click(function( event ) {
          +
          $( "body" ).on( "click", function( event ) {
             console.log( "clicked: " + event.target );
           });
           
          @@ -531,18 +558,26 @@

          Callback

          Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false:

          -
          $( "#myform" ).submit(function() {
          +
          $( "#myform" ).on( "submit", function() {
             return false;
          -});
          +} );
           

          Instead of always returning false, the callback could check fields of the form for validity, and return false only when the form is invalid.

          -


          +

          Error

          +

          An instance of an Error object is thrown as an exception when a runtime error occurs. Error can also be used as base to define user custom exception classes. In JavaScript an error can be thrown as shown below: +

          +
          throw new Error( "The argument provided is incorrect" );
          +
          +

          An error can also be thrown by the engine under some circumstances. For example, when trying to access a property of null:

          -

          Selector

          -

          A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most cases, the DOM document present in all browsers, but can also be an XML document received via AJAX. +

          var obj = null;
          +console.log( obj.foo() );
          +
          +

          Selector

          +

          A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most cases, the DOM document present in all browsers, but can also be an XML document received via Ajax.

          -

          The selectors are a composition of CSS and custom additions. All selectors available in jQuery are documented on the Selectors API page. +

          The selectors are a composition of CSS and custom additions. All selectors available in jQuery are documented on the Selectors API page.

          There are lot of plugins that leverage jQuery's selectors in other ways. The validation plugin accepts a selector to specify a dependency, whether an input is required or not:

          @@ -557,32 +592,44 @@

          Selector

          Event

          jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

          -

          Those properties are all documented, and accompanied by examples, on the Event object page. +

          Those properties are all documented, and accompanied by examples, on the Event object page.

          -

          The standard events in the Document Object Model are: blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, and keyup. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. +

          The standard events in the Document Object Model are: blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, and keyup. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any.

          -

          Element

          -

          An element in the Document Object Model (DOM) has attributes, text and children. It provides methods to traverse the parent and children and to get access to its attributes. Due to a lot of flaws in DOM API specifications and implementations, those methods are no fun to use. jQuery provides a wrapper around those elements to help interacting with the DOM. But often enough you will be working directly with DOM elements, or see methods that (also) accept DOM elements as arguments. +

          Element

          +

          An element in the Document Object Model (DOM) can have attributes, text, and children. It provides methods to traverse the parent and children and to get access to its attributes. Due to inconsistencies in DOM API specifications and implementations, however, those methods can be a challenge to use. jQuery provides a "wrapper" around those elements to help interacting with the DOM. But sometimes you will be working directly with DOM elements, or see methods that (also) accept DOM elements as arguments.

          -

          Whenever you use jQuery's each-method, the context of your callback is set to a DOM element. That is also the case for event handlers. +

          Whenever you call jQuery's .each() method or one of its event methods on a jQuery collection, the context of the callback function — this — is set to a DOM element.

          -

          Some properties of DOM elements are quite consistent among browsers. Consider this example of a simple on-blur-validation: +

          Some properties of DOM elements are quite consistent among browsers. Consider this example of a simple onblur validation:

          -
          $( ":text" ).blur(function() {
          +
          $( "input[type='text']" ).on( "blur", function() {
             if( !this.value ) {
               alert( "Please enter some text!" );
             }
           });
           
          -

          You could replace this.value with $(this).val() to access the value of the text input via jQuery, but in that case you don't gain anything. +

          You could replace this.value with $(this).val() to access the value of the text input via jQuery, but in that case you wouldn't gain anything. +

          +

          Text

          +

          Text is a node of the Document Object Model (DOM) that represents the textual content of an element or an attribute. Consider the following code:

          -

          jQuery

          +
          <p id="target"><b>Hello</b> world</p>
          +

          If you retrieve the children of the paragraph of the example as follows: +

          +
          var children = document.getElementById( "target" ).childNodes;
          +
          +

          you obtain two children. The first one is the element representing the b tag. The second child is a text node containing the string " world". +

          +

          jQuery

          A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document. Since jQuery methods often use CSS selectors to match elements from a document, the set of elements in a jQuery object is often called a set of "matched elements" or "selected elements".

          The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().

          Most frequently, you will use the jQuery() function to create a jQuery object. jQuery() can also be accessed by its familiar single-character alias of $(), unless you have called jQuery.noConflict() to disable this option. Many jQuery methods return the jQuery object itself, so that method calls can be chained:

          +

          In API calls that return jQuery, the value returned will be the original jQuery object unless otherwise documented by that API. API methods such as .filter() or .not() modify their incoming set and thus return a new jQuery object. +

          $( "p" ).css( "color", "red" ).find( ".special" ).css( "color", "green" );
           

          Whenever you use a "destructive" jQuery method that potentially changes the set of elements in the jQuery object, such as .filter() or .find(), that method actually returns a new jQuery object with the resulting elements. To return to the previous jQuery object, you use the .end() method. @@ -591,27 +638,30 @@

          jQuery

          $( ".badEntry" ).css({ color: "red" });
           
          -

          XMLHttpRequest

          -

          Some of jQuery's AJAX functions return the native XMLHttpRequest (XHR) object, or pass it as an argument to success/error/complete handlers, so that you can do additional processing or monitoring on the request. Note that AJAX functions only return or pass an XHR object when an XHR object is actually used in the request. For example, JSONP requests and cross-domain GET requests use a script element rather than an XHR object. +

          XMLHttpRequest

          +

          Some of jQuery's Ajax functions return the native XMLHttpRequest (XHR) object, or pass it as an argument to success/error/complete handlers, so that you can do additional processing or monitoring on the request. Note that Ajax functions only return or pass an XHR object when an XHR object is actually used in the request. For example, JSONP requests and cross-domain GET requests use a script element rather than an XHR object.

          -

          Although the XHR object is a standard, there are variations in its behavior on different browsers. Refer to the W3C site and browsers' documentation for more information: +

          Although the XHR object is a standard, there are variations in its behavior on different browsers. Refer to the WHATWG site and Mozilla Developer Network for more information:

          -
          • W3C standard -
          • Apple (Safari) -
          • Mozilla (Firefox) -
          • Microsoft (Internet Explorer) -
          • Opera + -

            Google does not appear to have an official page for their XHR documentation for Chrome. As of version 5, Chrome does not support the use of the file protocol for XHR requests. -

            -

            jqXHR

            -

            As of jQuery 1.5, the $.ajax() method returns the jqXHR object, which is a superset of the XMLHTTPRequest object. For more information, see the jqXHR section of the $.ajax entry +

            jqXHR

            +

            As of jQuery 1.5, the $.ajax() method returns the jqXHR object, which is a superset of the XMLHTTPRequest object. For more information, see the jqXHR section of the $.ajax entry

            +

            Thenable

            +

            Any object that has a then method.

            Deferred Object

            -

            As of jQuery 1.5, the Deferred object provides a way to register multiple callbacks into self-managed callback queues, invoke callback queues as appropriate, and relay the success or failure state of any synchronous or asynchronous function. +

            As of jQuery 1.5, the Deferred object provides a way to register multiple callbacks into self-managed callback queues, invoke callback queues as appropriate, and relay the success or failure state of any synchronous or asynchronous function.

            Promise Object

            -

            This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe. isResolved, and isRejected) to prevent users from changing the state of the Deferred. +

            This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred.

            Callbacks Object

            A multi-purpose object that provides a powerful way to manage callback lists. It supports adding, removing, firing, and disabling callbacks. The Callbacks object is created and returned by the $.Callbacks function and subsequently returned by most of that function's methods.

            +

            Document

            +

            A document object created by the browser's DOM parser, usually from a string representing HTML or XML.

            +

            XML Document

            +

            A document object created by the browser's XML DOM parser, usually from a string representing XML. XML documents have different semantics than HTML documents, but most of the traversing and manipulation methods provided by jQuery will work with them.

            +

            Assert

            +

            A reference to or instance of the object holding all of QUnit's assertions. See the API documentation for QUnit.assert for details.

            diff --git a/redirects.json b/redirects.json new file mode 100644 index 000000000..ba33f9ddd --- /dev/null +++ b/redirects.json @@ -0,0 +1,4 @@ +{ + "/api/": "/resources/api.xml", + "/extending-ajax/": "/jQuery.ajax/#extending-ajax" +} diff --git a/resources/0042_04_03.png b/resources/0042_04_03.png new file mode 100644 index 000000000..c6958fe88 Binary files /dev/null and b/resources/0042_04_03.png differ diff --git a/resources/events.js b/resources/events.js index e00efb363..9b01b7e6c 100644 --- a/resources/events.js +++ b/resources/events.js @@ -1,31 +1,31 @@ jQuery.print = function(message, insertionType) { - if (typeof(message) == 'object') { - var string = '{
            ', - values = [], - counter = 0; - $.each(message, function(key, value) { - if (value && value.nodeName) { - var domnode = '<' + value.nodeName.toLowerCase(); - domnode += value.className ? ' class="' + value.className + '"' : ''; - domnode += value.id ? ' id="' + value.id + '"' : ''; - domnode += '>'; - value = domnode; - } - values[counter++] = key + ': ' + value; - }); - string += values.join(',
            '); - string += '
            }'; - message = string; - } + if (typeof(message) == 'object') { + var string = '{
            ', + values = [], + counter = 0; + $.each(message, function(key, value) { + if (value && value.nodeName) { + var domnode = '<' + value.nodeName.toLowerCase(); + domnode += value.className ? ' class="' + value.className + '"' : ''; + domnode += value.id ? ' id="' + value.id + '"' : ''; + domnode += '>'; + value = domnode; + } + values[counter++] = key + ': ' + value; + }); + string += values.join(',
            '); + string += '
            }'; + message = string; + } - var $output = $('#print-output'); + var $output = $('#print-output'); - if ($output.length === 0) { - $output = $('