18 very good jquery code snippets _jquery

Source: Internet
Author: User

1, jquery implementation of the inner link smooth scrolling
do not need to use too complex plug-ins, as long as the use of download this code can be implemented based on internal link smooth scrolling

$ (' a[href^= ' #] '). Bind (' Click.smoothscroll ', function (e) {
e.preventdefault ();
 
var anchor = This.hash,
$target = $ (target);
 
$ (' HTML, Body '). Stop (). Animate ({
' scrolltop ': $target. Offset (). Top
},, ' Swing ', function () {
Window.location.hash = anchor;
};
 
});

2. Use jquery to get all the nodes

var $element = $ (' #gbtags ');
 var $nodes = $element. Contents ();
 $nodes. each (function () {
  If This.nodetype = 3 && $.trim ($ (this). Text ()) {
  $ (). Wrap (');
 }
});

3, limit the selection of selection box number

$ ("#categories option"). Click (function (e) {if (). (). (). ().
 val (). length < 2) {
  $ (this). removeattr ("selected");
 }
);

4. jquery uses wildcard characters to remove class

var _c = ' Your-icon-class '
 
$ ('. Currency '). Removeclass (function (index, CSS) {return
 (css.match ) || []). Join (');
}). AddClass (' icon-' +_c);

5. Toggle Enable and disable

/* HTML
|
|
<input type= "text" value= "Welcome access www.admin10000.com"/><input "button" type= "Disable button" value=
|
|
*
 
///Plugin
(function ($) {
 $.fn.toggledisabled = function () {return
  This.each (function () {
   var $this = $ (this);
   if ($this. attr (' disabled ')) $this. Removeattr (' disabled ');
   Else $this. attr (' disabled ', ' disabled ');
  });
 }
(jQuery);
 
TEST
$ (function () {
 $ (' Input:button '). Click (function () {
  $ (' Input:text '). toggledisabled ();
 });
});

6, smooth scrolling back to the top

7, using jquery and Google Analytics to track the form

var array1 = [];
$ (document). Ready (function () {
 $ (' input '). Change (function () {
  var Formbox = $ (this). attr (' id ');
  Array1.push (Formbox);
  Console.log ("You filled out box" + array1);
 });
 $ (' #submit '). Click (function () {
  console.log (' tracked ' + array1);
  Alert (' This is the order of boxes your filled out: ' + array1);
  _gaq.push ([' _trackevent ', ' Form ', ' Completed ', ' "' + array1 + '" ');
 });
};

8, the super simple password strength hint

$ (' #pass '). KeyUp (function (e) {
 var strongregex = new RegExp ("^"? =.{ 8,}) (? =.*[a-z]) (? =.*[a-z]) (? =.*[0-9]) (? =.*\w). *$ "," G ");
 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 ($ (this). 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;
});

9. jquery generates an automatic dock page end effect

//window Load event used just in case window ' is dependant upon images $ (Window). Bi
 nd ("Load", function () {var footerheight = 0, footertop = 0, $footer = $ ("#footer");
 
 Positionfooter ();
  function Positionfooter () {footerheight = $footer. Height ();
  Footertop = ($ (window). scrolltop () + $ (window). Height ()-footerheight) + "px";
/* Debugging Console.log ("Document Height:", $ (document.body). Height ());
Console.log ("Window height:", $ (window). Height ());
Console.log ("Window Scroll:", $ (window). scrolltop ());
Console.log ("Footer height:", footerheight);
Console.log ("Footer top:", footertop);
   */if (($ (document.body). Height () + footerheight) < $ (window). Height ()) {$footer. css ({position: "absolute"
  ). Stop (). Animate ({top:footertop});
  else {$footer. css ({position: "static"});
} $ (window). Scroll (positionfooter). Resize (positionfooter);
}); 

10. Prevent 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;
 }
});

11, image and other proportional 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
});

12, the mouse sliding when the gradual and out

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

13, the production of high columns

var max_height = 0;
$ ("Div.col"). each (the function () {
 if ($ (this). Height () > max_height) {max_height = $ (this). Height ();}
});
$ ("Div.col"). Height (max_height);

14. Pre-loading picture

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

15, get the parameters passed in the URL

$.urlparam = function (name) {
 var results = new RegExp (' [\\?&] ' + name + ' = ([^&#]*) '). EXEC ( WINDOW.LOCATION.HREF);
 if (!results) {return 0;}
 return Results[1] | | 0;
}

16, disable the form of ENTER key submit

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

17, so that the entire div can be clicked

<div class = "Mybox" > 
 < a href = "http://www.jb51.net" > Www.jb51.net </a>
</div > 
 
$ (". Mybox"). Click (function () {
 window.location=$ (this). Find ("a"). attr ("href");
 return false;
});

18, open the link in the new window (target= "blank")

$ (' a[@rel $= ' External ']. Click (function () {
   this.target = "_blank";
});

You can combine the previous small compiled articles to learn, the practical jquery code fragments are summarized for later learning to use.

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.