60 Very useful jquery code development tips for collecting _jquery

Source: Internet
Author: User
Tags tag name tagname

Ctrl+f Search for more content

See these nice jquery code development tips on the web by chance. The original collection of 30, in addition to find out when there are 20. Add another 10 practical jquery snippets, a total of 60 code tips, collected to share with everyone.

1. Creating a nested filter

. Filter (": Not (: Has (. selected)")//Remove all elements that do not contain class. Selected

2. Reuse your element query

var AllItems = $ ("Div.item"); 
var keeplist = $ ("Div#container1 Div.item"); 
<div>class names: 
$ (Formtolookat + "input:checked"). each (function () {  keeplistkeeplist = Keeplist.filter ("." + $ (This). attr ("name")); });
</div>

3. Use has () to determine whether an element contains a specific class or element

JQuery 1.4.* includes support for the has method. This method would find 
//if a element contains a certain the other element class or whatever it is 
//you are Looki Ng for and do anything your want to them. 
$ ("input"). has (". Email"). AddClass ("Email_icon");

4. Use jquery to toggle Styles

Look for the Media-type your wish to switch then set the "href to your" new style sheet 
$ (' link[media= ' Screen '). attr ( ' href ', ' alternative.css '); 

5. Restricted areas of choice

Where possible, pre-fix your class names with a tag name 
//so "JQuery doesn ' t have to spend" more time searching< C5/>//for the element you ' re after. Also Remember that anything 
//you can does more specific about where the element is 
//on your page would cut do WN on execution/search times 
var in_stock = $ (' #shopping_cart_items input.is_in_stock ');
<ul id= "Shopping_cart_items" > 
<li> 
<input value= "item-x" name= "Item" class= "Is_in_stock" Type= "Radio" > Item x</li> 
<li> <input value= "item-y" name= 
"Item" class= "3-5_days" type= " Radio "> Item y</li> 
<li> 
<input value=" item-z "name=" Item "class=" Unknown "type=" Radio " > Item z</li> 
</ul> 

6. How to use Toggleclass correctly

Toggle class allows you to add or remove a class 
//from a element depending on the presence of this 
. Where some developers would use: A.hasclass (' BlueButton ')? A.removeclass (' BlueButton ' 
): A.addclass (' BlueButton ') ); 
Toggleclass allows to easily doing this using 
a.toggleclass (' BlueButton '); 

7. Set the function specified by IE

