Web front end 35 jquery tips!

Source: Internet
Author: User

Nonsense do not say direct code, there are problems can communicate together

1. Disable right click on $ (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 found below in the comment fields) $ (document). Ready (function () {$ ("Input.text1"). Val ("Enter Your search Te   XT 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 the link in a new window XHTML 1.0 Strict doesn ' t allow this attribute in the code, so use this to keep the code valid.$ (document). Read   Y (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 open in a new window $ (' a[@rel $= ' external ']. Click (function () {this.target = "_blank"; });});/ /How to Use<a href= "http://www.opensourcehunter.com" Rel=external>open link</a>4. Detect Browser Note: In version jquery 1.4, $.support replaced the $.browser variable $ (document). Ready (function () {//Target Firefox 2 and Aboveif ($.browser . Mozilla && $.browser.version >= "1.8") {//Do something}//Target safariif ($.browser.safari) {//do S omething}//Target Chromeif ($.browser.chrome) {//Do something}//Target caminoif ($.browser.camino) {//Do Somethi ng}//Target Operaif ($.browser.opera) {//do something}//Target IE6 and belowif ($.browser.msie && $.browser.     Version <= 6) {//do something}//Target anything above ie6if ($.browser.msie && $.browser.version > 6) { Do something}}); 5. Preload picture This piece of code would prevent the loading of all images, which can is useful if you had 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 switch $ (document). Ready (function () {$ ("A.styleswitcher"). Click (function () {//SWICTH the LINK REL attribute    With the value of A REL attribute $ (' link[rel=stylesheet] '). attr (' href ', $ (this). attr (' REL ')); });//How to use//place the 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 to use$ (document). Ready (function () {Equalheight ($ (". Left")); EqualheigHT ($ (". Right"));}); 8. Dynamic control page font size The user can change the page font size by $ (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, 10);    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, 10);    var newfontsize = currentfontsizenum*0.8;    $ (' HTML '). CSS (' font-size ', newfontsize);  return false; });}); 9. Return to the top of the page for a smooth (animated) ride back to the top (or any location). $ (document). Ready (function () {$ (' a[href*=#] '). CLI CK (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 to use//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 the cursor is?$ (document). Ready (function () {$ (). MouseMove (function (e) {//display The x and Y axis values inside the div with the ID XY $ (' #XY '). HTML ("x axis:" + E.pagex + "|  Y Axis "+ e.pagey); });//How to Use<div id=xy></div>}); 11. Return to the top button you can use animate and scrolltop to return to the top of the animation without the need for other plugins.  Back to top$ (' A.top '). Click (function () {$ (document.body). Animate ({scrolltop:0}, 800); return false;});<!--Create an anchor tag--><a href= ' # ' >back to top</a> changing the value of scrolltop can be adjusted to return the distance from the top, while Animate's second parameter is the execution Returns the time, in milliseconds, that the action takes. 12. Preload pictures If you use a lot of invisible images in your page (such as: hover display), you may need to preload them: $.preloadimages = function () {for (var i = 0; i < arguments.length ;  i++) {$ ('  '). attr (' src ', arguments[i]); }};$.preloadimages (' img/hover1.png ', ' img/hover2.png '); 13. Check whether the picture is loaded or not, sometimes you need to make sure that the picture is finished loading to do the following: $ (' img '). Load ( function () {console.log (' Image load successful ');}); You can replace IMG with another ID or class to check that the specified picture is loaded. 14. Automatic modification of damaged images if you happen to find broken image links on your website, you can replace them with an image that is not easy to replace. Adding this simple code can save a lot of hassle: $ (' img '). On (' Error ', function () {$ (this). Prop (' src ', ' img/broken.png ');}); Even if your site does not have broken image links, adding this code is harmless. 15. Hover (hover) Toggle Class Property If you want to change the effect when the user hovers over a clickable element, the following code can add the class attribute when it hovers over the element, and automatically cancels the class attribute when the user mouse leaves: $ ('.  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 for this effect may be a better solution, but you still need to know the method. 16. Disable the input field sometimes you may want to disable the form's submit button or an input field until the user performs certain actions (for example, checking 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 in the property you want to remove as a parameter: $ ( ' input[type= '). 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 that you can do: $ (' A.no-link '). Click (function (e) {E.preventdefault ();}); 18. Switching between Fade/slidefade and slide is an animated effect that we often use in jQuery to make the elements appear better. But if you want the element to display with the first effect, and disappear with the second effect, you can do this://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 heightsThe same, regardless of how much content they contain.    You can use the following code snippet: var $columns = $ ('. Column '), var height = 0; $columns. each (function () {if ($ () () () () () () () () () () () () () () () ()  Height = $ (this). Height (); }); $columns. Height (height); This code loops through a set of elements and sets their height to the highest in the element. 21. Verify that the element is empty this would allow you to check if a element is empty.$ (document). Ready (function () {if ($ (' #id '). HTML ()) {/ /Do something}}); 22. Replace element $ (document). Ready (function () {$ (' #id '). ReplaceWith (' <div>i has been replaced</div> ');}); The jquery delay-loading feature $ (document). Ready (function () {window.settimeout () () {//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 in $ (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 th E URL window.location=$ (this). Find ("a"). attr ("href"); return False; });//How to Use<div><a href= "index.html" &GT;HOME&LT;/A&GT;&LT;/DIV&GT;}); 27. Conversion between ID and class when changing the window size, switch $ (document) between ID and class. Ready (function () {function checkwindowsize () {if (window). Widt    H () > () {$ (' body '). addclass (' large ');    } else {$ (' body '). Removeclass (' large '); }}$ (window). Resize (checkwindowsize);}); 28. Clone object $ (document). Ready (function () {var cloned = $ (' #id '). Clone ();//How to Use<div id=id></div>}); 29.      Causes the element to 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 clicked I  s over-pixels wide '); });}); 31. Number of statistics elements $ (document). Ready (function () {$ ("P"). Size ();});   32. Use your own bullets$ (document). Ready (function () {$ ("ul"). AddClass ("replaced"); $ ("ul > Li"). Prepend ("?"); /How to Useul. replaced {List-style:none;}}); 33. Refer to the jquery Class library on Google host (Google cannot use, can use Baidu Cdn)//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) <script type=text/javascript src=" Http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js "></script>34. Disables JQuery (animation) effect $ (document). Ready (function () {JQuery.fx.off = true;}); 35. With other JAVASCRipt Class Library conflict resolution $ (document). Ready (function () {var $jq = jquery.noconflict (); $JQ (' #id '). Show ();});


Web front end 35 jquery tips!

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.