Very useful 12 pieces of jquery code fragment _jquery

Source: Internet
Author: User

jquery offers many ways to create interactive Web sites, and developers should make good use of jquery code when developing Web projects, not only to bring a variety of animations, special effects to the site, but also to improve the user experience of the site.

This article collects 12 very useful pieces of jquery code that you can copy and paste into your code, but ask the developer to be aware of the code reuse. Let's enjoy the charm of the jquery code below.

1. Navigation menu Background Switch effect

In the front page of the project, the active navigation menu needs to set a different background than the other navigation menus. There are a number of ways to implement this effect, and here's a way to implement it using jquery:

<ul id= ' nav ' >
  <li> navigation one </li>
  <li> navigation two </li>
  <li> navigation three </li>
</ul>
/Note: code needs to be modified to perfect
$ (' #nav '). Click (function (e) {
 //To know the use of siblings
$ (e.target). addclass (' Tclass '). Siblings ('. Tclass '). Removeclass (' Tclass ');;
  });

2. Reverse-order access to elements in a jquery object

In some scenarios, we might need to reverse-order access to the page element objects that were fetched through the jquery selector, how does this happen? Look at the following code:

 To master the Get method of the jquery object and the reverse method of the array,
var arr = $ (' #nav '). Find (' Li '). (). reverse ();
$.each (Arr,function (index,ele) {
   ...
 });

3. Visit the elements in the IFRAME

In most cases, the IFRAME is not a good solution, but for a variety of reasons, the project does use an IFRAME, so you need to know how to access the elements in the IFRAME

var iframedom = $ ("Iframe#someid"). Contents ();
You can then iterate through the Find method to get the elements in the IFRAME
iframedom.find (". Message"). Slideup ();

4. Manage the value of the search box

Now each major site has a search box, and the search box usually has a default value, when the input box to get focus, the default value disappears. Once the input box loses focus and the input box does not enter a new value, the value in the input box reverts to the default value, and if a new value is entered into the input box, the value of the input box is the value of the new input. This special effect is easy to implement with jquery:

