15 jQuery tips for front end development

  • 2021-07-13 04:09:09
  • OfStack

The following simple tips can help you play jQuery.

1. Return to the top button

Using the animate and scrollTop methods in jQuery, you can create a simple animation that scrolls to the top without a plug-in:


// Back to top
$('.top').click(function (e) {
e.preventDefault();
$('html, body').animate({scrollTop: 0}, 800);
});
<!-- Create an anchor tag -->
<a class="top" href="#">Back to top</a>

Changing the value of scrollTop can change the position where you want to place the scroll bar. All you really need to do is animate the body of the document in 800 milliseconds until it scrolls to the top of the document.

Note: Be careful of some errors in scrollTop.

2. Preload the image

If you want to use a large number of images that are initially invisible (for example, hovering), you can preload these images:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');

3. Check whether the image is loaded

Sometimes, in order to continue the script, you may need to check whether all the images are loaded:


$('img').load(function () {
console.log('image load successful');
});

You can also replace it with ID or class < img > Tag to check whether a particular image is loaded.

4. Automatically repair damaged images

Replacing broken image links one by one is very painful. However, the following simple code can help you:


$('img').on('error', function () {
if(!$(this).hasClass('broken-image')) {
$(this).prop('src', 'img/broken.png').addClass('broken-image');
}
});

Even if there are no broken links, adding this 1 piece of code will not make you lose anything.

5. Hover switching class

Suppose you want a clickable element to change color when the user hovers over it. Then you can add a class to the element when the user hovers, otherwise delete the class:


$('.btn').hover(function () {
$(this).addClass('hover');
}, function () {
$(this).removeClass('hover');
});

You just need to add the necessary CSS. A simpler approach is to use the toggleClass method:


$('.btn').hover(function () {
$(this).toggleClass('hover');
});

Note: CSS may be a faster solution in this case, but it is necessary to understand this method.

6. Disable input fields

Sometimes, you may want to disable the Submit button of the form or one of its text entries until the user performs a specific action (for example, check the "I have read the relevant terms" check box). Add the disabled attribute to your input to enable it when you want:

$('input[type="submit"]').prop('disabled', true);

Then you just need to run the input prop method, but the value of disabled should be set to false:

$('input[type="submit"]').prop('disabled', false);

7. Stop loading links

Sometimes you don't need to link to a particular page or reload the page-you might want the link to do something else, such as trigger some other script. It's time to make a fuss about blocking the default action:


$('a.no-link').click(function (e) {
e.preventDefault();
});

8. Fade-in/Slide Switch

Sliding and fading are things that we use a lot when animating with jQuery. fadeIn and slideDown methods are perfect if you just want to show one element after the user clicks. However, if you want the element to appear on the first click and then disappear on the second click, you can try the following code:


// Fade
$('.btn').click(function () {
$('.element').fadeToggle('slow');
});
// Toggle
$('.btn').click(function () {
$('.element').slideToggle('slow');
});

9. Simple accordion

This is a simple way to quickly generate accordions:


// Close all panels
$('#accordion').find('.content').hide();
// Accordion
$('#accordion').find('.accordion-header').click(function () {
var next = $(this).next();
next.slideToggle('fast');
$('.content').not(next).slideUp('fast');
return false;
});

By adding this script, all you really need to do is add the necessary HTML elements to the page so that it can work.

10. Let the two div have the same height

Sometimes, you need to make two div have the same height no matter what they contain:

$('.div').css('min-height', $('.main-div').height());

Set min-height, which means it can be larger than the main div but never smaller than the main div. 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 () {
if ($(this).height() > height) {
height = $(this).height();
}
});
$columns.height(height);

If you want all columns to have the same height:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
0

11. Open external links in new tabs/windows

Open external links in a new browser tab or window, and make sure that links from the same source can be opened in the same tab or window:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
1

Note: window. location. origin is not valid in IE10. Be careful about this problem when fixing it.

12. Find Elements by Text

By using the contains () selector in jQuery, you can find the text of the element content. If the text does not exist, hide the element:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
2

13. Triggered when Visibility is changed

JavaScript is triggered when the user stops focusing on an tab or refocuses on the original 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!');
}
});

14. AJAX Call Error Handling

When an Ajax call returns a 404 or 500 error, an error handler is executed. If no handler is defined, other jQuery codes may strike. Define a global Ajax error handler:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
4

15. Chain plug-in call

jQuery allows "chained" method calls for plug-ins to ease the process of repeatedly querying DOM and creating multiple jQuery objects. For example, the following code snippet represents your plug-in method call:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
5

By using chains, you can greatly improve:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
6

Another method is to cache elements in (prefix $) variables:


$.preloadImages = function () {
for (var i = 0; i < arguments.length; i++) {
$('<img>').attr('src', arguments[i]);
}
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');
7

Both the chaining and caching approaches are best practices in jQuery to make code shorter and faster.


Related articles: