jQuery Tips Everyone Should Know
A collection of simple tips to help up your jQuery game.
[!TIP]
For other great lists check out @sindresorhus 's curated list of awesome lists .
Table of Contents
Tips
Use noConflict()
Checking If jQuery Loaded
Check Whether an Element Exists
Use .on() Binding Instead of .click()
Back to Top Button
Preload Images
Checking If Images Are Loaded
Fix Broken Images Automatically
Post a Form with AJAX
Toggle Classes on Hover
Disabling Input Fields
Stop the Loading of Links
Cache jQuery Selectors
Toggle Fade/Slide
Simple Accordion
Make Two Divs the Same Height
Open External Links in New Tab/Window
Find Element By Text
Trigger on Visibility Change
AJAX Call Error Handling
Chain Plugin Calls
Sort List Items Alphabetically
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:
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:
let $x = jQuery.noConflict();
back to table of contents
Checking If jQuery Loaded
Before you can do anything with jQuery you first need to make certain it has loaded:
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
Check Whether an Element Exists
Prior using a HTML element you need to ensure it's part of DOM.
if ($("#selector").length) {
//do something with element
}
back to 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...
.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:
.on('click.menuOpening')
Namespaces give you the power to unbind a specific event (e.g., .off('click.menuOpening')).
back to 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:
// Back to top
$(".container").on("click", ".back-to-top", function (e) {
e.preventDefault();
$("html, body").animate({ scrollTop: 0 }, 800);
});
<!-- Create an anchor tag -->
<div class="container">
<a href="#" class="back-to-top">Back to top</a>
</div>
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 with scrollTop.
back to 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:
$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$("<img>").attr("src", arguments[i]);
}
};
$.preloadImages("img/hover-on.png", "img/hover-off.png");
back to 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:
$("img").on("load", function () {
console.log("image load successful");
});
You can also check if one particular image has loaded by replacing the <img> tag with an ID or class.
jQuery Tips Everyone Should Know
A collection of simple tips to help up your jQuery game.
[!TIP]
For other great lists check out @sindresorhus 's curated list of awesome lists .
Table of Contents
Tips
Use noConflict()
Checking If jQuery Loaded
Check Whether an Element Exists
Use .on() Binding Instead of .click()
Back to Top Button
Preload Images
Checking If Images Are Loaded
Fix Broken Images Automatically
Post a Form with AJAX
Toggle Classes on Hover
Disabling Input Fields
Stop the Loading of Links
Cache jQuery Selectors
Toggle Fade/Slide
Simple Accordion
Make Two Divs the Same Height
Open External Links in New Tab/Window
Find Element By Text
Trigger on Visibility Change
AJAX Call Error Handling
Chain Plugin Calls
Sort List Items Alphabetically
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:
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:
let $x = jQuery.noConflict();
back to table of contents
Checking If jQuery Loaded
Before you can do anything with jQuery you first need to make certain it has loaded:
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
Check Whether an Element Exists
Prior using a HTML element you need to ensure it's part of DOM.
if ($("#selector").length) {
//do something with element
}
back to 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...
.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:
.on('click.menuOpening')
Namespaces give you the power to unbind a specific event (e.g., .off('click.menuOpening')).
back to 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:
// Back to top
$(".container").on("click", ".back-to-top", function (e) {
e.preventDefault();
$("html, body").animate({ scrollTop: 0 }, 800);
});
<!-- Create an anchor tag -->
<div class="container">
<a href="#" class="back-to-top">Back to top</a>
</div>
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 with scrollTop.
back to 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:
$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$("<img>").attr("src", arguments[i]);
}
};
$.preloadImages("img/hover-on.png", "img/hover-off.png");
back to 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:
$("img").on("load", function () {
console.log("image load successful");
});
You can also check if one particular image has loaded by replacing the <img> tag with an ID or class.