50 necessary practical jQuery code snippets

2011/09/20 13:32
Reading 4.5K

This article will show you 50 jquery code fragments, which can help your javascript project. Some of the code segments are supported since jQuery 1.4.2, while 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!

1. How to modify the default jQuery code (for example, change the default UTF-8 to GB2312):

 $.ajaxSetup({ ajaxSettings:{ contentType:"application/x-www-form-urlencoded;chartset=GB2312"}  });


2. Resolve the coexistence of jQuery and prototype, and the $global variable conflict:

 <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 import prototype. js and then import jquery. js. The order cannot be wrong.

3. By default, jQuery determines whether an event is bound to an element

 //JQuery event encapsulation supports judging whether an event is bound to an element. This method is only applicable 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 the media type you want to switch, and then set the href to the new style sheet. $('link[media='screen']').attr('href', 'alternative.css');


5. How to limit the selection range (based on optimization purpose):

 // As far as possible, use the tag name as the prefix of the class name, // In this way, jQuery does not need to spend more time searching // The element you want. One more thing to remember is that, // The more specific the operation of the elements on your page, // The less time it takes 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 "  / > Item Y< / li >    < li >< input type = " radio " value = " Item-Z " name = " item " class = " unknown "  / > Item Z< / li >  < / ul>


6. How to use toggleClass correctly:

 // Toggle class allows you to // Whether it exists to add or delete this class. // In this case, some developers use:  a.hasClass( ' blueButton ' ) ? a.removeClass( ' blueButton ' ) : a.addClass( ' blueButton ' ); // ToggleClass allows you to do this easily by using the following statement  a.toggleClass( ' blueButton ' );


7. How to set IE specific functions:

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


8. How to use jQuery to replace an element:

 $( ' #thatdiv ' ).replaceWith( ' fnuh ' );


9. How to verify whether an element is empty:

 // Method 1  if ($( ' #keks ' ).html()) { // Nothing was found;  } // Method 2  if ($( ' #keks ' ).is( " :emty " )) { // Nothing was found;  }


10. How to find the index number of an element from an unsorted set

 $( " ul > li " ).click( function () {   var index = $( this ).prevAll().length; // PrevAll ([expr]): Find all the peer elements before the current element  });


11. How to bind functions to events:

 // Method 1  $( ' #foo ' ).click( function (event) {    alert( ' User clicked on "foo. " ' );  }); // Method 2: Support dynamic parameter transfer  $( ' #foo ' ).bind( ' click ' , {test1: " abc " , test2: " one hundred and twenty-three " }, function (event) {    alert( ' User clicked on "foo. " '  + event.data.test1 + event.data.test2 );  });


12. How to append or add html to elements:

 $( ' #lal ' ).append( ' sometext ' );


13. How to use object 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 using many similar input elements with different types, // This accuracy based approach is useful  var elements = $( ' #someid input[type=sometype][value=somevalue] ' ).get();


15. How to use jQuery to preload images:

 jQuery.preloadImages =  function () {   for ( var i =  ;  i < arguments.length; i ++ ) {      $( " <img /> " ).attr( ' src ' , arguments[i]);    } }; // usage  $.preloadImages( ' image1.gif ' , ' /path/to/image2.png ' , ' some/image3.jpg ' );


16. How to set the event handler for any element matching the selector:

 $( ' button.someClass ' ).live( ' click ' , someFunction); // Note that in jQuery 1.4.2, the delegate and undelete options // They are introduced instead of live because they provide better context support // For example, for 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 " );  });


17. How to find an option element that has been selected:

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


18. How to hide an element containing 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 collection, // Only those parts that match the given selector are left. under these circumstances, // Query deletes any (: not) Yes (: 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 1.4. * includes support for this has method. // This method finds out whether an element contains another element class or any other thing you are looking for and want to operate on.  $( " input " ).has( " .email " ).addClass( " email_icon " );


22. How to disable right-click context menu:

 $(document).bind( ' contextmenu ' , function (e){     return  false ;  });


23. How to define a customized selector

 $.expr[ ' : ' ].mycustomselector =  function (element, index, meta, stack){ // Element - a DOM element // Index – The current circular index in the stack // Meta – Metadata about selectors // Stack – stack of all elements to loop // Returns true if the current element is included // If it does not contain the current element, it returns false}; // Custom selector usage:  $( ' .someClasses:test ' ).doSomething();


24. How to check whether an element exists

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


25. How to use jQuery to detect right click and left click:

 $( " #someelement " ).live( ' click ' , function (e) { if ( ( ! $.browser.msie && e.button ==  ) || ($.browser.msie && e.button ==  one ) ) {  alert( " Left Mouse Button Clicked " );  } else  if (e.button ==  two ) {  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 close elements after a period of time (supports version 1.4):

 // This is the way we use setTimeout in 1.3.2  setTimeout( function () {  $( ' .mydiv ' ).hide( ' blind ' , {}, five hundred )  }, five thousand ); // This is the way that you can use the function delay() in 1.4 (this is much like sleeping)  $( " .mydiv " ).delay( five thousand ).hide( ' blind ' , {}, five hundred );


28. How to dynamically add the created elements to the DOM:

 var newDiv = $( ' <div></div> ' );  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 >  : this .selectionStart !=  this .selectionEnd; return  ! ( this .value.length >= max && (keyCode >  fifty  || keyCode ==  thirty-two  || keyCode ==   || keyCode ==  thirteen ) &&  ! ob.ctrlKey &&  ! ob.altKey &&  ! hasSelection);  }; this .onkeyup =  function (){ if ( this .value.length > max){ this .value =  this .value.substring( ,max);  }  }; } }); }; // usage  $( ' #mytextarea ' ).maxLength( five hundred );


30. How to register and disable jQuery global events

 // JQuery registers the ajax global event ajaxStart, ajaxStop:  $(document).ajaxStart( function (){ $( " #background,#progressBar " ).show(); }).ajaxStop( function (){ $( " #background,#progressBar " ).hide(); }); // Disable global events for ajax requests: $. ajax() has a parameter global (default: true) whether to trigger global Ajax events. If set to false, global Ajax events will not be triggered. For example, ajaxStart or ajaxStop can be used to control different Ajax events.


31. How to clone an element in jQuery:

 var cloned = $( ' #somediv ' ).clone();


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

 if ($(element).is( ' :visible ' )) {   // The element is visible  }


33. How to place an element in the center of the screen:

 jQuery.fn.center =  function () {     return  this .each( function (){     $( this ).css({       position: ' absolute ' ,       top, ( $(window).height() -  this .height() ) /  two  + $(window).scrollTop() +  ' px ' ,        left, ( $(window).width() -  this .width() ) /  two  + $(window).scrollLeft() +  ' px '     });   }); } // Use the above function:  $(element).center();

 

34. How to put the values of all elements with a specific name into an array:

 var arrInputValues =  new Array();  $( " input[name='xxx'] " ).each( function (){    arrInputValues.push($( this ).val()); });


35. How to remove HTML from an element

 ( function ($) {  $.fn.stripHtml =  function () {     var regexp =  / <("[^"]*"|'[^']*'|[^'">])*> / gi;     this .each( function () {      $( this ).html( $( this ).html().replace(regexp, '' ) );    });    return $( this );  }  })(jQuery); // Usage:  $( ' p ' ).stripHtml();