if ($.browser.msie) {//Internet Explorer is a sadist.} 

8. Use jquery to replace an element

$ (' #thatdiv '). ReplaceWith (' Fnuh ');

9. Verify that an element is empty

if ($ (' #keks '). HTML ()) {//nothing found;} 

10. Find an index of an element in a unordered set

$ ("ul > Li"). Click (function () { 
 var index = $ (this). Prevall (). length; 
});

11. Bind a function to an event

$ (' #foo '). Bind (' click ', Function () { 
 alert (' User clicked on ' foo. "'); 
}); 

12. Add HTML to an element

$ (' #lal '). Append (' Sometext ');

13. Use objects to define attributes when creating elements

var e = $ ("", {href: "#", Class: "A-class Another-class", Title: "..."});

14. Filter multiple properties using filters

This precision-based approached can is useful when your use 
//lots of similar input elements which have different Typ Es 
var elements = $ (' #someid Input[type=sometype][value=somevalue] '). get (); 

15. Pre-loading pictures with jquery

Jquery.preloadimages = function () {for (var i = 0; I '). attr (' src ', arguments[i]);}; 
Usage $.preloadimages (' image1.gif ', '/path/to/image2.png ', ' some/image3.jpg '); 

16. Set any event handlers that match a selector

$ (' Button.someclass '). Live (' click ', someFunction);
 Note This in JQuery 1.4.2, the delegate and undelegate options have been//introduced to
 replace live as they offer Better support
 for the context//for example, in terms of a table where before your use.
 . Live ()
 $ ("table"). each (function () {
 $ (' TD ', this '). Live ("hover", function () {
 $ (this). Toggleclass (" Hover ");
 }
 ); Now use.
 $ ("table"). Delegate ("TD", "hover", function () {
 $ (this). Toggleclass ("hover");

17. Find the selected OPTION element

$ (' #someElement '). Find (' option:selected ');

18. Hide elements that contain specific values

$ ("P.value:contains (' Thetextvalue ')"). Hide ();

19. Automatic scrolling to specific areas of the page

JQuery.fn.autoscroll = function (selector) {
 $ (' html,body '). Animate (
 {scrolltop: $ (selector). Offset (). Top},
 )
;
Then to scroll to the Class/area your wish to get to like this:
$ ('. Area_name '). AutoScroll ();

20. Detect various Browsers

Detect Safari (if ($.browser.safari),
detect IE6 and over (if ($.browser.msie && $.browser.version > 6)) ,
detect IE6 and below (if ($.browser.msie && $.browser.version <= 6)),
detect FireFox 2 and above ( if ($.browser.mozilla && $.browser.version >= ' 1.8 '))

21. Replace the word in the string

var el = $ (' #id ');
El.html (el.html (). Replace (/word/ig, '));

22. Close the right button menu

$ (document). Bind (' ContextMenu ', function (e) {return false;});

23. Define a custom Selector

$.expr[': '].mycustomselector = function (element, index, meta, stack) {
//Element-is a DOM element
//Index-the Current loop index into stack
//Meta-meta data about your selector
//Stack-stack of all elements to loop
/ /return True to include the current element
//return FALSE to Explude current element
};
Custom Selector Usage:
$ ('. Someclasses:test '). dosomething ();

24. Determine if an element exists

if ($ (' #someDiv '). length) {//hooray!!! it exists ...}

25. Use jquery to determine the mouse key 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. Show or delete the default value of the input box

This snippet would show you and keep a default value
//in a text input field for when a user hasn ' t entered in
  
   //a value to replace it
swap_val = [];
$ (". Swap"). each (function (i) {
 swap_val[i] = $ (this). Val ();
 $ (this). Focusin (function () {
  if ($ (this). val () = = Swap_val[i]) {
   $ (this). Val ("");
  }
 ). Focusout (function () {
  if ($.trim ($ (this). val ()) = = "") {
   $ (this). Val (Swap_val[i]);
  }
 }
);

  
<input class=swap value= "Enter Username here ..." type=text> 

27. Automatically hide or close elements after a specified time (1.4 support)

Here's how we used the 1.3.2 using settimeout
settimeout (function () {
 $ ('. Mydiv '). Hide (' blind ', {}, 50 0)
}, 5000);
And here's how can I do it with 1.4 using the delay () feature (
". Mydiv"). Delay (5000). Hide (' blind ', {}, 500);

28. Dynamically creating elements to DOM

var newgbin1div = $ (');
NEWGBIN1DIV.ATTR (' id ', ' gbin1.com '). Appendto (' body ');

29. Limit the number of characters textarea

JQuery.fn.maxLength = function (max) {
 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:
$ (' #gbin1textarea '). MaxLength (500);

30. Create a basic test case for a function

Separate tests into modules.
Module ("Module B");
Test ("Some other gbin1.com test", function () {
 //specify I many assertions are to run expected a test.
 Expect (2);
 A comparison assertion, equivalent to JUnit ' s assertequals.
 Equals (True, false, "failing test");
 Equals (True, true, "passing Test");
});

31. Cloning elements using jquery

var cloned = $ (' #gbin1div '). Clone ();

32. Test whether an element is visible in jquery

if ($ (Element). Is (': visible ') = = ' true ') {//the element is visible}

33. Element Screen Center

JQuery.fn.center = function () {
 this.css (' position ', ' absolute ');
 This.css (' Top ', ($ (window). Height ()-this.height ())/+$ (window). scrolltop () + ' px ');
 This.css (' Left ', ($ (window). Width ()-this.width ())/2+$ (window)-scrollleft () + ' px ');
Use the above function as: $ (' #gbin1div '). Center ();

34. Generate an array using the corresponding value of the element of a particular name

var arrinputvalues = new Array ();
$ ("Input[name= ' table[]"). each (function () {
  Arrinputvalues.push ($ (this). Val ());
});

35. Exclude HTML from the element

(function ($) {
 $.fn.striphtml = function () {
  var regexp =/< ("[^"]* "|") [^']*'| [^ ' "]) *>/gi;
  This.each (function () {
   $ (this). HTML (
    $ (this). html (). Replace (RegExp, "")
   );
  return $ (this);
 }
}) (jQuery);
Usage:
$ (' P '). striphtml ();

36. Use closest to get the parent element

$ (' #searchBox '). Closest (' div ');

37. Use Firebug to record jquery events

Allows chainable logging
//Usage: $ (' #someDiv '). Hide (). log (' div hidden '). addclass (' SomeClass ');
JQuery.log = JQuery.fn.log = function (msg) {
  if (console) {
   console.log ("%s:%o", MSG, this);
  }
  return this;
};

38. Click the link to force a new window to pop up

JQuery (' A.popup '). Live (' click ', Function () {
 Newwindow=window.open (this). attr (' href '), ', ' height=200, Width=150 ');
 if (window.focus) {Newwindow.focus ()} return
 false;
});

39. Click on the link force to open a new tab page

JQuery (' A.newtab '). Live (' click ', Function () {
 Newwindow=window.open ($ (this). href);
 JQuery (this). target = "_blank";
 return false;
});

40. Use siblings () to handle similar elements

Rather than doing this
$ (' #nav li '). Click (function () {
 $ (' #nav Li '). Removeclass (' active ');
 $ (this). addclass (' active ');
};
Do this instead
$ (' #nav li '). Click (function () {
 $ (this). addclass (' active ')
  . Siblings (). Removeclass (' Active ');

41. Select or uncheck all check boxes on the page

var tog = false; Or true if they are checked on load
$ (' a '). Click (function () {
 $ ("Input[type=checkbox]"). attr ("Checked",!) TOG);
 Tog =!tog;
});

42. Filter page elements based on input text

If the value of the element matches that of the entered text
//it would be returned
$ ('. Gbin1class '). Filter (Fun Ction () {return $ (this
 ). attr (' value ') = = $ (' Input#gbin1id '). Val ();
 })

43. Get the X and y coordinates of the mouse

$ (document). MouseMove (function (e) {
$ (document). Ready (function () {
$ (). MouseMove (function (e) {
$ (' # XY '). HTML ("Gbin1 X Axis:" + E.pagex + "| Gbin1 Y Axis "+ e.pagey);
}";

44. Make the entire list element (LI) clickable

$ ("ul Li"). Click (function () {
 window.location=$ (this). Find ("a"). attr ("href"), return false;
});
<UL>
<li><a href= "#" >gbin1 Link 1</a></li>
<li><a href= "#" > GBin1 link 2</a></li>
<li><a href= "#" >gbin1 link 3</a></li>
<li ><a href= "#" >gbin1 Link 4</a></li>
</UL> 

45. Using jquery to parse XML

function Parsexml (XML) {
 //find every Tutorial and print the author
 $ (XML). Find ("Tutorial"). each (function () c21/>{
 $ ("#output"). Append ($ (this). attr ("author") + "");
 }

46. Judge whether a picture is loaded completely

$ (' #theGBin1Image '). attr (' src ', ' image.jpg '). Load (function () {
alert (' This image has Been Loaded ');
});

47. Using the jquery naming event

Events can be namespaced like this
$ (' input '). Bind (' Blur.validation ', function (e) {
 //...
});
The data method also accept namespaces
$ (' input '). Data (' Validation.isvalid ', true);

48. Determine whether the cookie is activated or closed

var dt = new Date ();
Dt.setseconds (Dt.getseconds () +);
Document.cookie = "cookietest=1; Expires= "+ dt.togmtstring ();
var cookiesenabled = document.cookie.indexOf ("cookietest=")!=-1;
if (!cookiesenabled)
{
 //cookies have not been enabled
}

49. Force expired Cookies

var date = new Date ();
Date.settime (Date.gettime () + (x * * 1000));
$.cookie (' Example ', ' foo ', {expires:date});

50. Use a clickable chain to replace all URLs in the page

$.fn.replaceurl = function () {
  var regexp =/(FTP|HTTP|HTTPS)://(w+:{0,1}w*@)? ( s+) (: [0-9]+)? (/|/([w#!:.? +=&%@!-/])? /gi;
  This.each (function () {
   $ (this). HTML (
    $ (this). html (). Replace (RegExp, ' <a href= ' >$1</A> ')
   );
  });
  return $ (this);
 }
Usage
$ (' #GBin1div '). Replaceurl (); 

51: Disable "Enter" in the form

The following code is certainly helpful when you might want to prevent users from accidentally submitting a form in the form's operations:

$ ("#form"). KeyPress (function (e) {
 if (E.which =) {return
 false;
 }
});

52: Clear all the form data

You may need to invoke different types of clear methods for different forms, but using this out-of-the-box method will definitely save you a lot of effort.

function ClearForm (form) {//iterate over all of the inputs for the
 form
 //element that is passed in
 $ (': in Put ', form]. each (function () {
 var type = This.type;
 var tag = This.tagName.toLowerCase (); Normalize case
 //It's OK to reset the value attr of text inputs,
 //password inputs, and Textareas
 if (typ E = = ' Text ' | | Type = = ' Password ' | | Tag = = ' textarea ')
  this.value = "";
 Checkboxes and radios need to have their checked state cleared
 //But-should *not* have ' value ' their >else if (type = = ' checkbox ' | | | type = = ' Radio ')
  this.checked = false;
 Select elements need to have their ' selectedindex ' property set To-1
 //(This works for both single and multiple Select elements)
 else if (tag = = ' select ')
  this.selectedindex =-1;
 });

53: Disable the buttons in the form

The following code is useful for AJAX operations, and you can effectively prevent users from submitting data multiple times, and individuals often use:

Disable button:

$ ("#somebutton"). attr ("Disabled", true);

Start button:

$ ("#submit-button"). Removeattr ("Disabled");

You may often use. attr (' disabled ', false), but this is not the correct call.

54: Enable the Submit button after entering the content

This code is similar to the above, and belongs to the help user to control the form Submit button. After using this code, the Submit button can be started only after the user enters the specified content.

$ (' #username '). KeyUp (function () {
 $ (' #submit '). attr (' disabled ',!$ (' #username '). Val ()); 

55: No multiple submission of forms

Submitting a form multiple times is a headache for Web applications, and the following code is a great way to help you solve this problem:

$ (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;
 }
});

56: Highlight the current focus of the input box to indicate

Sometimes you need to prompt the user for the current operation of the input box, you can use the following code to highlight the indicator:

$ ("Form:input"). focus (function () {
 $ (' label[for= ' + this.id + ' '] '). addclass ("Labelfocus");
Blur (function () {
 $ ("label"). Removeclass ("Labelfocus");

57: Add form elements in a dynamic way

This method can help you dynamically add elements of the form, such as input, etc.:

Change event in Password1 field to prompt new input
$ (' #password1 '). Change (function () {
  //dynamically create NE W input and insert after Password1
  $ ("#password1"). Append ("<input type= ' text ' name= ' password2 ' id= '," Password2 ')/& gt; ");
});

58: Automatically import data into Selectbox

The following code can automatically generate the contents of the selection box using AJAX data

$ (function () {
 $ ("Select#ctljob"). Change (function () {
 $.getjson ("/select.php", {ID: $ (this). Val (), Ajax: ' True '}, function (j) {
  var options = ';
  for (var i = 0; i < j.length i++) {
  options = ' <option value= ' + j[i].optionvalue + ' "> ' + J[i].optiondis Play + ' </option> ';
  }
  $ ("Select#ctlperson"). HTML (options),
 })}
)

59: Determine if a check box is selected

The code is simple, as follows:

$ (' #checkBox '). attr (' checked ');

60: Use the code to submit the form

The code is simple, as follows:

 $ ("#myform"). Submit (); 

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.