Home >Web Front-end >JS Tutorial >15 commonly used jquery code snippets_jquery

15 commonly used jquery code snippets_jquery

WBOY
WBOYOriginal
2016-05-16 15:24:361115browse

This article shares 15 commonly used jquery code snippets for your reference. The specific content is as follows

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

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

Change the value of scrollTop to where you want the scrollbar to stop. And then what you do is, set it to go back to the top in 800 milliseconds.

2. Preload images
If your page uses a lot of images that are not initially visible (e.g. bound to a hover), it is useful 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');

3. Check whether the image is loaded
Sometimes you may need to check whether the image is completely loaded before you can perform subsequent operations in the script:

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

You can also check whether a specific image has been loaded by replacing the img tag with an ID or class.

4. Repair damaged pictures
If you find that the image links on your website are broken, it is very troublesome to replace them one by one. This simple code can help a lot:

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

Even if you don’t have any broken links, adding this code will have no impact.

5. Class switching on Hover
If the user's mouse hovers over a clickable element on the page, you want to change the visual representation of that element. You can use the following code to add a class to the element when the user hovers it; remove the class when the user leaves the mouse:

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

You only need to add the necessary CSS. If you need a simpler way, 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’s still worth knowing.

6. Disable input field
Sometimes you may want to make a form's submit button or its text input box unavailable until the user performs a specific action (such as confirming the "I have read the terms" checkbox). Add disabled attribute to your input to achieve the effect you want:

Copy code The code is as follows:
$('input[type="submit"]').prop ('disabled', true);

When you want to change the value of disabled to false, just run the prop method on the input again.

Copy code The code is as follows:
$('input[type="submit"]').prop ('disabled', false);

7. Stop link loading
Sometimes you don't want a link to jump to a page or reload the page, but you want to be able to do something else, such as trigger other scripts. The following code is a little trick to disable the default behavior:
 $('a.no-link').click(function (e) {
 e.preventDefault();
 });

8. Fade/sliding switch
Fade in and fade out and slide are animation effects that we often use jQuery to create. Maybe you just want to reveal an element when the user clicks on something, using fadeIn and slideDown are both great. But if you want the element to appear on the first click and disappear on the second click, the following code can do the job well:

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

9. Simple accordion effect
Here's a quick and easy way to achieve an 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 see if the script works properly within the necessary HTML.

10. Make the two Divs the same height
Sometimes you might want two divs to have the same height, regardless of what content they contain:

Copy code The code is as follows:
('.div').css('min-height', $(' .main-div').height());

This example sets the min-height, meaning it can be larger than the main div, but never smaller. But a more flexible method is to iterate through the settings of a set of elements and 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 be the same height:

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

11、在新标签/窗口打开站外链接
在一个新标签或者新窗口中打开外置链接,并确保站内链接会在相同的标签或窗口中打开:

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

注意:window.location.origin 在 IE 10 中不可用,该 issue 的修复方法。

12、通过文本找到元素
通过使用 jQuery 中的 contains() 选择器,你可以找到某个元素中的文本。如果文本不存在,该元素将会隐藏:

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

13、视觉改变触发
当用户焦点在另外一个标签上,或重新回到标签时,触发 JavaScript:

 $(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 调用的错误处理
当某次 Ajax 调用返回 404 或 500 错误,就会执行错误处理。但如果没有定义该处理,其他 jQuery 代码或许会停止工作。可以通过下面这段代码定义一个全局 Ajax 错误处理:

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

15、插件链式调用
jQuery 支持链式调用插件,以减缓反复查询 DOM,并创建多个 jQuery 对象。看下面示例代码:

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

上面这段代码,可以通过链式操作大大改进:

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

还有另外一种方法,把元素缓存在变量中(前缀是  $ ):

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

jQuery 中的链式操作和缓存方法,都极大精简和提速了代码。
以上就是本文的全部内容,希望对大家的学习有所帮助。 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn