Programmer must know 35 jquery code fragments _jquery

Source: Internet
Author: User
Tags hash

jquery is now the most popular JavaScript library in web development, with jquery and a large number of plug-ins, you can easily achieve a variety of gorgeous effects. This article will introduce you to some of the practical techniques of jquery, hopefully to help you use jquery more efficiently.

Collect 35 JQuery Tips/snippets that can help you develop quickly.

1. No Right click

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

2. Hide Search text box text

Hide when clicked in the Search field, the value. (example can be found below in the comment fields)
$ (document). Ready (function () {
$ ("Input.text1"). Val ("Enter Your search text here");
  Textfill ($ (' input.text1 ')
  ); function Textfill (input) {//input focus text function
   var originalvalue = Input.val ();
   Input.focus (function () {
     if ($.trim (Input.val ()) = = OriginalValue) {input.val (');}
   });
   Input.blur (function () {
     if ($.trim (Input.val ()) = = ') {input.val (OriginalValue);}}
   );
}

3. Open a link in a new window

The XHTML 1.0 Strict doesn ' t allow this attribute in the code, and so, the code keep.
$ (document). Ready (function () {
  //example 1:every Link would open in a new window
  $ (' a[href^= ' http://"]"). attr (" Target "," _blank ");
  Example 2:links with the rel= "external" attribute would only be open in a new window
  $ (' a[@rel $= ' External ']). Click (Fun Ction () {
   this.target = "_blank";
  });
};
How to use
<a href= "http://www.opensourcehunter.com" Rel=external>open link</a>

4. Detection browser

Note: In version jquery 1.4, $.support replaces the $.browser variable

$ (document). Ready (function () {
//Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8") {
  //do something
}
//Target Safari
if ($.browser.safari) {
  //do something
}
Target Chrome
if ($.browser.chrome) {
  //do something
}
//target Camino
if ($. Browser.camino) {
  //do something
}
//Target Opera
if ($.browser.opera) {
  //do something
}
Target IE6 and below
if ($.browser.msie && $.browser.version <= 6) {
  //do something
}
/ /Target Anything above IE6
if ($.browser.msie && $.browser.version > 6) {
  //do something
}
   });

5. Pre-loading pictures

This piece of code would prevent the loading of all images, which can is useful if you have a site with lots of images.
   
    $ (document). Ready (function () {
jquery.preloadimages = function ()
{for
 (var i = 0; i<arguments. LENGTH; JQuery (? ). attr ("src", arguments[i]);
 }
How to use
$.preloadimages ("image1.jpg");
};
   

6. Page Style Switching

$ (document). Ready (function () {
  $ ("A.styleswitcher"). Click (function () {
    //swicth the LINK REL attribute with The value in A REL attributes
    $ (' link[rel=stylesheet] '). attr (' href ', $ (this). attr (' REL ');
  });
your header
<link rel=stylesheet type=text/css href= "Default.css" >//
The links
<a href= "#" Rel=default.css>default theme</a>
<a href= "#" rel=red.css>red Theme </A>
<a href= "#" Rel=blue.css>blue theme</a>
});

7. Column height is the same

If you use two CSS columns, this can be the same height as the two columns.

$ (document). Ready (function () {
function equalheight (group) {
  tallest = 0;
  Group.each (function () {
    Thisheight = $ (this). Height ();
    if (Thisheight > tallest) {
      tallest = Thisheight;
    }
  });
  Group.height (tallest);
}
How do you
$ (document). Ready (function () {
  equalheight ($ (". Left"));
  Equalheight ($ (". Right"));};

8. Dynamically control page Font size

User can change page font size

$ (document). Ready (function () {
 //Reset the font size (back to default)
 var originalfontsize = $ (' html '). CSS (' Font-size ');
  $ (". Resetfont"). Click (function () {
  $ (' HTML '). CSS (' font-size ', originalfontsize);
 });
 Increase the font size (bigger font0
 $ (". Increasefont"). Click (function () {
  var currentfontsize = $ (' html '). CSS (' font-size ');
  var currentfontsizenum = parsefloat (Currentfontsize, ten);
  var newfontsize = currentfontsizenum*1.2;
  $ (' HTML '). CSS (' font-size ', newfontsize);
  return false;
 });
 Decrease the font size (smaller font)
 $ (". Decreasefont"). Click (function () {
  var currentfontsize = $ (' HTML ') . css (' font-size ');
  var currentfontsizenum = parsefloat (Currentfontsize, ten);
  var newfontsize = currentfontsizenum*0.8;
  $ (' HTML '). CSS (' font-size ', newfontsize);
  return false;
 });


9. Return to the top of the page function

For a smooth (animated) ride, or any location).
$ (document). Ready (function () {
$ (' a[href*=#] '). Click (function () {
 if (location.pathname.replace (/^\//, ') = = This.pathname.replace (/^\//, ')
 && location.hostname = = this.hostname) {
  var $target = $ (This.hash) ;
  $target = $target. Length && $target
  | | $ (' [name= ' + this.hash.slice (1) + '] ');
  if ($target. length) {
 var targetoffset = $target. Offset (). Top;
 $ (' html,body ')
 . Animate ({Scrolltop:targetoffset}, 900);
  return false;}}
 );
How do I//place this
where you want to scroll to
<a name=top></a>
//the link
<a href= "#top" >go to Top</a>
});

10. Get the mouse pointer xy value

Want to know where your mouse cursor is?
$ (document). Ready (function () {
  $ (). MouseMove (function (e) {
   //display the x and Y axis values inside the div with th E ID XY
  $ (' #XY '). HTML ("X Axis:" + E.pagex + "| Y Axis "+ e.pagey);
 }";
How to use
<div id=xy></div>
});

11. Return Top button

You can use animate and scrolltop to achieve a return to the top of the animation, without the need to use other plug-ins.

Back to top
$ (' A.top '). Click (function () {
 $ (document.body). Animate ({scrolltop:0},);
 return false;
});
<!--Create a anchor tag-->
<a href= "#" >back to Top</a>

Changing the value of the scrolltop adjusts the distance from the top of the return distance, while the second parameter of animate is the time (in milliseconds) it takes to perform the return action.

12. Pre-loading pictures

If you use a lot of invisible images on your page (such as the hover display), you may want to preload them:

$.preloadimages = function () {
 for (var i = 0; i < arguments.length; i++) {
  $ ('  '). attr (' src ', argum Ents[i]);
 }
;
$.preloadimages (' img/hover1.png ', ' img/hover2.png ');

13. Check whether the picture is loaded and complete

Sometimes you need to make sure that the picture finishes loading to perform the following actions:

$ (' img '). Load (function () {
 console.log (' Image load successful ');
});

You can replace the IMG with another ID or class to check whether the specified picture is loaded.

14. Automatic modification of damaged images

If you happen to find a broken image link on your site, you can replace it with an image that is not easily replaced. Adding this simple code can save you a lot of trouble:

$ (' img '). On (' Error ', function () {
 $ (this). Prop (' src ', ' img/broken.png ');
});

Even if your site does not have a broken image link, adding this code does no harm.

15. Mouse hover (hover) Toggle Class attribute

If you want to change the effect when the user hovers over a clickable element, the following code adds the class attribute when it hovers over the element, and automatically cancels the class attribute when the user leaves the mouse:

$ ('. btn '). Hover (function () {
 $ (this). addclass (' hover ');
 }, Function () {
  $ (this). Removeclass (' hover ');
 );
You just need to add the necessary CSS code. If you want more concise code, you can use the Toggleclass method:
$ ('. btn '). Hover (function () { 
 $ (this). Toggleclass (' hover '); 
});

Note: Using CSS directly to implement this effect may be a better solution, but you still need to know the method.

16. Disable input fields

Sometimes you may want to disable the Submit button for the form or an input field until the user performs some action (for example, check the Read terms check box). You can add the disabled property until you want to enable it:

$ (' input[type= "submit"]). Prop (' disabled ', true);
All you have to do is execute the Removeattr method and pass the attribute to be removed as a parameter:
$ (' input[type= "submit"]). Removeattr (' disabled ');

17. Block Link Loading

Sometimes you don't want to link to a page or reload it, you might want it to do something else or trigger some other script, you can do this:

$ (' A.no-link '). Click (function (e) {
 e.preventdefault ();
});

18. Switch Fade/slide

Fade and slide are the animations we often use in jQuery to make the elements appear better. But if you want the element to display with the first effect and the second effect when it disappears, you can do so:

Fade
$ ('. btn '). Click (function () {
 $ ('. Element '). Fadetoggle (' slow ');
});
Toggle
$ ('. btn '). Click (function () {
 $ ('. Element '). Slidetoggle (' slow ');
});

19. Simple Accordion Effect

This is a quick and easy way to achieve the accordion effect:

Close all panels
$ (' #accordion '). Find ('. Content '). Hide ();
Accordion
$ (' #accordion '). Find ('. Accordion-header '). Click (function () {
 var next = $ (this). Next ();
 Next.slidetoggle (' fast ');
 $ ('. Content '). Not (next). Slideup (' fast ');
 return false;
});

20. Make two DIV heights the same

Sometimes you need to make two Div heights the same, regardless of how much content they contain. You can use the following code fragment:

var $columns = $ ('. column ');
var height = 0;
$columns. each (function () {
 if ($). Height () > height) {
  height = $ (this). Height ();
 }
});
$columns. Height (height);

This code loops through a set of elements and sets them to the maximum height in the element.

21. Verify that the element is empty

This would allow you to check if a is empty.
$ (document). Ready (function () {
 if ($ (' #id '). HTML ()) {
  //do Something
  }
});

22. Replace elements

$ (document). Ready (function () {
  $ (' #id '). ReplaceWith ('
<div>i have been replaced</div>
') );
});

jquery time-Delay loading function

$ (document). Ready (function () {
  window.settimeout (function () {
   //do something
  }, 1000);

24. Remove Word function

$ (document). Ready (function () {
  var el = $ (' #id ');
  El.html (el.html (). Replace (/word/ig, ""));

25. Verify that the element exists in the JQuery object collection

$ (document). Ready (function () {
  if ($ (' #id '). Length) {
 //do Something
 }
});

26. Make the entire DIV clickable

$ (document). Ready (function () {
  $ ("div"). Click (function () {
   //get the URL from href attribute and launch the URL
   window.location=$ (this). Find ("a"). attr ("href"), return false;
  });
How to use
<div><a href= "index.html" >home</A></DIV>
});

Convert between ID and class

When changing the window size, switch between ID and class

$ (document). Ready (function () {
  function checkwindowsize () {
  if ($ (window). Width () > 1200) {
    $ (' body '). AddClass (' large ');
  }
  else {
    $ (' body '). Removeclass (' large ');
  }
$ (window). Resize (checkwindowsize);
});

28. Cloning objects

$ (document). Ready (function () {
  var cloned = $ (' #id '). Clone ();
How to use
<div id=id></div>
});

29. Make the element reside in the middle of the screen

$ (document). Ready (function () {
 jQuery.fn.center = function () {
   this.css ("position", "absolute");
   This.css ("Top", ($ (window). Height ()-this.height ())/2+$ (window). scrolltop () + "px");
   This.css ("Left", ($ (window). Width ()-this.width ())/2+$ (window). ScrollLeft () + "px");
   return this;
 }
 $ ("#id"). Center ();

30. Write your own selector

$ (document). Ready (function () {
  $.extend ($.expr[': '), {
    morethen1000px:function (a) {return
      $ (a). Width ( ) > 1000;
   }
  );
 $ ('. box:morethen1000px '). Click (function () {
   //Creating a simple JS alert box
   alert (' The element so you have CLI Cked is over 1000 pixels wide ');
 };

31. Number of statistical elements

$ (document). Ready (function () {
  $ ("P"). Size ();
});

32. Use your own bullets

$ (document). Ready (function () {
  $ ("ul"). AddClass ("replaced");
  $ ("ul > Li"). Prepend ("\u2012");
 How to use
 ul. replaced {list-style:none}
});

33. Refer to the jquery Class library on Google mainframe

Example 1
<script src= "Http://www.google.com/jsapi" ></SCRIPT>
<script type=text/ javascript>
google.load ("jquery", "1.2.6");
Google.setonloadcallback (function () {
  //do something
});
</script><script type=text/javascript src= "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/ Jquery.min.js "></SCRIPT>
 //Example 2: (The best and fastest way)
<script type=text/javascript src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" ></SCRIPT>

34. Disable jquery (animation) effects

$ (document). Ready (function () {
  JQuery.fx.off = true;
});

35. Conflict resolution with other JavaScript class libraries

$ (document). Ready (function () {
  var $jq = jquery.noconflict ();
  $JQ (' #id '). Show ();

The above content is small make up to share the programmer must know 35 jquery code fragment, Hope everybody likes.

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.