15 common jquery code snippets _ jquery-js tutorials

Source: Internet
Author: User
This article mainly introduces 15 commonly used jquery code snippets, which are helpful for you to learn about jquery programming, for more information about jquery, see the following section.

1. Return to the top button
By using the animate and scrollTop methods in jQuery, you can create a simple back-to-top animation without using plug-ins:

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

 
  Back to top

Change the value of scrollTop to where you want the scrollbar to stop. What you need to do is set to return to the top within 800 milliseconds.

2. Pre-load images
If your page uses a large number of images that cannot be initially visible (for example, bound to a hover), it is very useful to pre-load them:

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

3. Check whether the image has been loaded.
Sometimes you may need to check whether the image is fully loaded before performing subsequent operations in the script:

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

You can also replace the img label with the ID or class to check whether the image is loaded.

4. repair damaged Images
If you find that the image link on your website is down, it is very troublesome to replace the link one by one. This simple code can help you a lot:

 $('img').on('error', function () { $(this).prop('src', 'img/broken.png'); });

Even if you do not have any corrupted links, adding this code will not affect you.

5. Class switching on Hover
If you hover your mouse over a clickable element on the page, you want to change the visual performance of the element. You can use the following code to add a class to the element when the user hovers. When the user moves away, the class is removed:

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

You only need to add the necessary CSS. If you need a simpler method, you can also use the toggleClass method:

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

Note:CSS may be a faster solution for this example, but it is worth knowing.

6. Disable the input field
Sometimes you may want to make the form's submit button or text input box unavailable until the user executes a specific behavior (for example, confirm the check box for "I have read the terms ). Add the disabled attribute to your input to achieve the desired effect:

The Code is as follows:

$ ('Input [type = "submit"] '). prop ('Disabled', true );


To change the value of disabled to false, you only need to run the prop method again on the input.

The Code is as follows:

$ ('Input [type = "submit"] '). prop ('Disabled', false );


7. Stop link Loading
Sometimes you do not want to link to a page or reload the page, but want to do other things, such as triggering other scripts. The following code is a trick to disable default behavior:

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

8. Fade-in and fade-out/slide Switch
Fade-in and fade-out and slide are animation effects we often use jQuery. Maybe you just want to show an element when a user clicks something. Both fadeIn and slideDown are great. But if you want this element to appear when you click it for the first time and disappear when you click it for the second time, the following code can do a good job:

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

9. Simple accordion Effect
This is a simple method to quickly implement the accordion effect:

 // 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; });

After adding this script, all you need to do is to check whether the script works properly in the required HTML.

10. Make the two Div Heights the same
Sometimes you may want two p to have the same height, no matter what they contain:

The Code is as follows:

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


In this example, min-height is set, which means it can be larger than the primary p, but never smaller. However, there is a more flexible way to traverse the settings of a group of elements, and then set the height to the highest value in the 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:

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

11. Open the out-of-site link in the new tag/window
Open an external link in a new tag or window and make sure that the site link is opened in the same tag 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 unavailable in IE 10. This issue fix method.

12. Find elements through text
By using the contains () selector in jQuery, you can find the text in an element. If the text does not exist, the element is hidden:

 var search = $('#search').val(); $('p:not(:contains("' + search + '"))').hide();

13. Visual change triggering
When the user focuses on another tag or returns to the tag, 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!'); } }); 

14. Ajax call error handling
When an Ajax call returns a 404 or 500 error, it will handle the error. However, if this process is not defined, other jQuery code may stop working. You can use the following code to define a global Ajax error handling:

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

15. Plug-in chain call
JQuery supports chained calling plug-ins to slow down repeated DOM queries and create multiple jQuery objects. See the following sample code:

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

The above code can be greatly improved through chained operations:

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

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

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

The chain operations and cache methods in jQuery greatly simplify and speed up code.
The above is all the content of this article, hoping to help you learn.

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.