50 jquery Code Snippets (RPM)
This article will show you 50 jquery code snippets that will help you with your JavaScript project. Some of these snippets are only supported from jQuery1.4.2, others are really useful functions or methods that can help you get things done quickly and easily. If you find any place you can do better, you are welcome to paste your version in the comments!
1. How to modify jquery default encoding (e.g. default UTF-8 to change GB2312):
$.ajaxsetup ({
});
2. Resolve 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: You must first introduce prototype.js and then introduce Jquery.js, the order is not wrong.
3. JQuery determines whether an event is bound on an element
jquery Event encapsulation supports determining whether an event is bound on an element, and this method applies only to jquery-bound events
var $events = $ ("#foo"). Data ("events");
if ($events && $events ["click"]) {
Your code
4. How to use jquery to switch style sheets
Find out what type of media you wish to switch to (Media-type), and then set the href to the new style sheet.
$ (' link[media= ' screen '] '). attr (' href ', ' alternative.css ');
5. How to limit the selection (for optimization purposes):
Use the tag name as a prefix to the class name whenever possible.
So jquery doesn't have to spend more time searching for
The element you want. Another thing to keep in mind is that
The more specific the manipulation of the elements on your page,
The more time you can reduce execution 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"/> Item y</li>
<li><input type= "Radio" value= "Item-z" name= "item" class= "Unknown"/> Item z</li>
</ul>
6. How to use Toggleclass correctly:
The Toggle (toggle) class allows you to base a class
Whether it exists to add or remove the class.
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 ');
7. How to set the features specific to IE:
if ($.browser.msie) {
Internet Explorer is a sadist.
}
8. How to use jquery instead of an element:
$ (' #thatdiv '). ReplaceWith (' Fnuh ');
9. How to verify that an element is empty:
Method One
if (! $ (' #keks '). HTML ()) {
Nothing was found;
}
Method Two
if ($ (' #keks '). Is (": Empty")) {
Nothing was found;
}
10. How to find the index number of an element from an unordered collection
$ ("ul > Li"). Click (function () {
var index = $ (this). Prevall (). length; Prevall ([expr]): Finds all sibling elements before the current element
});
11. How to bind a function to an event:
Method One
Method Two, support for dynamic parameter transfer
12. How to append or add HTML to an element:
13. How to use object literals (literal) to define attributes when creating elements
14. How to use multiple properties to filter
15. How to preload an image using jquery:
}
16. How to set an event handler for any element that matches the selector:
For example, in the case of table, you used to
17. How to find an option element that has been selected:
18. How to hide an element that contains a value text:
19. 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 are left. In this case,
The query deleted any (: not) there (: has)
Contains a child node of class "Selected" (. selected).
. Filter (": Not (: Have (. selected))")
20. How to detect various browsers:
Detects Safari (if ($.browser.safari)),
Detect IE6 and later versions (if ($.browser.msie && $.browser.version > 6)),
Detect IE6 and Previous versions (if ($.browser.msie && $.browser.version <= 6)),
Detects Firefox 2 and later (if ($.browser.mozilla && $.browser.version >= ' 1.8 '))
21. Use the has () to check if an element contains a class or element:
The JQuery 1.4.* contains support for this has method.
This method finds out whether an element contains another element class or anything else that you are looking for and that you want to manipulate on top of it.
$ ("input"). has (". Email"). AddClass ("Email_icon");
22. How to disable the right-click context menu:
23. How to define a custom selector
24. How to check if an element exists
25. How to use jquery to detect both right and left mouse clicks:
}
});
26. How to replace words in a string
27. How to automatically hide or close elements after a period of time (1.4 versions supported):
28. How to dynamically add elements that have been created to the DOM:
29. 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 the standard maxLength
This.maxlength = max;
} elseif (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 >50| | keycode ==32| | keycode ==0| | keycode ==13) &&!ob.ctrlkey &&!ob.altkey &&!hasselection);
};
This.onkeyup =function () {
if (This.value.length > Max) {
This.value =this.value.substring (0,max);
}
};
}
});
};
Usage
$ (' #mytextarea '). MaxLength (500);
30. How jquery registers and disables jquery global events
jquery Registers Ajax Global Event Ajaxstart,ajaxstop:
$ (document). Ajaxstart (function () {
$ ("#background, #progressBar"). Show ();
}). Ajaxstop (function () {
$ ("#background, #progressBar"). Hide ();
});
The AJAX request disables the global event: $.ajax () has a parameter global (default: TRUE) to trigger global AJAX events. Setting to False will not trigger global AJAX events, such as Ajaxstart or ajaxstop, which can be used to control different Aja X event.
31. How to clone an element in jquery:
32. How to test whether an element is visible in jquery
33. How to place an element in the center of the screen:
Returnthis.each (function () {
$ (this). CSS ({
Position: ' Absolute ',
Left, ($ (window). Width ()-this.width ())/2+ $ (window). ScrollLeft () + ' px '
});
});
}
This will use the above function:
34. How to put the values of all elements with a particular name in an array:
Arrinputvalues.push ($ (this). Val ());
35. How to remove HTML from an element
});
36. How to use closest to get the parent element:
37. How to use Firebug and Firefox to record the jquery event log:
Allow chained logging
}
};
$ (' #someDiv '). Hide (). log (' div hidden '). addclass (' SomeClass ');
38. How to force a link to open in a pop-up window:
Returnfalse;
39. How to force a link to open in a new tab:
40. How to use. Siblings () in jquery to select sibling elements
});
});
41. How to toggle all the check boxes on the page:
Tog =!tog;
});
42. How to filter a list of elements based on some input text:
43. How to get the mouse pad cursor position x and Y
});
});
44. How to extend the method of a String object
$.extend (String.prototype, {
Ispositiveinteger:function () {
Return (new RegExp (/^[1-9]\d*$/). Test (this));
},
Isinteger:function () {
Return (new RegExp (/^\d+$/). Test (this));
},
Isnumber:function (value, Element) {
Return (new RegExp (/^-) (?: \ d+|\d{1,3} (?:, \d{3}) +) (?: \. \d+) $/). Test (this));
},
Trim:function () {
Returnthis.replace (/(^\s*) | ( \s*$) |\r|\n/g, "");
},
Trans:function () {
Returnthis.replace (/</g, ' < '). Replace (/>/g, ' > '). replace (/"/g, ' "');
},
Replaceall:function (OS, NS) {
Returnthis.replace (New RegExp (OS, "GM"), NS);
},
Skipchar:function (CH) {
if (!this| | this.length===0) {return ';}
if (This.charat (0) ===ch) {returnthis.substring (1). Skipchar (ch);}
Returnthis;
},
Isvalidpwd:function () {
Return (New RegExp (/^ ([_]|[ A-za-z0-9]) {6,32}$/). Test (this));
},
Isvalidmail:function () {
Return (New RegExp (/^\w+ (-\w+) | ( \.\w+)) *\@[a-za-z0-9]+ ((\.| -) [a-za-z0-9]+] *\. [a-za-z0-9]+$/). Test (This.trim ()));
},
Isspaces:function () {
for (var i=0; i<this.length; i+=1) {
var ch =this.charat (i);
if (ch!= ' && ch!= "\ n" && ch!= "\ T" && ch!= "\ r") {Returnfalse;}
}
Returntrue;
},
Isphone:function () {
Return (new RegExp (^ ([0-9]{3,4}[-])? \d{3,8} (-\d{1,6})? $) | ( ^\ ([0-9]{3,4}\) \d{3,8} (\ (\d{1,6}\))? $) | (^\d{3,8}$)/). Test (this));
},
Isurl:function () {
Return (New RegExp (/^[a-za-z]+:\/\/([a-za-z0-9\-\.] +) ([-\w. \/?%&=:]*) $/). Test (this));
},
Isexternalurl:function () {
Returnthis.isurl () &&this.indexof ("://" +document.domain) ==-1;
}
});
45. How to Standardize write jquery plugins:
(function ($) {
$.fn.extend ({
Pluginone:function () {
Returnthis.each (function () {
My Code
});
},
Plugintwo:function () {
Returnthis.each (function () {
My Code
});
}
});
}) (JQuery);
46. How to check if the image has been fully loaded in
47. How to use jquery to specify namespaces for events:
48. How to check if cookies are enabled
49. How to expire cookies:
$.cookie (' Example ', ' foo ', {expires:date});
50. How to use a clickable link to replace any URL in the page
$ (this). html (). Replace (RegExp, ' <a href= ' >$1</a> ')
});
50 jquery Code Snippets (RPM)