- Jquery-tips-everyone-should-know
- By AllThingsSmitty (Matt Smith)
- The Nuggets translation Project
- Translator: Yves X
- Sqrthree (square root of three)
- Status: Done
Here are some simple tips to help you get started with jQuery.
- Check whether jQuery is loaded
- Back to top button
- Preloading images
- Check whether the image is loaded
- Automatic repair of invalid pictures
- Hover to toggle class
- Disabling input fields
- Blocking link loading
- Cache jQuery selector
- Toggle fade/slide
- Simple accordion effect
- Make two divs equal in height
- Open external links in a new TAB/new window
- Find elements by text
- Triggered when the visibility property changes
- Ajax call error handling
- Chained plug-in calls
Check whether jQuery is loaded
Before you do anything with jQuery, you need to make sure it has been loaded:
if (typeof jQuery == 'undefined') {
console.log('jQuery hasn\'t loaded');
} else {
console.log('jQuery has loaded');
}Copy the code
Back to top button
Using jQuery’s animate and scrollTop methods, you can create simple scroll up effects without plug-ins:
// Return to the top
$('a.top').click(function (e) {
e.preventDefault();
$(document.body).animate({scrollTop: 0}, 800);
});Copy the code
<! -- Set anchor -->
<a class="top" href="#">Back to top</a>Copy the code
Adjust the value of scrollTop to change the rolling landing position. All you’re really doing is setting the position of the body of the document for 800 milliseconds until it scrolls to the top.
Preloading images
If your page uses a lot of images that are not immediately visible (such as images triggered by hovering over a mouse), it makes sense to preload these images:
$.preloadImages = function (a) {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src'.arguments[i]); }}; $.preloadImages('img/hover-on.png'.'img/hover-off.png');Copy the code
Check whether the image is loaded
In some cases, in order to continue executing the script, you need to check that the image is fully loaded:
$('img').load(function (a) {
console.log('image load successful');
});Copy the code
Also, by using an tag with an ID or class attribute, you can check that a particular image is loaded.
Automatic repair of invalid pictures
If you find broken image links on your site, replacing them one by one can be a chore. This simple code can greatly alleviate the pain:
$('img').on('error'.function (a) {
if(! $(this).hasClass('broken-image')) {$(this).prop('src'.'img/broken.png').addClass('broken-image'); }});Copy the code
Even if you don’t have any broken links yet, it doesn’t hurt to add this code.
Hover to toggle class
If you want to change the visual appearance of a clickable element when the user hovers over it, you can add a class to the element when it is hovered, and remove the class when the mouse is no longer hovering:
$('.btn').hover(function (a) {
$(this).addClass('hover');
}, function (a) {
$(this).removeClass('hover');
});Copy the code
If you’re looking for an even simpler approach, you can use the toggleClass method and just add the necessary CSS:
$('.btn').hover(function (a) {
$(this).toggleClass('hover');
});Copy the code
Note: Using CSS might be a faster solution in this case, but it’s still worth knowing a little bit about.
Disabling input fields
Sometimes, you may want to disable the submit button of a form or disable one of the input fields before the user completes certain actions (for example, checking the “I have read the rules” confirmation box). You can add the disabled attribute to your input field, and then you can enable it as needed:
$('input[type="submit"]').prop('disabled'.true);Copy the code
You simply run the prop method on the input field again, but this time change the value of disabled to false:
$('input[type="submit"]').prop('disabled'.false);Copy the code
Blocking link loading
Sometimes you don’t want to link to a specific page or reload the current page, but you want them to do something else, such as trigger another script. This requires doing something to prevent default actions:
$('a.no-link').click(function (e) {
e.preventDefault();
});Copy the code
Cache jQuery selector
Think about how many of the same selectors you have written over and over again in your project. Each $(‘.element’) must query the entire DOM once, regardless of whether it has ever done so. Instead, we run the selector only once and store the result in a variable:
var blocks = $('#blocks').find('li');Copy the code
Now you can use the blocks variable anywhere without having to query the DOM every time:
$('#hideBlocks').click(function (a) {
blocks.fadeOut();
});
$('#showBlocks').click(function (a) {
blocks.fadeIn();
});Copy the code
Caching jQuery selectors is a simple performance boost.
Toggle fade/slide
Fade-out and sliding are effects that we use a lot in jQuery. You might just want to show an element after the user clicks, and fadeIn and slideDown are perfect. But if you want this element to appear on the first click and disappear on the second click, this code is useful:
/ / out
$('.btn').click(function (a) {
$('.element').fadeToggle('slow');
});
/ / switch
$('.btn').click(function (a) {
$('.element').slideToggle('slow');
});Copy the code
Simple accordion effect
Here’s a quick and easy way to achieve an accordion effect:
// Close all panels
$('#accordion').find('.content').hide();
// Accordion effect
$('#accordion').find('.accordion-header').click(function (a) {
var next = $(this).next();
next.slideToggle('fast');
$('.content').not(next).slideUp('fast');
return false;
});Copy the code
By adding this script, all you really need to do is provide the necessary HTML elements for it to work.
Make two divs equal in height
Sometimes you want two divs to have the same height no matter what they contain:
$('.div').css('min-height', $('.main-div').height());Copy the code
This example sets min-height, which means the height can be greater than the main div but not less than it. However, a more flexible approach is to traverse a set of elements and then set the height to the height of the highest element:
var $columns = $('.column');
var height = 0;
$columns.each(function (a) {
if ($(this).height() > height) {
height = $(this).height(); }}); $columns.height(height);Copy the code
If you want all columns to be the same height:
var $rows = $('.same-height-columns');
$rows.each(function (a) {
$(this).find('.column').height($(this).height());
});Copy the code
Open external links in a new TAB/new window
Open external links in a new browser TAB or window and ensure that links from the same source are opened in the same TAB or window:
$('a[href^="http"]').attr('target'.'_blank');
$('a[href^="//"]').attr('target'.'_blank');
$('a[href^="' + window.location.origin + '"]).attr('target'.'_self');Copy the code
Note: Window.location. origin is not available in IE10. This fix focuses on that problem.
Find elements by text
You can find text in element content by using jQuery’s Contains () selector. If the text does not exist, the element will be hidden:
var search = $('#search').val();
$('div:not(:contains("' + search + '"))).hide();Copy the code
Triggered when the visibility property changes
Javasrcipt fires when the user’s focus leaves or returns to a TAB:
$(document).on('visibilitychange'.function (e) {
if (e.target.visibilityState === "visible") {
console.log('Tab is now in view! ');
} else if (e.target.visibilityState === "hidden") {
console.log('Tab is now hidden! '); }});Copy the code
Ajax call error handling
When an Ajax call returns a 404 or 500 error, the error handler is executed. If error handling is not defined, other jQuery code may no longer be valid. So define a global Ajax error handling:
$(document).ajaxError(function (e, xhr, settings, error) {
console.log(error);
});Copy the code
Chained plug-in calls
JQuery allows you to ease the process of repeatedly querying the DOM and creating multiple jQuery objects by invoking methods through “chained” plug-ins. For example, the following code represents your plug-in call:
$('#elem').show();
$('#elem').html('bla');
$('#elem').otherStuff();Copy the code
By using the chain operation, there is a significant improvement:
$('#elem')
.show()
.html('bla')
.otherStuff();Copy the code
Another way is to cache elements in variables prefixed with $:
var $elem = $('#elem');
$elem.hide();
$elem.html('bla');
$elem.otherStuff();Copy the code
Both chained operations and caching elements are best practices in jQuery to simplify and optimize code.