36. How to use closest to get the parent element:

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


37. How to use Firebug and Firefox to record jQuery event logs:

 // Allow chained logging  jQuery.log = jQuery.fn.log =  function (msg) {   if (console){      console.log( " %s: %o " , msg, this );    }   return  this ;  }; // Usage:  $( ' #someDiv ' ).hide().log( ' div hidden ' ).addClass( ' someClass ' );


38. How to force a link to open in a 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 be opened in a new tab:

 $( ' a.newTab ' ).live( ' click ' , function (){     var newwindow = window.open( this .href);    $( this ).target =  " _blank " ;     return  false ;  });


40. How to use. siblings() to select peer elements in jQuery

 // No  $( ' #nav li ' ).click( function (){    $( ' #nav li ' ).removeClass( ' active ' );    $( this ).addClass( ' active ' );  }); // The alternative 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 when 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 value of the element matches the entered text, the element will be returned  $( ' .someClass ' ).filter( function () {     return $( this ).attr( ' value ' ) == $( ' input#someId ' ).val();  })


43. How to obtain mouse pad cursor positions 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 method of 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 === ) { return  '' ;} if ( this .charAt( ) === ch) { return  this .substring( one ).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 = ;  i < this .length;  i += one ) { 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) ==  - one ; } });


45. How to standardize the writing of 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

 $( ' #theImage ' ).attr( ' src ' , ' image.jpg ' ).load( function () {    alert( ' This Image Has Been Loaded ' );  });


47. How to use jQuery to specify a namespace for events:

 // Events can bind namespaces like this  $( ' input ' ).bind( ' blur.validation ' , function (e){   // ...  }); // The data method also accepts namespaces  $( ' input ' ).data( ' validation.isValid ' , true );


48. How to check whether cookies are enabled

 var dt =  new Date();  dt.setSeconds(dt.getSeconds() +  sixty );  document.cookie =  " cookietest=1; expires= "  + dt.toGMTString(); var cookiesEnabled = document.cookie.indexOf( " cookietest= " ) !=  - one ; if ( ! cookiesEnabled) {     // Cookies are not enabled  }


49. How to make cookies expire:

 var date =  new Date();  date.setTime(date.getTime() + (x *  sixty  *  one thousand ));  $.cookie( ' example ' , ' foo ' , { expires: date });  


50. How to use a clickable link to replace any URL in the page

 $.fn.replaceUrl =  function () {   var regexp =  / ((ftp|http|https):\/\/(\w+:{0,1}\w*@)? (\S+)(:[0-9]+)? (\/|\/([\w#!:.?+=&%@!\-\/]))?) / gi;   return this .each( function () {      $( this ).html(        $( this ).html().replace(regexp, ' <a href="$1">$1</a>')     );    }); }  //Usage $( ' p ' ).replaceUrl();

 

Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
thirty-eight Collection
four fabulous
 Back to top
Top