源地址:http://www.catswhocode.com/blog/10-handy-and-reusable-jquery-code-snippets

Smooth scrolling to top of page

Let’s start this list by a very popular and useful snippet: Those 4 lines will allow your visitors to smooth scrool to the top of the page simply by clicking a a link (with #top id) located at the bottom of your page.

$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});

Source: http://stackoverflow.com/questions/1144805/how-do-i-scroll…

Clone table header to the bottom of table

For a better readability of your tables, it can be a good idea to clone the table header on the bottom of the table. This is what this useful snippet do.

var $tfoot = $('<tfoot></tfoot>');
$($('thead').clone(true, true).children().get().reverse()).each(function(){
$tfoot.append($(this));
});
$tfoot.insertAfter('table thead');

Source: http://lunart.com.ua/jquery

Load external content

Do you need to add some external content to a div? It is pretty easy to do with jQuery, as demonstrated in the example below:

$("#content").load("somefile.html", function(response, status, xhr) {
// error handling
if(status == "error") {
$("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
}
});

Source: http://api.jquery.com/load/

Equal height columns

When you’re using columns to display content on your site, it definitely look better if the columns have an equal height. The code below will take all div elements with the .col class and will adjust their heights according to the bigger element. Super useful!

var maxheight = 0;
$("div.col").each(function(){
if($(this).height() > maxheight) { maxheight = $(this).height(); }
}); $("div.col").height(maxheight);

Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Table Stripes (Zebra)

When displaying data on a table, alternating colors on each row definitely increases readability. Here’s a snippet to automatically add a CSS class to one row of out two.

$(document).ready(function(){
$("table tr:even").addClass('stripe');
});

Source: http://www.alovefordesign.com/5-jquery-must-have-code-snippets/

Partial page refresh

If you need to refresh only a portion of a page, the 3 lines of code below will definitely help. In this example, a#refresh div is automatically refreshed every 10 seconds.

setInterval(function() {
$("#refresh").load(location.href+" #refresh>*","");
}, 10000); // milliseconds to wait

Source: http://web.enavu.com/tutorials/top-10-jquery-snippets-including-jquery-1-4/

Preload images

jQuery make it easy to preload images in the background so visitors won’t have to wait forever when they would like to display an image. This code is ready to use, just update the image list on line 8.

$.preloadImages = function() {
for(var i = 0; i<arguments.length; i++) {
$("<img />").attr("src", arguments[i]);
}
} $(document).ready(function() {
$.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});

Source: http://css-tricks.com/snippets/jquery/image-preloader/

Open external links in a new tab/window

The target="blank" attribute allows you to force opening of links in new windows. While it is relevant to open external links in a new tab or window, same domain links should definitely be opened in the same window.

This code detect if a link is external, and if yes, adds a target="blank" attribute to it.

$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});

Source: http://css-tricks.com/snippets/jquery/open-external-links-in-new-window/

Div full Width/Height of viewport with jQuery

This handy piece of code allows you to create a full width/height div according to the viewport. The code also handles window resizing. Great for modal dialogs or popups.

// global vars
var winWidth = $(window).width();
var winHeight = $(window).height(); // set initial div height / width
$('div').css({
'width': winWidth,
'height': winHeight,
}); // make sure div stays full width/height on resize
$(window).resize(function(){
$('div').css({
'width': winWidth,
'height': winHeight,
});
});

Source: http://www.jqueryrain.com/2013/03/div-full-widthheight-of-viewport-with-jquery/

Test password strength

When you let users defining their password, it is generally a good thing to indicate how strong the password is. This is exactly what this code do.

First, assume this HTML:

<input type="password" name="pass" id="pass" />
<span id="passstrength"></span>

And here is the corresponding jQuery code. The entered password will be evaluated using regular expressions and a message will be returned to the user to let him know if his chosen password is strong, medium, weak, or too short.

$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');
} else {
$('#passstrength').className = 'error';
$('#passstrength').html('Weak!');
}
return true;
});

Source: http://css-tricks.com/snippets/jquery/password-strength/

Image resizing using jQuery

Although you should resize your images on server side (using PHP and GD for example) it can be useful to be able to resize images using jQuery. Here’s a snippet to do it.

$(window).bind("load", function() {
// IMAGE RESIZE
$('#product_cat_list img').each(function() {
var maxWidth = 120;
var maxHeight = 120;
var ratio = 0;
var width = $(this).width();
var height = $(this).height(); if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
//$("#contentpage img").show();
// IMAGE RESIZE
});

Source: http://snipplr.com/view/62552/mage-resize/

Automatically load content on scroll

Some websites such as Twitter loads content on scroll. Which means that all content is dynamically loaded on a single page as long as you scroll down.

Here’s how you can replicate this effect on your website:

var loading = false;
$(window).scroll(function(){
if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
if(loading == false){
loading = true;
$('#loadingbar').css("display","block");
$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
$('body').append(loaded);
$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
$('#loadingbar').css("display","none");
loading = false;
});
}
}
}); $(document).ready(function() {
$('#loaded_max').val(50);
});

Source: http://fatfolderdesign.com/173/content-load-on-scroll-with-jquery

Check if an image is loaded

Here’s a snippet I often use when working with images, as it is the best way to know if an image is loaded or not.

var imgsrc = 'img/image1.png';
$('<img/>').load(function () {
alert('image loaded');
}).error(function () {
alert('error loading image');
}).attr('src', imgsrc);

Source: http://tympanus.net/codrops/2010/01/05/some-useful…

Sort a list alphabetically

On some cases, it can be very useful a sort a long list by alphabetical order. This snippet take any list and order its element alphabetically.

