JQuery tips that front-end programmers should know

Source: Internet
Author: User
By using the animate and scrollTop methods in jQuery, you can create a simple animation to scroll to the top without using plug-ins:

By using the animate and scrollTop methods in jQuery, you can create a simple animation to scroll to the top without using plug-ins:

// Back to top$('.top').click(function (e) {  e.preventDefault();  $('html, body').animate({scrollTop: 0}, 800);});
 Back to top

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

Note: Be careful with some incorrect behaviors of scrollTop.

Preload Images

If your webpage needs to use a large number of starting invisible (for example, hovering) images, You can pre-load these images:

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

Check whether the image is loaded

Sometimes, to continue the script, you may need to check whether all the images have been loaded:

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

You can also use ID or class replacement labels to check whether a specific image is loaded.

Automatic repair of damaged Images

Replacing damaged 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 is no broken link, adding this code will not cause you any loss.

Hover switch class

Suppose you want to change the color when you hover your mouse over the clickable element. You can add the class to the element when the user hovers over, and delete the class vice versa:

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

You only need to add necessary CSS. The simpler method is to use the toggleClass method:

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

Note: In this case, CSS is faster, but it is necessary to understand this method.

Disable input fields

Sometimes, you may want to disable the submit button of a table or a text input of the table until the user performs a specific operation (for example, check the "I have read related terms" check box ). After you add the disabled attribute to your input, you can enable it only when you want it:

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

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

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

Stop link Loading

Sometimes, you do not need to link to a specific webpage or re-load the webpage-you may want the link to do something else, for example, to trigger some other scripts. This requires an article on blocking default actions:

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

Fade-in/slide Switching

Slide and fade-In are a lot of things we use when using jQuery for animation. If you only want to display an element after a user clicks, The fadeIn and slideDown methods are perfect. However, if you want the element to appear at the first click and then disappear at the second click, you can try the following code:

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

Simple accordion

This is a simple way to quickly generate an accordion:

// 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, you only need to add the necessary HTML elements on the page so that it can run the work.

Make two p Heights the same

Sometimes, you need to make the two p have the same height regardless of what it contains:

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

Set min-height, which means it can be larger than the Master p but cannot be smaller than the Master p. However, there is also a more flexible way to traverse a group of elements and then set the height of the element to the highest:

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:

var $rows = $('.same-height-columns');$rows.each(function () {  $(this).find('.column').height($(this).height());});

Open external link in new tab/window

Open an external link in a new browser tab or window and make sure that the link from the same source can be 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');

Note: window. location. origin is invalid in IE10. Be careful when fixing the problem.

Triggered when Visibility is changed

When the user no longer pays attention to a tab, or re-focuses the original tab, the JavaScript is triggered:

$(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!');  }});

AJAX call error handling

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

$(document).ajaxError(function (e, xhr, settings, error) {  console.log(error);});

Chained plug-in call

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

$('#elem').show();$('#elem').html('bla');$('#elem').otherStuff();

By using the chain, you can greatly improve:

$('#elem')  .show()  .html('bla')  .otherStuff();

Another way is to cache elements in the (prefix $) variable:

var $elem = $('#elem');$elem.hide();$elem.html('bla');$elem.otherStuff();

The chained and high-speed cache methods are best practices for code generation that can be made shorter and faster in jQuery.

JQuery Tips Everyone shoshould Know

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.