diff --git a/CODE-OF-CONDUCT.md b/CODE-OF-CONDUCT.md new file mode 100644 index 0000000..f45a2cf --- /dev/null +++ b/CODE-OF-CONDUCT.md @@ -0,0 +1,24 @@ +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project maintainer at mjsmithme@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/](http://contributor-covenant.org/version/1/3/0/). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b703561..09c3083 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,17 +1,38 @@ # Contribution Guidelines -Please ensure your pull requests adhere to the following guidelines: - -* Search open and closed PR's to avoid duplicate suggestions. -* Only submit jQuery tips that you think would be useful to others. This implies each tip has enough succinct content to describe why it's useful. -* Add your tip at the bottom of the [README](https://github.com/AllThingsSmitty/jquery-tips-everyone-should-know/blob/master/README.md) document. Add a link to your tip at the bottom of the table of contents. -* Use [title-casing](http://titlecapitalization.com). -* Code formatting should follow standard [JSLint](http://www.jslint.com/) default settings. -* PR's should include a .js snippet file added to the `js` folder. -* Snippet folders should be named identical to the tip being added in the [README](https://github.com/AllThingsSmitty/jquery-tips-everyone-should-know/blob/master/README.md) document using the following convention: `make-two-divs-the-same-height`. -* Snippets should begin with a comment that matches the name of the tip, e.g., `// Make two divs the same height`. -* Make sure your text editor is set to remove trailing whitespace. -* Check your spelling and grammar. -* The PR should have a useful title. - -Thank you for your suggestions! \ No newline at end of file +Please note that this project is released with a [Contributor Code of Conduct](CODE-OF-CONDUCT.md). By participating in this project you agree to abide by its terms. + +## Table of Contents + +- [Adding to This List](#adding-to-this-list) +- [Updating Your Pull Request](#updating-your-pull-request) + +## Adding to This List + +Please ensure your pull request adheres to the following guidelines: + +- Search open and closed PR's to avoid duplicate suggestions. +- Only submit jQuery tips that you think would be useful to others. This implies each tip has enough succinct content to describe why it's useful. +- Add your tip at the bottom of the [README](https://github.com/AllThingsSmitty/jquery-tips-everyone-should-know/blob/master/README.md) document. Add a link to your tip at the bottom of the table of contents. +- Use [title-casex](https://titlecaseconverter.com/). +- Code formatting should follow standard [JSLint](http://www.jslint.com/) default settings, including: + - Indent with two spaces + - Use single quotes, e.g., `$.preloadImages('img/hover-on.png');` +- Make sure your text editor is set to remove trailing whitespace. +- Check your spelling and grammar. +- The PR should have a useful title. + +Thank you for your suggestions! + +### Language Translations + +If you fluently speak another language and want to contribute by translating this list into that language, please submit a PR using the following guidelines: + +- Add a new folder to the [`translations`](https://github.com/AllThingsSmitty/jquery-tips-everyone-should-know/tree/master/translations) folder +- The new folder should be labeled the language culture name, e.g, `es-ES`, `ru-RU`, `zh-CN`, etc. + +Additionally, feel free to review already translated content for accuracy. + +## Updating Your Pull Request + +Sometimes a maintainer will ask you to edit your pull request before it's included. This is normally due to spelling errors or because your PR didn't match the above guidelines. [This write-up](https://github.com/RichardLitt/knowledge/blob/master/github/amending-a-commit-guide.md) covers the different ways you can change a pull request diff --git a/LICENSE b/LICENSE index 1bcc01b..3bbbc1e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,22 +1,116 @@ -The MIT License (MIT) +CC0 1.0 Universal -Copyright (c) 2015 Matt Smith +Statement of Purpose -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND 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. +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + \ No newline at end of file diff --git a/README.md b/README.md index 8d5c761..b8bd583 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,106 @@ -# jQuery Tips Everyone Should Know +# jQuery Tips Everyone Should Know [![Awesome](https://awesome.re/badge-flat.svg)](https://awesome.re) A collection of simple tips to help up your jQuery game. +> [!TIP] +> For other great lists check out [@sindresorhus](https://github.com/sindresorhus/)'s curated list of [awesome lists](https://github.com/sindresorhus/awesome/). + +## Table of Contents + +- [Tips](#tips) +- [Support](#support) +- [Translations](#translations) +- [Contribution Guidelines](CONTRIBUTING.md) + +## Tips + +1. [Use `noConflict()`](#use-noconflict) +1. [Checking If jQuery Loaded](#checking-if-jquery-loaded) +1. [Check Whether an Element Exists](#check-whether-an-element-exists) +1. [Use `.on()` Binding Instead of `.click()`](#use-on-binding-instead-of-click) 1. [Back to Top Button](#back-to-top-button) 1. [Preload Images](#preload-images) 1. [Checking If Images Are Loaded](#checking-if-images-are-loaded) 1. [Fix Broken Images Automatically](#fix-broken-images-automatically) +1. [Post a Form with AJAX](#post-a-form-with-ajax) 1. [Toggle Classes on Hover](#toggle-classes-on-hover) 1. [Disabling Input Fields](#disabling-input-fields) 1. [Stop the Loading of Links](#stop-the-loading-of-links) +1. [Cache jQuery Selectors](#cache-jquery-selectors) 1. [Toggle Fade/Slide](#toggle-fadeslide) 1. [Simple Accordion](#simple-accordion) 1. [Make Two Divs the Same Height](#make-two-divs-the-same-height) 1. [Open External Links in New Tab/Window](#open-external-links-in-new-tabwindow) 1. [Find Element By Text](#find-element-by-text) 1. [Trigger on Visibility Change](#trigger-on-visibility-change) +1. [AJAX Call Error Handling](#ajax-call-error-handling) +1. [Chain Plugin Calls](#chain-plugin-calls) +1. [Sort List Items Alphabetically](#sort-list-items-alphabetically) +1. [Disable Right-Click](#disable-right-click) + +### Use `noConflict()` + +The `$` alias used by jQuery is also used by other JavaScript libraries. To ensure that jQuery doesn't conflict with the `$` object of different libraries, use the `noConflict()` method at the start of the document: + +```javascript +jQuery.noConflict(); +``` + +Now you'll reference the jQuery object using the `jQuery` variable name instead of `$` (e.g., `jQuery('div p').hide()`). If you have multiple versions of jQuery on the same page (not recommended), you can use `noConflict()` to set an alias to a specific version: + +```javascript +let $x = jQuery.noConflict(); +``` + +[back to table of contents](#table-of-contents) + +### Checking If jQuery Loaded + +Before you can do anything with jQuery you first need to make certain it has loaded: + +```javascript +if (typeof jQuery == "undefined") { + console.log("jQuery hasn't loaded"); +} else { + console.log("jQuery has loaded"); +} +``` + +Now you're off... + +[back to table of contents](#table-of-contents) + +### Check Whether an Element Exists + +Prior using a HTML element you need to ensure it's part of DOM. + +```javascript +if ($("#selector").length) { + //do something with element +} +``` + +[back to table of contents](#table-of-contents) + +### Use `.on()` Binding Instead of `.click()` + +Using `.on()` gives you several advantages over using `.click()`, such as the ability to add multiple events... + +```javascript +.on('click tap hover') +``` +...a binding applies to dynamically created elements, as well (there's no need to manually bind every single element dynamically added to a DOM element)... + +...and the possibility to set a namespace: + +```javascript +.on('click.menuOpening') +``` + +Namespaces give you the power to unbind a specific event (e.g., `.off('click.menuOpening')`). + +[back to table of contents](#table-of-contents) ### Back to Top Button @@ -23,19 +108,25 @@ By using the `animate` and `scrollTop` methods in jQuery you don't need a plugin ```javascript // Back to top -$('a.top').click(function (e) { +$(".container").on("click", ".back-to-top", function (e) { e.preventDefault(); - $(document.body).animate({scrollTop: 0}, 800); + $("html, body").animate({ scrollTop: 0 }, 800); }); ``` ```html -Back to top +
+ Back to top +
``` Changing the `scrollTop` value changes where you wants the scrollbar to land. All you're really doing is animating the body of the document throughout the course of 800 milliseconds until it scrolls to the top of the document. +> [!NOTE] +> Watch for some [buggy behavior](https://github.com/jquery/api.jquery.com/issues/417) with `scrollTop`. + +[back to table of contents](#table-of-contents) ### Preload Images @@ -44,105 +135,169 @@ If your web page uses a lot of images that aren't visible initially (e.g., on ho ```javascript $.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { - $('').attr('src', arguments[i]); + $("").attr("src", arguments[i]); } }; -$.preloadImages('img/hover-on.png', 'img/hover-off.png'); +$.preloadImages("img/hover-on.png", "img/hover-off.png"); ``` +[back to table of contents](#table-of-contents) ### Checking If Images Are Loaded Sometimes you might need to check if your images have fully loaded in order to continue on with your scripts: ```javascript -$('img').load(function () { - console.log('image load successful'); +$("img").on("load", function () { + console.log("image load successful"); }); ``` You can also check if one particular image has loaded by replacing the `` tag with an ID or class. +[back to table of contents](#table-of-contents) ### Fix Broken Images Automatically If you happen to find broken image links on your site replacing them one by one can be a pain. This simple piece of code can save a lot of headaches: ```javascript -$('img').on('error', function () { - $(this).prop('src', 'img/broken.png'); +$("img").on("error", function () { + if (!$(this).hasClass("broken-image")) { + $(this).prop("src", "img/broken.png").addClass("broken-image"); + } +}); +``` + +Alternatively, if you wish to hide broken images this snippet will take care of that for: + +```javascript +$("img").on("error", function () { + $(this).hide(); +}); +``` + +[back to table of contents](#table-of-contents) + +### Post a Form with AJAX + +jQuery AJAX methods are a common way to request text, HTML, XML, or JSON. If you wanted to send a form via AJAX you could collect the user inputs via the `val()` method: + +```javascript +$.post("sign_up.php", { + user_name: $("input[name=user_name]").val(), + email: $("input[name=email]").val(), + password: $("input[name=password]").val(), }); ``` -Even if you don't have any broken links, adding this won't do any harm. +But all of those `val()` calls are expensive and using `.val()` on `