$(function() {
$.fn.sortList = function() {
var mylist = $(this);
var listitems = $('li', mylist).get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : 1;
});
$.each(listitems, function(i, itm) {
mylist.append(itm);
});
} $("ul#demoOne").sortList(); });

Source: http://stackoverflow.com/questions/13394796/javascript-jquery-to-sort…

转载:10+ handy and reusable jQuery code snippets的更多相关文章

  1. 10个漂亮的jQuery日历插件下载【转载】

    10个漂亮的jQuery日历插件下载 2013-08-07 标签:jQuery日历插件jQuery日历jQuery插件   日期是非常重要的,随时随地.微薄或网站的日期选取器日历必须在那里.您可以使用 ...

  2. Problem and Solution Code Snippets

    (积累知识,遇到发展,本文仅用于备忘录,不时它需要召回准备) Problem: 依据String的大小来调整Label的frame.在view中又一次更新views的layout并显示. Soluti ...

  3. 10 个免费的 jQuery 可视化编辑器插件

    富文本编辑器,也就是所见即所得的 HTML 编辑器,是网站一个非常重要的组件,特别是对于一些内容发布网站来说.本文介绍 10 个基于 jQuery 的可视化文本编辑器. MarkitUp markIt ...

  4. 10+优秀“分步引导”jQuery插件(转)

    很 多时候一个网站或者一个Web应用出品,为了让你的用户知道你的站点(或应用)有些什么?如何操作?为了让你的用户有更好的体验.往往这个时候都会给你的 站点(应用)添加一个分步指引的效果.然而这样的效果 ...

  5. (2)入门指南——(7)添加jquery代码(Adding our jQuery code)

    Our custom code will go in the second, currently empty, JavaScript file which we included from the H ...

  6. 10 Tips for Writing Better Code (阅读理解)

    出发点 http://www.tuicool.com/articles/A7VrE33 阅读中文版本<编写质优代码的十个技巧>,对于我编码十年的经验,也有相同感受, 太多的坑趟过,太多的经 ...

  7. 转载 +function ($) { "use strict";}(window.jQuery);全面分析

    转载 https://www.cnblogs.com/cndotabestdota/p/5664112.html +function ($) { "use strict";}(wi ...

  8. 绝对震撼 10个实用的jQuery/HTML5插件

    在HTML5的世界里,我们见证了无数的特效奇迹,但很多特效我们很难在网页中应用,今天我们要分享10款效果震撼但是又比较实用的jQuery/HTML5插件,希望这些项目在应用的过程中也能给你带来设计灵感 ...

  9. iOS开发-代码片段(Code Snippets)提高开发效率

    简介 在 XCode4 引入了一个新特性,那就是“代码片段(Code Snippets)”.对于一些经常用到的代码,抽象成模板放到 Code Snippets 中,使用的时候就只需要键入快捷键就可以了 ...

随机推荐

  1. 随机深林和GBDT

    随机森林(Random Forest): 随机森林是一个最近比较火的算法,它有很多的优点: 在数据集上表现良好 在当前的很多数据集上,相对其他算法有着很大的优势 它能够处理很高维度(feature很多 ...

  2. Mysql Having的用法:对group by之后的分组加限制条件(复制)

    在使用聚合函数之前,我们可以通过where对查询加限制条件,那么如果在group by之后我们要对分组里面的数据再加限制条件怎么办呢?答案是having. HAVING子句可以让我们筛选成组后的各组数 ...

  3. ruby中的self

    self,自己,在ruby中表示当前对象或默认对象.程序执行的任一时刻,有且仅有一个self. 1.谁成为self,在什么位置成为self? 要知道哪个对象是self,就必须知道当前的上下文.上下文主 ...

  4. ROS学习

    随着机器人领域的快速发展和复杂化,代码的复用性和模块化的需求原来越强烈,而已有的开源机器人系统又不能很好的适应需求.2010年Willow Garage公司发布了开源机器人操作系统ROS(robot ...

  5. Linux Swap交换分区介绍

    Swap分区在系统的物理内存不够用的时候,把物理内存中的一部分空间释放出来,以供当前运行的程序使用.那些被释放的空间可能来自一些很长时间没有什么操作的程序,这些被释放的空间被临时保存到Swap分区中, ...

  6. Python面试题之Python生成器

    首先说明一下生成器也是迭代器,也有迭代器的那些优点. 那为什么要生成器呢?因为到目前为止都 不是你写的迭代器,都是别人定义好的.那如何自己去造一个迭代器呢?下面的内容就会给你答案. 想要自己造一个迭代 ...

  7. CSS Float(浮动)

    CSS Float(浮动) 一.CSS Float(浮动) CSS 的 Float(浮动),会使元素向左或向右移动,其周围的元素也会重新排列. Float(浮动),往往是用于图像,但它在布局时一样非常 ...

  8. linux go with vscode

    1 install go apt install golang 将会同时安装下列软件:  golang-1.9 golang-1.9-doc golang-1.9-go golang-1.9-src ...

  9. java并发容器之 SynchronousQueue [转]

    SynchronousQueue 这个队列实现了 BlockingQueue接口 该队列的特点 1.容量为0,无论何时 size方法总是返回0 2. put操作阻塞,jquery插件库  直到另外一个 ...

  10. 分布式文档存储数据库(MongoDB)副本集配置

    副本集特征: N 个节点的集群 任何节点可作为主节点 所有写入操作都在主节点上 自动故障转移 自动恢复 相关文章: http://www.cnblogs.com/huangxincheng/archi ...