49 classic jQuery code snippets

Source: Internet
Author: User

49 classic jQuery code snippets
49 classic jquery code snippets that can help your javascript project. Some of the code segments are supported since jQuery1.4.2, while others are actually useful functions or methods. They can help you complete things quickly and well. If you find anything you can do better, paste your version in the comments!

1. How to modify jQuery default encoding (for example, change the default UTF-8 to GB2312): $. ajaxSetup ({
AjaxSettings: {contentType: "application/x-www-form-urlencoded; chartset = GB2312 "}
});


2. Solve the Problem of coexistence of jQuery and prototype and $ global variable conflict: frontend UI sharing
<Script src = "prototype. js"> </script>
<Script src = "http://blogbeta.blueidea.com/jquery.js"> </script>
<Script type = "text/javascript">
JQuery. noConflict ();
</Script>
Note: you must first introduce prototype. js and then jquery. js. The sequence is not wrong.

3. jQuery checks whether an event is bound to an element.
// JQuery event encapsulation supports determining whether events are bound to an element. This method is only applicable to events bound to jQuery.
Var $ events = $ ("# foo"). data ("events ");
If ($ events & $ events ["click"]) {
// Your code
}

4. How to Use jQuery to switch between style sheets
// Find the media type you want to switch to, and then set href to a new style sheet.
$ ('Link [media = 'screen'''). attr ('href ', 'alternative.css ');

5. How to limit the selection range (for optimization purposes ):


// Use the label name as the class name prefix whenever possible,
// JQuery does not need to spend more time searching.
// The elements you want. Remember that,
// The more specific the operations on the elements on your page,
// The lower the execution and search time. Frontend UI sharing
Var in_stock = $ ('# shopping_cart_items input. is_in_stock ');


      
  • Item X

  •   
  • Item Y

  •   
  • Item Z



6. How to correctly use toggleClass:
// Toggle class allows you
// Whether the class exists to be added or deleted.
// In this case, some developers use:
A. hasClass ('bluebutton ')? A. removeClass ('bluebutton'): a. addClass ('bluebutton ');
// ToggleClass allows you to use the following statements to easily achieve this
A. toggleClass ('bluebutton ');

7. How to set the unique features of IE:
If ($. browser. msie ){
// Internet Explorer is crazy.
}

8. How to Use jQuery to replace an element:
$ ('# Thatdiv'). replaceWith ('fnuh ');

9. How to verify whether an element is null:
// Method 1
If (! Certificate ('{keks'}.html ()){
// Nothing is found;
}

// Method 2
If ($ ('# keks'). is (": empty ")){
// Nothing is found;
}

10. How to Find the index number of an element from an unordered set front-end UI sharing
$ ("Ul> li"). click (function (){
Var index = $ (this). prevAll (). length; // prevAll ([expr]): Find all peer elements before the current element
});

11. How to bind a function to an event:


// Method 1
$ ('# Foo'). click (function (event ){
Alert ('user clicked on "foo ."');
});

// Method 2: Support for dynamic parameter passing
$ ('# Foo'). bind ('click', {test1: "abc", test2: "123"}, function (event ){
Alert ('user clicked on "foo." '+ event. data. test1 + event. data. test2 );
});

12. How to append or add html to an element:
$ ('# Lal'). append ('sometext ');

13. How to Use literal to define attributes when creating elements
Var e = $ ("", {href: "#", class: "a-class another-class", title :"..."});

14. How to use multiple attributes for filtering
// When many similar input elements have different types,
// This precision-based method is useful for front-end UI sharing.
Var elements = $ ('# someid input [type = sometype] [value = somevalue]'). get ();

15. How to Use jQuery to pre-load images:
JQuery. preloadImages = function (){
For (var I = 0; I <arguments. length; I ++ ){
$ (""). Attr ('src', arguments );
}
};
// Usage
Pai.preloadimages('image1.gif ','/path/to/image2.png ', 'some/image3.jpg ');

16. How to Set Event Handlers for any element that matches the selector:
$ ('Button. someClass '). live ('click', someFunction );
// Note: In jQuery 1.4.2, the delegate and undelegate options
// Be introduced to replace live because they provide better context support
// For example, in table, you used
$ ("Table"). each (function (){
$ ("Td", this). live ("hover", function (){
$ (This). toggleClass ("hover ");
});
});
// Used now
$ ("Table"). delegate ("td", "hover", function (){
$ (This). toggleClass ("hover ");
});

17. How to find a selected option element:
$ ('# SomeElement'). find ('option: selected ');

18. How to hide an element that contains a value text:
$ ("P. value: contains ('thetextvalue')"). hide ();

19. How to Create nested filters:
// Allows you to reduce the filter of matching elements in the set,
// Only the parts that match the given selector are left. In this case,
// The query has deleted any (: not) with (: has)
// Contains child nodes whose class is "selected" (. selected.
. Filter (": not (: has (. selected ))")

20. How to detect various browsers:

Detect Safari (if ($. browser. safari )),
Check IE6 and later versions (if ($. browser. msie & $. browser. version> 6 )),
Check IE6 and earlier versions (if ($. browser. msie & $. browser. version <= 6 )),
Check FireFox 2 and later versions (if ($. browser. mozilla & $. browser. version> = '1. 8 '))
21. Any use of has () to check whether an element contains a class or element:
// JQuery. * contains support for this has method. Frontend UI sharing
// This method is used to find out whether an element contains another element class or any other stuff you are looking for and operating on.
$ ("Input"). has (". email"). addClass ("email_icon ");

22. How to disable context menu by right-clicking:
$ (Document). bind ('textmenu ', function (e ){
Return false;
});

23. How to define a custom Selector
$. Expr [':']. mycustomselector = function (element, index, meta, stack ){
// Element-a DOM element
// Index-the current cyclic index in the stack
// Meta-metadata about the selector
// Stack-stack of all elements to be recycled
// Returns true if it contains the current element.
// If the current element is not included, false is returned };
// Custom selector usage:
$ ('. SomeClasses: test'). doSomething ();

24. How to check whether an element exists
If ($ ('# somediv'). length ){
// Long live !!! It exists ......
}

25. How to Use jQuery to detect two situations: Right-click and left-click:


$ ("# Someelement"). live ('click', function (e ){
If ((! $. Browser. msie & e. button = 0) | ($. browser. msie & e. button = 1 )){
Alert ("Left Mouse Button Clicked ");
} Else if (e. button = 2 ){
Alert ("Right Mouse Button Clicked ");
}
});

26. How to replace words in a string
Var el = $ ('# id ');
El.html(el.html (). replace (/word/ig ,''));

27. How to automatically hide or disable elements after a period of time (version 1.4 is supported ):
// This is implemented using setTimeout in 1.3.2.
SetTimeout (function (){
$ ('. Mydiv'). hide ('blind', {}, 500)
},5000 );
// This method can be implemented using the delay () function in 1.4 (this is like sleep)
$ (". Mydiv"). delay (5000). hide ('blind', {}, 500 );

28. How to dynamically Add the created elements to the DOM:
Var newDiv = $ ('');
NewDiv. attr ('id', 'mynewdiv '). appendTo ('body ');

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;
} 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> 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 to register and disable jQuery global events
// JQuery registers the ajax global event ajaxStart and ajaxStop:
$ (Document). ajaxStart (function (){
$ ("# Background, # progressBar"). show ();
}). AjaxStop (function (){
$ ("# Background, # progressBar"). hide ();
});
// Disable global events for ajax requests: $. ajax () has a global parameter (default: true) to determine whether to trigger a global AJAX event. setting false does not trigger global AJAX events. For example, ajaxStart or ajaxStop can be used to control different Ajax events. Frontend UI sharing

31. In jQuery, how can I get an element:
Var cloned = $ ('# somediv'). clone ();

32. How to test whether an element is visible in jQuery?


If ($ (element). is (': visible ')){
// This element is visible.
}

33. How to place an element in the center of the screen:
JQuery. fn. center = function (){
Return this. each (function (){
Certificate (this).css ({
Position: 'absolute ',
Top, ($ (window). height ()-this. height ()/2 + $ (window). scrollTop () + 'px ',
Left, ($ (window). width ()-this. width ()/2 + $ (window). scrollLeft () + 'px'
});
});
}
// Use the above function in this way:
$ (Element). center ();
34. How to put the values of all elements with a specific name in an array:
Var arrInputValues = new Array ();
$ ("Input [name = 'xxx']"). each (function (){
ArrInputValues. push ($ (this). val ());
});

35. How to remove HTML from elements
(Function ($ ){
$. Fn. stripHtml = function (){
Var regexp =/<("[^"] * "| '[^'] * '| [^'">]) *>/gi;
This. each (function (){
Certificate (this).html (certificate (this).html (). replace (regexp ,''));
});
Return $ (this );
}
}) (JQuery );
// Usage:
$ ('P'). stripHtml ();

36. How to Use closest to obtain the parent element:
$ ('# Searchbox'). closest ('div ');

37. How to Use Firebug and Firefox to record jQuery Event Logs:


// Enable chained Logging
JQuery. log = jQuery. fn. log = function (msg ){
If (console ){
Console. log ("% s: % o", msg, this );
}
Return this;
};
// Usage:
$ ('# Somediv'). hide (). log ('div den'). addClass ('someclass ');

38. How to force the link to be opened in the pop-up window:
$ ('A. popup'). live ('click', function (){
Var newwindow = window. open ($ (this). attr ('href '), '', 'height = 200, width = 150 ');
If (window. focus ){
Newwindow. focus ();
}
Return false;
});

39. How to force the link to open in a new tab:
$ ('A. newTab '). live ('click', function (){
Var newwindow = window. open (this. href );
Certificate (thisdomain.tar get = "_ blank ";
Return false;
});

40. How to Use. siblings () in jQuery to select peer element front-end UI sharing
// Do not do this
$ ('# Nav li'). click (function (){
$ ('# Nav li'). removeClass ('active ');
$ (This). addClass ('active ');
});
// The alternative method is
$ ('# Nav li'). click (function (){
$ (This). addClass ('active'). siblings (). removeClass ('active ');
});

41. How to switch all check boxes on the page:
Var tog = false;
// Or true, if they are selected during loading
$ ('A'). click (function (){
$ ("Input [type = checkbox]"). attr ("checked ",! Tog );
Tog =! Tog;
});

42. How to filter an element list based on some input text:
// If the element value matches the input text, the element will be returned
$ ('. SomeClass'). filter (function (){
Return $ (this). attr ('value') =$ ('input # someid'). val ();
})

43. How to obtain the mouse pad position x and y
$ (Document). ready (function (){
$ (Document). mousemove (function (e ){
('{Xy'{.html ("X Axis:" + e. pageX + "| Y Axis" + e. pageY );
});
});

44. How to extend the 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 (){
Return this. replace (/(^ \ s *) | (\ s * $) | \ r | \ n/g ,"");
},
Trans: function (){
Return this. replace (/& lt;/g, '<'). replace (/& gt;/g, '> '). replace (/& quot;/g ,'"');
},
ReplaceAll: function (OS, ns ){
Return this. replace (new RegExp (OS, "gm"), ns );
},
SkipChar: function (ch ){
If (! This | this. length = 0) {return '';}
If (this. charAt (0) === ch) {return this. substring (1). skipChar (ch );}
Return this;
},
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 Var ch = this. charAt (I );
If (ch! = ''& Ch! = "\ N" & ch! = "\ T" & ch! = "\ R") {return false ;}
}
Return true;
},
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 (){
Return this. isUrl () & this. indexOf (": //" + document. domain) =-1;
}
});

45. How to standardize writing jQuery plug-ins:


(Function ($ ){
$. Fn. extend ({
PluginOne: function (){
Return this. each (function (){
// My code
});
},
PluginTwo: function (){
Return this. each (function (){
// My code
});
}
});
}) (JQuery );

46. How to check whether the image has been fully loaded into the front-end UI for sharing
$ ('# Theimag'). attr ('src', 'image.jpg'). load (function (){
Alert ('this Image Has Been loaded ');
});

47. How to Use jQuery to specify a namespace for an event:
// Events can be bound to namespaces in this way
$ ('Input'). bind ('blur. valider', function (e ){
//...
});
// The data method also accepts the namespace
$ ('Input'). data ('validation. isvalid', true );

48. How to check whether cookies are enabled
Var dt = new Date ();
Dt. setSeconds (dt. getSeconds () + 60 );
Document. cookie = "cookietest = 1; expires =" + dt. toGMTString ();
Var cookiesEnabled = document. cookie. indexOf ("cookietest = ")! =-1;
If (! CookiesEnabled ){
// No cookie is enabled
}

49. How to Make the cookie expire:
Var date = new Date ();
Date. setTime (date. getTime () + (x * 60*1000 ));
$. Cookie ('example ', 'foo', {expires: date });

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.