# 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 By using the `animate` and `scrollTop` methods in jQuery you don't need a plugin to create a simple scroll-to-top animation: ```javascript // Back to top $(".container").on("click", ".back-to-top", function (e) { e.preventDefault(); $("html, body").animate({ scrollTop: 0 }, 800); }); ``` ```html
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 If your web page uses a lot of images that aren't visible initially (e.g., on hover) it makes sense to preload them: ```javascript $.preloadImages = function () { for (var i = 0; i < arguments.length; i++) { $("").attr("src", arguments[i]); } }; $.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").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 () { 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(), }); ``` But all of those `val()` calls are expensive and using `.val()` on `