12 ultra-practical JQuery code snippets and 12jquery code snippets
1. navigation menu background switch Effect
On the front-end page of the project, different backgrounds must be set for the activated navigation menu compared to other navigation menus. There are many ways to implement this effect. The following is a method implemented using JQuery:
<Ul id = 'nav'> <li> Navigation 1 </li> <li> navigation 2 </li> <li> navigation 3 </li> </ul>/ /Note: code needs to be improved $ ('# nav '). click (function (e) {// the usage of siblings(e.tar get ). addClass ('tclass '). siblings ('. tclass '). removeClass ('tclass ');;});
2. Access elements in JQuery objects in reverse order
In some scenarios, we may need to access the page element object obtained through the JQuery selector in reverse order. How can this be achieved? See the following code:
// To master the get method of the JQuery object and the reverse method of the array, You Can var arr =$ ('# nav '). find ('lil '). get (). reverse (); $. each (arr, function (index, ele ){.......});
3. Access elements in IFrame
In most cases, IFrame is not a good solution, but for various reasons, IFrame is indeed used in the project, so you need to know how to access the elements in IFrame.
Var iFrameDOM = $ ("iframe # someID "). contents (); // then, you can use the find method to traverse and obtain the iFrameDOM element in iFrame. find (". message "). slideUp ();
4. Manage the search box values
Currently, all major websites have a search box, and the search box usually has a default value. When the input box gets the focus, the default value disappears. Once the input box loses focus, and no new value is entered in the input box, the value in the input box is restored to the default value. If a new value is entered in the input box, the value in the input box is the new value. This special effect is easily implemented using JQuery:
$ ("# Searchbox "). focus (function () {$ (this ). val ('')}). blur (function () {var $ this = $ (this); // search... 'is the default value of the search box ($ this. val () = '')? $ This. val ('search... '): null ;});
5. load updates on some pages
To improve the web performance, we usually do not load the entire page when there is an update, but only update part of the page content and delay loading of parts. The special effects of page refreshing are also easy to implement in JQuery:
SetInterval (function () {// refresh the page content every five seconds // The retrieved content will be added to the element with the id of content $ ("# content "). load (url);}, 5000 );
6. Use the data method to cache data
In a project, to avoid repeated requests to the server, the obtained data is usually cached for later use. JQuery allows you to implement this function elegantly:
Var cache ={}; $. data (cache, 'key', 'value'); // cache data // get data $. data (cache, 'key ');
7. Compatibility Between JQuery and other libraries
If JQuery is used in a project, $ is the most common variable name, But JQuery is not the only library that uses $ as the variable name. To avoid name conflicts, you can organize your Code as follows:
// Method 1: Rename JQuery as $ jvar $ j = jQuery. noConflict (); $ j ('# id ').... // Method 2: Recommended function ($) {$ (document ). ready (function () {// here, you can use JQuery syntax normally}) ;}( jQuery );
8. Clone the table header to the bottom of the table.
To make the table more readable, we can clone the header information of the table to the bottom of the table. This special effect is easily achieved through JQuery:
var $tfoot = $('<tfoot></tfoot>'); $($('thead').clone(true, true).children().get().reverse()).each(function(){ $tfoot.append($(this));});$tfoot.insertAfter('table thead');
9. Create a div with full screen width and height (width/height) based on the window (viewport)
The following code allows you to create a full-screen div Based on viewport. This is effective when the modal or dialog box is displayed in different window sizes:
$('#content').css({ 'width': $(window).width(), 'height': $(window).height(),});// make sure div stays full width/height on resize$(window).resize(function(){ var $w = $(window); $('#content').css({ 'width': $w.width(), 'height': $w.height(), });});
10 Test password strength
In some websites, you are often asked to set a password. The website will also give corresponding prompts Based on the character characteristics of the entered password, such as the password is too short, the intensity is poor, the intensity is moderate, and the intensity is strong. How is this implemented? See the following code:
<Input type = "password" name = "pass" id = "pass"/> <span id = "passstrength"> </span> // The following regular expressions are recommended for favorites. oh, $ ('# pass') may be used on the project '). keyup (function (e) {// The password is eight or more characters and the three special letters and numbers contain var strongRegex = new RegExp ("^ (? =. {8 ,})(? =. * [A-Z]) (? =. * [A-z]) (? =. * [0-9]) (? =. * \ W ). * $ "," g "); // The password must be seven or more characters and contain letters, numbers, and special characters, the intensity is moderate var mediumRegex = new RegExp ("^ (? =. {7 ,})(((? =. * [A-Z]) (? =. * [A-z]) | ((? =. * [A-Z]) (? =. * [0-9]) | ((? =. * [A-z]) (? =. * [0-9]). * $ "," g "); var enou1_gex = new RegExp ("(? =. {6 ,}). * "," g "); if (false = enouw.gex. test ($ (this ). val () {values ('{passstrength'{.html ('more Characters ');} else if (strongRegex. test ($ (this ). val () {$ ('# passstrength '). className = 'OK'; condition ('{passstrength'{.html ('strong! ');} Else if (mediumRegex. test ($ (this ). val () {$ ('# passstrength '). className = 'alert '; ('{passstrength'{.html ('medium! ');} Else {$ (' # passstrength '). className = 'error'; condition ('{passstrength'{.html ('weak! ');} Return true ;});
11. Use JQuery to redraw the size of the part
You can redraw the image size on the server or on the client using JQuery.
$(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. dynamic page content loading during scrolling
In some websites, webpage content is not loaded at one time, but is dynamically loaded when the mouse is scroll down. How can this be done? See the following code:
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);});
The 15 useful jQuery code snippets collected in this article can be directly copied and pasted into the code, but please note that you need to understand the code before using it.