$ ("#searchbox")
  . Focus (Function () {$ (this). Val (')}]
  . blur (function () {
    var $this = $ (this);
   ' Please search ... ' is the default value for the search box
   ($this. val () = = ") $this. Val (' Please search ... '): null;
 });

5. Partial-page load update

In order to improve the performance of the web, we usually do not load the entire page when there is an update, but only update some of the page content, such as the delay loading of the picture. The page-partially refreshed effects are also easy to implement in jquery:

SetInterval (function () {  //Refresh page content
   //get content every 5 seconds will be added to the element with ID content
   $ ("#content"). Load (URL);
 5000);

6. Using the data method to cache

In a project, to avoid repeated requests for data to the server, the acquired data is usually cached for subsequent use. jquery enables you to gracefully implement this feature:

 var cache = {};
 $.data (Cache, ' key ', ' value '); Cache data
 //Fetch data
 $.data (cache, ' key ');

7. Configuration of jquery and other library compatibility

If using jquery,$ in your project is the most commonly used variable name, but jquery is not the only library that uses $ as a variable name, to avoid naming conflicts, you can organize your code in the following ways:

Method One: Rename jQuery to $j

var $j = jquery.noconflict ();
$j (' #id ') .... 
Method Two: The recommended mode

(function ($) {
  $ (document). Ready (function () {
    //here, you can use jquery syntax normally
  });
(JQuery);

8. Clone table header to the bottom of the table

To make the table more readable, we can clone the header information from the table to the bottom of the table, which is easy to achieve through jquery:

var $tfoot = $ (' <tfoot></tfoot> '); 
$ (' thead '). Clone (True, True). Children (). get (). Reverse ()). each (function () {
  $tfoot. Append ($ (this));
};
$tfoot. InsertAfter (' table thead ');

9. Create a full screen width and height (width/height) div according to the window (viewport)

The following code completely allows you to create a Full-screen div based on viewport. This is useful for displaying modal or dialog boxes under different window sizes:

$ (' #content '). css ({'
  width ': $ (window). Width (),
  ' height ': $ (window). Height (),
});
Make sure Div stays full width/height on resize
$ (window). Resize (function () {
  var $w = $ (window);
  $ (' #content '). css ({
   ' width ': $w. Width (),
   ' height ': $w. Height (),
  });
});

10 Strength of the test password

In some Web site registration will often be required to set the password, the site will also be based on the character characteristics of the input password to give the corresponding prompts, such as short password, poor strength, moderate strength, strong strength and so on. How does this happen? Look at the following code:

<input type= "password" name= "pass" id= "pass"/> <span "id=" ></span>//The following regular expression suggest you collect Oh, There may be a need for $ (' #pass ') on the project. KeyUp (function (e) {//password is eight digits and above and alphanumeric special character three items all include var Strongregex = new RegExp ("^"? =.{
 8,}) (? =.*[a-z]) (? =.*[a-z]) (? =.*[0-9]) (? =.*\\w). *$ "," G "); The password is seven digits and above and there are two items in the letter, number, special character three, the intensity is medium var Mediumregex = new RegExp ("^" =.{ 7,}) ((? =.*[a-z]) (? =.*[a-z]) | ( (? =.*[a-z]) (? =.*[0-9]) | ((? =.*[a-z]) (? =.*[0-9])).
   *$ "," G "); var Enoughregex = new RegExp (? =.{
   6,}). * "," G ");
   if (false = = Enoughregex.test ($ (this). val ())} {$ (' #passstrength '). html (' more Characters ');
       else if (Strongregex.test (). Val ()) {$ (' #passstrength '). ClassName = ' OK ';
   $ (' #passstrength '). html (' strong! ');
       else if (Mediumregex.test (). Val ()) {$ (' #passstrength '). ClassName = ' alert ';
   $ (' #passstrength '). html (' medium! ');
       else {$ (' #passstrength '). ClassName = ' ERROR ';
   $ (' #passstrength '). html (' weak! '); } return TRue });

11. Redraw the size of a picture using jquery

Redrawing the size of the picture, you can do it on the server, or you can do it on the client via jquery.

$ (window). Bind ("Load", function () {
   //IMAGE RESIZE
   $ (' #product_cat_list img '). each (function () {
     var MaxWidth =;
     var maxheight =;
     var ratio = 0;
     var width = $ (this). width ();
     var height = $ (this). Height ();
     if (Width > maxwidth) {
      ratio = maxwidth/width;
      $ (this). CSS ("width", maxwidth);
      $ (this). CSS ("height", height * ratio);
      Height = height * ratio;
     }
     var width = $ (this). width ();
     var height = $ (this). Height ();
     if (height > maxheight) {
      ratio = maxheight/height;
      $ (this). CSS ("height", maxheight);
      $ (this). CSS ("width", width * ratio);
      width = width * ratio;
     }
   });
   $ ("#contentpage img"). Show ();
   IMAGE RESIZE
});

12. Dynamically load page content when scrolling

Some Web page content is not loaded at once, but in the mouse scrolling down dynamically loaded, this is how to do it? Look at the following code:

var loading = false;
$ (window). Scroll (function () {
 if ((($ (window). scrolltop () +$ (window). Height ()) +250) >=$ (document). Height ()) {
   if (loading = = False) {
      loading = true;
      $ (' #loadingbar '). CSS ("Display", "block");
      $.get ("load.php?start=" +$ (' #loaded_max '). Val (), function (loaded) {
        $ (' body '). Append (loaded);
        $ (' #loaded_max '). Val (parseint (' #loaded_max '). Val ()) +50);
        $ (' #loadingbar '). CSS ("display", "none");
        loading = false;};}}}
);
$ (document). Ready (function () {
 $ (' #loaded_max '). val;
};

The above content is small to share the very useful 12 pieces of jquery code snippets, the need for friends can be used directly.

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.