50 Essential Practical jquery Code Snippets + 15 jquery snippets that can be used directly

Source: Internet
Author: User
Tags tag name


This article will show you 50 pieces of jquery code that can help with your JavaScript project. Some of these pieces of code are supported by jQuery1.4.2 and others are really useful functions or methods that can help you get things done quickly and well. If you find anything you can do better, please paste your version in the comments! How to modify the jquery default encoding (for example, default UTF-8 changed to GB2312):

$.ajaxsetup ({
ajaxsettings:{contentType: "application/x-www-form-urlencoded;chartset=gb2312"} 
});
Solve jquery, prototype coexistence, $ global variable conflict problem:
<script src= "Prototype.js" ></script>
<script src= "Http://blogbeta.blueidea.com/jquery.js" > </script>
<script type= "Text/javascript" >
      jquery.noconflict ();

Note: must first introduce prototype.js and then introduce Jquery.js, the order can not be wrong. JQuery determines whether an event is bound on an element

The jquery event encapsulation supports determining whether an event is bound on an element, and this method applies only to jquery-bound event
var $events </span> = $ ("#foo"). Data ("events");
if ($events </span> &amp;&amp; <span class= "hljs-variable" > $events ["click"]) {
//your code} 
How to use jquery to toggle a style sheet
Find the type of media you want to switch (Media-type), and then set the href to a new style sheet. $ (' link[media= ' screen ']. attr (' href ', ' alternative.css ');
How to limit selection (based on optimization purposes):
Use the tag name as a prefix to the class name whenever possible,
so jquery doesn't need to spend more time searching
//The elements you want. One thing to keep in mind is that the
more specific the operations of the elements on your page are, the
more you can reduce the time to execute and search. var In_stock = $ (' #shopping_cart_items input.is_in_stock ');

<ul id= "Shopping_cart_items" > <li><input type= "Radio" value= "Item-x" "
name=" Item "class=" Is_in_ Stock "/> Item x</li> <li><input type= Radio" value= "Item-y
" name= "Item" class= "3-5_days"/> I TEM y</li>
<li><input type= "Radio" value= "Item-z" name= "item" class= "Unknown"/> Item z</li& gt;
</ul>
How to use Toggleclass correctly:
The Toggle (toggle) class allows you
to add or remove a class based on whether or not it exists.
//In this case some developers use: A.hasclass (' BlueButton ')? A.removeclass (' BlueButton '): A.addclass (' BlueButton ');
Toggleclass allows you to use the following statement to easily do this a.toggleclass (' BlueButton ');
How to set IE-specific features:
if ($.browser.msie) {
//Internet Explorer is a sadist}

8. How to use jquery instead of an element:

$ (' #thatdiv '). ReplaceWith (' Fnuh ');
How to verify that an element is empty:
Method one if (! $ (' #keks '). HTML ()) {
//nothing found;}

Method two if ($ (' #keks '). Is (": Empty")) {
//nothing found;}
How to find the index number of an element from an unordered collection
$ ("ul > Li"). Click (function () {
var index = $ (this). Prevall (). length;//prevall ([expr]): Find all sibling elements before the current element});
How to bind a function to an event:
Method A $ (' #foo '). Click (Function (event) { 
alert (' User clicked on ' foo. 

');  Method Two, which supports dynamic parameter $ (' #foo '). Bind (' click ', {test1: "abc", Test2: "123"}, function (event) { 
alert (' User clicked on ' foo. ') Event.data.test1 + event.data.test2); 
How to append or add HTML to an element:
How to use object literals (literal) to define attributes when creating an element
How to filter by using multiple properties
When many similar input elements with different types are used, 
How to use jquery to preload an image:
Jquery.preloadimages = function () {for 
(var i = 0; i < arguments.length; i++) { 
$ ("
How to set an event handler for any element that matches the selector:
$ (' Button.someclass '). Live (' click ', someFunction); 
Note that in the jquery 1.4.2, the delegate and undelegate options 
//are introduced instead of live because they provide better contextual support 
//For example, in the case of a table, you used to use $ ("table").  each (function () { 
$ (' TD ', this '). Live ("hover", function () { 
$ (this). Toggleclass ("hover"); 
}); 
}); 
Now use $ ("table"). Delegate ("TD", "hover", function () { 
$ (this). Toggleclass ("hover"); 
How to find an option element that is already selected:
How to hide an element that contains a text of a value:
How to create a nested filter:
Filters that allow you to reduce the matching elements in the collection,
//Only those parts that match the given selector. In this case,
//The query removes any (: not) (: has)
//contains child nodes with Class "Selected" (. selected). Filter (: Not () has (. selected))
How to detect various browsers:
Detect Safari (if ($.browser.safari)),  
detect IE6 and later versions (if ($.</span>browser.msie &amp;&amp; <span class=) Hljs-variable ">$.browser.version > 6") to  
detect IE6 and previous versions (if ($.</span>browser.msie &amp;&amp; <span class= "hljs-variable" >$.browser.version <= 6) to  
detect Firefox 2 and later versions (if ($.</span> Browser.mozilla &amp;&amp; <span class= "hljs-variable" >$.browser.version >= ' 1.8 '))
Any use of has () to check whether an element contains a class or element:
The JQuery 1.4.* contains support for this has approach.
//This method finds whether an element contains another element class or anything else that you are looking for and that you want to operate on. $ ("input"). has (". Email"). AddClass ("Email_icon");
How to disable right-click context menus:
$ (document). Bind (' ContextMenu ', function (e) {return 
false; 
How to define a custom selector
$.expr[': '].mycustomselector = function (element, index, meta, stack) { 
//element- 
The current cyclic index in a DOM element//index– Stack c4/>//meta–/// 
stack– the stack of all elements to loop///If the 
current element is included returns True 
//returns False if the current element is not included; 
How to check if an element exists
if ($ (' #someDiv '). Length) { 
How to use jquery to detect two mouse clicks with the right and left buttons:
$ ("#someelement"). Live (' click ', Function (e) { 
    if (!$.browser.msie &amp;&amp; E.button = = <span class= "Hljs-number" >0</span>) | | ($.browser.msie && E.button = 1)) { 
        alert ("Left Mouse button clicked"); 
    } else if (E.button = = 2) { 
        alert ("Right Mouse button clicked"); 
    }
);
How to replace a word in a string
var el = $ (' #id '); 
How to automatically hide or close elements after a period of time (support for version 1.4):
This is the way we use settimeout to implement in 1.3.2 settimeout (function () { 
$ ('. Mydiv '). Hide (' blind ', {},) 
}, 5000); 
How to dynamically add elements that have been created to the DOM:
var newdiv = $ (' <div></div> '); 
How to limit the number of characters in the "Text-area" field:
JQuery.fn.maxLength = function (max) {return This.each (function () {var type = This.tagName.toLowerCase (); var inputtype = This.type? 
        This.type.toLowerCase (): null;              if (type = = "Input" && inputtype = = "Text" | | | inputtype = = "Password") {//apply standard maxLength 
        This.maxlength = max; 
                else if (type = = "textarea") {this.onkeypress = function (e) {var ob = e | | | event; 
                var keycode = Ob.keycode; var hasselection = document.selection? 
                Document.selection.createRange (). text.length > 0:this.selectionstart!= this.selectionend; Return! (This.value.length >= Max && (KeyCode > | | keycode = | | keycode = 0 | | keycode =) &&!ob 
            . Ctrlkey &&!ob.altkey &&!hasselection); 
            }; This.onkeyup = function () {if (This.value.length > max) {tHis.value = this.value.substring (0,max);
        } 
            };
}
    });
};  Usage $ (' #mytextarea '). MaxLength (500);
How to jquery Register and disable jquery global events
jquery Registers Ajax Global event ajaxstart,ajaxstop:$ (document). Ajaxstart (function () {
    $ (#background, #progressBar). Show ( );
}). Ajaxstop (

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.