15 jquery Code Snippets for direct use _jquery

Source: Internet
Author: User

Published a "10 Super useful PHP code fragment decisive collection"? This article will continue to give you 15 of super useful jquery code Snippets.

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.

Let's enjoy the charm of the jquery code below.

1. Pre-loading pictures

(function ($) { 
 var cache = []; 
 Arguments are image paths relative to the current page. 
 $.preloadimages = function () { 
  var args_len = arguments.length; 
  for (var i = Args_len; i--;) { 
   var cacheimage = document.createelement (' img '); 
   CACHEIMAGE.SRC = Arguments[i]; 
   Cache.push (cacheimage); 
  } 
Jquery.preloadimages ("Image1.gif", "/path/to/image2.png"); 

2. Make each element of the page suitable for display on mobile devices

var scr = document.createelement (' script '); 
Scr.setattribute (' src ', ' https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js '); 
Document.body.appendChild (SCR); 
Scr.onload = function () { 
  $ (' div '). attr (' class ', '). attr (' id ', '). css ({ 
    ' margin ': 0, 
    ' padding ': 0, 
    ' Width ': ' 100% ', 
    ' clear ': ' Both ' 
  }; 

3. Image Scaling

$ (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 

4. Return to the top of the page

Back to top 
$ (document). Ready (function () {  
 $ ('. Top '). Click (function () {  
   $ (document). Scrollto (0,500);  
 }) ; 
});  
Create a link defined with the class. Top 
<a href= ' # ' class= ' top ' >back to top</a> 

5. Use jquery to create accordion folding effect

var accordion = { 
   init:function () { 
      var $container = $ (' #accordion '); 
      $container. Find (' Li:not (: i) details '). Hide (); 
      $container. Find (' Li:first '). addclass (' active '); 
      $container. On (' Click ', ' Li a ', function (e) { 
         e.preventdefault (); 
         var $this = $ (this). Parents (' Li '); 
         if ($this. Hasclass (' active ')) { 
             if ('. Details '). Is (': Visible ') 
                } {$this. Find ('. Details '). Slideup (); 
             } else { 
                $this. Find ('. Details '). Slidedown (), 
             } 
         } else { 
             $container. Find (' li.active details '). Slideup (); 
             $container. Find (' Li '). Removeclass (' active '); 
             $this. addclass (' active '); 
             $this. Find ('. Details '). Slidedown (); 
         } 
    

6. Use the previous image in the gallery to mimic the way Facebook pictures are displayed

var nextimage = "/images/some-image.jpg"; 
$ (document). Ready (function () { 
window.settimeout (function () { 
var img = $ (""). attr ("src", nextimage). Load ( function () { 
//all done 
}); 
}, 100; 

7. Automatically populate the selection box with jquery and Ajax

$ (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 + = ' 
+ j[i].optiondisplay + ' 
; 
} 
$ ("Select#ctlperson"). html (options); 
} 
) 

8. Automatically replace the missing picture

Safe Snippet 
$ ("img"). Error (function () { 
  $ (this). Unbind ("Error"). attr ("src", "missing_image.gif"); 
}); 
//Persistent snipper 
$ ("img"). Error (function () { 
  $ (this). attr ("src", "missing_image.gif"); 

9. Show fade/fade effects in mouse hover

$ (document). Ready (function () { 
  $ (". Thumbs img"). Fadeto ("slow", 0.6);//This sets the opacity of the thumbs to Fade Dow N to 60% when the page loads 
  $ (". Thumbs img"). Hover (function () { 
    $ (this). Fadeto ("Slow", 1.0);//this should set th e opacity to 100% on hover 
  },function () { 
    $ (a). Fadeto ("slow", 0.6);//This should set the opacity back to 60% O n mouseout 
  }); 

10. Clear the form data

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

11. Prevention of multiple submissions of forms

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

12. Dynamically adding form elements

Change event in Password1 field to prompt new input 
$ (' #password1 '). Change (function () { 
    //dynamically Create New input and insert after Password1 
    $ ("#password1"). Append (""); 

13. Let the entire Div clickable

blah blah blah. Link the following lines of JQuery to make the 
entire div clickable: $ (". Mybox"). Click (function () {window.location=$ (this). Find ("a"). attr ("href"); return false; });  

14. Balance Height or div element

var maxheight = 0; 
$ ("div"). each (the function () { 
  if ($ (this). Height () > maxheight) {maxheight = $ (this). Height ();} 
}); 
$ ("div"). Height (maxheight); 

15. Automatically load content as the window scrolls

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 (50); 

This collection of 15 pieces of very useful jquery snippets, you can copy and paste into the code directly, but please note to the developer, to understand the code reuse OH.

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.