├── CODE-OF-CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md └── translations ├── bg-BG └── README.md ├── es-ES └── README.md ├── fr-FR └── README.md ├── hu-HU └── README.md ├── ko-KR └── README.md ├── pt-PT └── README.md ├── ru-RU └── README.md ├── zh-CN └── README.md └── zh-TW └── README.md /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | 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. 4 | 5 | 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. 6 | 7 | Examples of unacceptable behavior by participants include: 8 | 9 | * The use of sexualized language or imagery 10 | * Personal attacks 11 | * Trolling or insulting/derogatory comments 12 | * Public or private harassment 13 | * Publishing other's private information, such as physical or electronic addresses, without explicit permission 14 | * Other unethical or unprofessional conduct 15 | 16 | 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. 17 | 18 | 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. 19 | 20 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 21 | 22 | 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. 23 | 24 | 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/). 25 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | 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. 4 | 5 | ## Table of Contents 6 | 7 | - [Adding to This List](#adding-to-this-list) 8 | - [Updating Your Pull Request](#updating-your-pull-request) 9 | 10 | ## Adding to This List 11 | 12 | Please ensure your pull request adheres to the following guidelines: 13 | 14 | - Search open and closed PR's to avoid duplicate suggestions. 15 | - 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. 16 | - 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. 17 | - Use [title-casex](https://titlecaseconverter.com/). 18 | - Code formatting should follow standard [JSLint](http://www.jslint.com/) default settings, including: 19 | - Indent with two spaces 20 | - Use single quotes, e.g., `$.preloadImages('img/hover-on.png');` 21 | - Make sure your text editor is set to remove trailing whitespace. 22 | - Check your spelling and grammar. 23 | - The PR should have a useful title. 24 | 25 | Thank you for your suggestions! 26 | 27 | ### Language Translations 28 | 29 | 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: 30 | 31 | - Add a new folder to the [`translations`](https://github.com/AllThingsSmitty/jquery-tips-everyone-should-know/tree/master/translations) folder 32 | - The new folder should be labeled the language culture name, e.g, `es-ES`, `ru-RU`, `zh-CN`, etc. 33 | 34 | Additionally, feel free to review already translated content for accuracy. 35 | 36 | ## Updating Your Pull Request 37 | 38 | 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 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jQuery Tips Everyone Should Know [![Awesome](https://awesome.re/badge-flat.svg)](https://awesome.re) 2 | 3 | A collection of simple tips to help up your jQuery game. 4 | 5 | > [!TIP] 6 | > For other great lists check out [@sindresorhus](https://github.com/sindresorhus/)'s curated list of [awesome lists](https://github.com/sindresorhus/awesome/). 7 | 8 | ## Table of Contents 9 | 10 | - [Tips](#tips) 11 | - [Support](#support) 12 | - [Translations](#translations) 13 | - [Contribution Guidelines](CONTRIBUTING.md) 14 | 15 | ## Tips 16 | 17 | 1. [Use `noConflict()`](#use-noconflict) 18 | 1. [Checking If jQuery Loaded](#checking-if-jquery-loaded) 19 | 1. [Check Whether an Element Exists](#check-whether-an-element-exists) 20 | 1. [Use `.on()` Binding Instead of `.click()`](#use-on-binding-instead-of-click) 21 | 1. [Back to Top Button](#back-to-top-button) 22 | 1. [Preload Images](#preload-images) 23 | 1. [Checking If Images Are Loaded](#checking-if-images-are-loaded) 24 | 1. [Fix Broken Images Automatically](#fix-broken-images-automatically) 25 | 1. [Post a Form with AJAX](#post-a-form-with-ajax) 26 | 1. [Toggle Classes on Hover](#toggle-classes-on-hover) 27 | 1. [Disabling Input Fields](#disabling-input-fields) 28 | 1. [Stop the Loading of Links](#stop-the-loading-of-links) 29 | 1. [Cache jQuery Selectors](#cache-jquery-selectors) 30 | 1. [Toggle Fade/Slide](#toggle-fadeslide) 31 | 1. [Simple Accordion](#simple-accordion) 32 | 1. [Make Two Divs the Same Height](#make-two-divs-the-same-height) 33 | 1. [Open External Links in New Tab/Window](#open-external-links-in-new-tabwindow) 34 | 1. [Find Element By Text](#find-element-by-text) 35 | 1. [Trigger on Visibility Change](#trigger-on-visibility-change) 36 | 1. [AJAX Call Error Handling](#ajax-call-error-handling) 37 | 1. [Chain Plugin Calls](#chain-plugin-calls) 38 | 1. [Sort List Items Alphabetically](#sort-list-items-alphabetically) 39 | 1. [Disable Right-Click](#disable-right-click) 40 | 41 | ### Use `noConflict()` 42 | 43 | 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: 44 | 45 | ```javascript 46 | jQuery.noConflict(); 47 | ``` 48 | 49 | 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: 50 | 51 | ```javascript 52 | let $x = jQuery.noConflict(); 53 | ``` 54 | 55 | [back to table of contents](#table-of-contents) 56 | 57 | ### Checking If jQuery Loaded 58 | 59 | Before you can do anything with jQuery you first need to make certain it has loaded: 60 | 61 | ```javascript 62 | if (typeof jQuery == "undefined") { 63 | console.log("jQuery hasn't loaded"); 64 | } else { 65 | console.log("jQuery has loaded"); 66 | } 67 | ``` 68 | 69 | Now you're off... 70 | 71 | [back to table of contents](#table-of-contents) 72 | 73 | ### Check Whether an Element Exists 74 | 75 | Prior using a HTML element you need to ensure it's part of DOM. 76 | 77 | ```javascript 78 | if ($("#selector").length) { 79 | //do something with element 80 | } 81 | ``` 82 | 83 | [back to table of contents](#table-of-contents) 84 | 85 | ### Use `.on()` Binding Instead of `.click()` 86 | 87 | Using `.on()` gives you several advantages over using `.click()`, such as the ability to add multiple events... 88 | 89 | ```javascript 90 | .on('click tap hover') 91 | ``` 92 | 93 | ...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)... 94 | 95 | ...and the possibility to set a namespace: 96 | 97 | ```javascript 98 | .on('click.menuOpening') 99 | ``` 100 | 101 | Namespaces give you the power to unbind a specific event (e.g., `.off('click.menuOpening')`). 102 | 103 | [back to table of contents](#table-of-contents) 104 | 105 | ### Back to Top Button 106 | 107 | By using the `animate` and `scrollTop` methods in jQuery you don't need a plugin to create a simple scroll-to-top animation: 108 | 109 | ```javascript 110 | // Back to top 111 | $(".container").on("click", ".back-to-top", function (e) { 112 | e.preventDefault(); 113 | $("html, body").animate({ scrollTop: 0 }, 800); 114 | }); 115 | ``` 116 | 117 | ```html 118 | 119 |
120 | Back to top 121 |
122 | ``` 123 | 124 | 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. 125 | 126 | > [!NOTE] 127 | > Watch for some [buggy behavior](https://github.com/jquery/api.jquery.com/issues/417) with `scrollTop`. 128 | 129 | [back to table of contents](#table-of-contents) 130 | 131 | ### Preload Images 132 | 133 | If your web page uses a lot of images that aren't visible initially (e.g., on hover) it makes sense to preload them: 134 | 135 | ```javascript 136 | $.preloadImages = function () { 137 | for (var i = 0; i < arguments.length; i++) { 138 | $("").attr("src", arguments[i]); 139 | } 140 | }; 141 | 142 | $.preloadImages("img/hover-on.png", "img/hover-off.png"); 143 | ``` 144 | 145 | [back to table of contents](#table-of-contents) 146 | 147 | ### Checking If Images Are Loaded 148 | 149 | Sometimes you might need to check if your images have fully loaded in order to continue on with your scripts: 150 | 151 | ```javascript 152 | $("img").on("load", function () { 153 | console.log("image load successful"); 154 | }); 155 | ``` 156 | 157 | You can also check if one particular image has loaded by replacing the `` tag with an ID or class. 158 | 159 | [back to table of contents](#table-of-contents) 160 | 161 | ### Fix Broken Images Automatically 162 | 163 | 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: 164 | 165 | ```javascript 166 | $("img").on("error", function () { 167 | if (!$(this).hasClass("broken-image")) { 168 | $(this).prop("src", "img/broken.png").addClass("broken-image"); 169 | } 170 | }); 171 | ``` 172 | 173 | Alternatively, if you wish to hide broken images this snippet will take care of that for: 174 | 175 | ```javascript 176 | $("img").on("error", function () { 177 | $(this).hide(); 178 | }); 179 | ``` 180 | 181 | [back to table of contents](#table-of-contents) 182 | 183 | ### Post a Form with AJAX 184 | 185 | 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: 186 | 187 | ```javascript 188 | $.post("sign_up.php", { 189 | user_name: $("input[name=user_name]").val(), 190 | email: $("input[name=email]").val(), 191 | password: $("input[name=password]").val(), 192 | }); 193 | ``` 194 | 195 | But all of those `val()` calls are expensive and using `.val()` on `