JQuery is a necessary javascript library for the most popular Web development today. This article collects 18 great jQuery code snippets, hoping they will be helpful to you.
1. jQuery implements smooth scrolling of internal links
No complicated plug-ins are required. you only need to download this code to implement smooth scrolling based on internal links.
$('a[href^="#"]').bind('click.smoothscroll',function (e) {e.preventDefault(); var anchor = this.hash,$target = $(target); $('html, body').stop().animate({'scrollTop': $target.offset().top}, 500, 'swing', function () {window.location.hash = anchor;}); });
2. use jQuery to retrieve all nodes
var $element = $('#gbtags'); var $nodes = $element.contents(); $nodes.each(function() { if(this.nodeType === 3 && $.trim($(this).text())) { $(this).wrap(''); }});
3. limit the number of selection boxes
$("#categories option").click(function(e){ if ($(this).parent().val().length < 2) { $(this).removeAttr("selected"); }});
4. jQuery uses wildcards to delete classes.
var _c = 'your-icon-class' $('.currency').removeClass (function (index, css) { return (css.match (/\bicon-\S+/g) || []).join(' ');}).addClass('icon-'+_c);
5. switch to enable and disable
/* HTML || * // Plugin (function ($) {$. fn. toggleDisabled = function () {return this. each (function () {var $ this = $ (this); if ($ this. attr ('disabled ') $ this. removeAttr ('disabled '); else $ this. attr ('disabled ', 'disabled') ;};}) (jQuery); // TEST $ (function () {$ ('input: click '). click (function () {$ ('input: text '). toggleDisabled ();});});
6. smooth scrolling back to the top
Admin).com returns the top $ (document ). ready (function () {$ (". topLink "). click (function () {$ ("html, body "). animate ({scrollTop: $ (this ). attr ("href ")). offset (). top + "px" },{ duration: 500, easing: "swing"}); return false ;});});
7. use jQuery and Google Analytics to track forms
var array1 = [];$(document).ready(function () { $('input').change(function () { var formbox = $(this).attr('id'); array1.push(formbox); console.log("you filled out box " + array1); }); $('#submit').click(function () { console.log('tracked ' + array1); //alert('this is the order of boxes you filled out: ' + array1); _gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']); });});
8. simple password strength prompt
$('#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;});
9. jQuery generates an automatic ending check.
// Window load event used just in case window height is dependant upon images$(window).bind("load", function () { var footerHeight = 0, footerTop = 0, $footer = $("#footer"); positionFooter(); function positionFooter() { footerHeight = $footer.height(); footerTop = ($(window).scrollTop() + $(window).height() - footerHeight) + "px"; /* DEBUGGINGconsole.log("Document height: ", $(document.body).height());console.log("Window height: ", $(window).height());console.log("Window scroll: ", $(window).scrollTop());console.log("Footer height: ", footerHeight);console.log("Footer top: ", footerTop);*/ if (($(document.body).height() + footerHeight) < $(window).height()) { $footer.css({ position: "absolute" }).stop().animate({ top: footerTop }); } else { $footer.css({ position: "static" }); } } $(window) .scroll(positionFooter) .resize(positionFooter);});
10. prevent multiple forms from being submitted
$(document).ready(function() { $('form').submit(function() { if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') { jQuery.data(this, "disabledOnSubmit", { submited: true }); $('input[type=submit], input[type=button]', this).each(function() { $(this).attr("disabled", "disabled"); }); return true; } else { return false; } });});
11. proportional scaling of images
$(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});
12. fade-in and fade-out when the mouse slides
$(document).ready(function(){ $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads $(".thumbs img").hover(function(){ $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover },function(){ $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout });});
13. create a high-level column
var max_height = 0;$("p.col").each(function(){ if ($(this).height() > max_height) { max_height = $(this).height(); }});$("p.col").height(max_height);
14. image pre-loading
(function($) { var cache = []; // Arguments are image paths relative to the current page. $.preLoadImages = function() { var args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } } jQuery.preLoadImages("image1.gif", "/path/to/image2.png");
15. get the parameters passed in the URL
$.urlParam = function(name){ var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); if (!results) { return 0; } return results[1] || 0;}
16. forbidden form enter submission
$("#form").keypress(function(e) { if (e.which == 13) { return false; }});
17. enable the entire DIV to be clicked
< a href = "http://www.jb51.net" > www.jb51.net < /a>
$(".myBox").click(function(){ window.location=$(this).find("a").attr("href"); return false;});
18. open the link in a new window (target = "blank ")
$('a[@rel$='external']').click(function(){ this.target = "_blank";});
You can combine the articles compiled in the previous section to summarize the practical jQuery code snippets for future use.