35 jQuery tips on Web Front-end and webjquery tips

Source: Internet
Author: User

35 jQuery tips on Web Front-end and webjquery tips

1. Right-click prohibited
$ (Document). ready (function (){
$ (Document). bind ("contextmenu", function (e ){
Return false;
});
});

2. Hide text in the search text box
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 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). ready (function (){
// Example 1: Every link will open in a new window
$ ('A [href ^ = "http: //"] '). attr ("target", "_ blank ");
// Example 2: Links with the rel = "external" attribute will only open in a new window
$ ('A [@ rel $ = 'external'] '). click (function (){
This.tar get = "_ blank ";
});
});
// How to use
<A href = "http://www.opensourcehunter.com" rel = external> open link </a>

4. Check the browser
Note: In jQuery 1.4, $. support replaced 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-load images
This piece of code will prevent the loading of all images, which can be 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 attribute
$ ('Link [rel = stylesheet] '). attr ('href', $ (this). attr ('rel '));
});
// How to use
// Place this in your header
<LINK rel = stylesheet type = text/css href = "default.css">
// The links
<A href = "#" relatedefault.css> Default Theme </A>
<A href = "#" relatered.css> Red Theme </A>
<A href = "#" relw.blue.css> Blue Theme </A>
});

7. The column height is the same
If two CSS columns are used, the height of the two columns can be the same.
$ (Document). ready (function (){
Function compute height (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 "));
Raise height ($ (". right "));
});
});

8. dynamically control the page font size. You can change the 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, 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 * = #] '). click (function (){
If (location. pathname. replace (/^ //, '') = this. pathname. replace (/^ //,'')
& Amp; 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
<A name = top> </A>
// The link
<A href = "# top"> go to top </A>
});

10. Obtain the XY value of the mouse pointer.
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 the id XY
Certificate ('{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 the animation at the top, without using other plug-ins.
// 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 scrollTop value can adjust the return distance from the top, while the second parameter of animate is the time required to execute the Return Action (unit: milliseconds ).

12. Pre-load images
If your page uses a lot of invisible images (such as hover display), you may need to pre-load 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 image is loaded.
Sometimes you need to make sure that the image is loaded to perform the following operations:
$ ('Img '). load (function (){
Console. log ('image load successful ');
});
You can replace img with another ID or class to check whether the specified image is loaded.

14. Automatically modify damaged Images
If you happen to find broken image links on your website, you can replace them with images that are not easy to replace. Adding this simple code can save a lot of trouble:
$ ('Img '). on ('error', function (){
$ (This). prop ('src', 'img/broken.png ');
});
Even if your website does not have broken image links, adding this code is harmless.

15. hover the mouse over (hover) to switch the class attribute
If you want to change the effect when hovering over a clickable element, the following code adds the class attribute when hovering over the element, when you move the mouse away, the class attribute is automatically canceled:
$ ('. Btn'). hover (function (){
$ (This). addClass ('hover ');
}, Function (){
$ (This). removeClass ('hover ');
});
You only need to add necessary CSS code. If you want more concise code, you can use the toggleClass method:
$ ('. Btn'). hover (function (){
$ (This). toggleClass ('hover ');
});
Note: directly using CSS to achieve this effect may be a better solution, but you still need to know this method.

16. Disable the input field
Sometimes you may need to disable the form's submit button or an input field until the user performs some operations (for example, check the "read terms" check box ). You can add the disabled attribute until you want to enable it:
$ ('Input [type = "submit"] '). prop ('Disabled', true );
All you need to do is execute the removeAttr method and pass the attribute to be removed as a parameter:
$ ('Input [type = "submit"] '). removeAttr ('Disabled ');

17. Stop link Loading
Sometimes you don't want to link to a page or reload it. You may want it to do something else or trigger some other scripts. You can do this:
$ ('A. no-link'). click (function (e ){
E. preventDefault ();
});

18. Switch between fade and slide
Fade and slide are the animation effects we often use in jQuery. They can make the element display better. However, if you want to use the first effect when the element is displayed and the second effect when it disappears, you can do this:
// Fade
$ ('. Btn'). click (function (){
$ ('. Element'). fadeToggle ('low ');
});
// Toggle
$ ('. Btn'). click (function (){
$ ('. Element'). slideToggle ('low ');
});

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 ('quick ');
$ ('. Content'). not (next). slideUp ('quick ');
Return false;
});

20. Make the two divs have the same height
Sometimes you need to make the two divs have the same height regardless of the content in them. You can use the following code snippet:
Var $ columns = $ ('. column ');
Var height = 0;
$ Columns. each (function (){
If ($ (this). height ()> height ){
Height = $ (this). height ();
}
});
$ Columns. height (height );
This code loops through a group of elements and sets their height to the maximum height in the element.

21. verify whether the element is null
This will allow you to check if an element is empty.
$ (Document). ready (function (){
If ((('your id'}.html ()){
// Do something
}
});

22. Replace Element
$ (Document). ready (function (){
$ ('# Id'). replaceWith ('
<DIV> I have been replaced </DIV>
');
});

23. jQuery delayed Loading Function
$ (Document). ready (function (){
Window. setTimeout (function (){
// Do something
},1000 );
});

24. Remove words
$ (Document). ready (function (){
Var el = $ ('# id ');
El.html(el.html (). replace (/word/ig ,""));
});

25. verify whether the element exists in the jquery object set
$ (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>

});

27. Conversion between ID and Class
When the Window size is changed, 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. Clone object
$ (Document). ready (function (){
Var cloned = $ ('# id'). clone ();
// How to use
<DIV id = id> </DIV>

});

29. Place elements in the center 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 (){
Return $ (a). width ()> 1000;
}
});
$ ('. Box: moreThen1000px'). click (function (){
// Creating a simple js alert box
Alert ('the element that you have clicked is over 1000 pixels wide ');
});
});

31. count the number of elements
$ (Document). ready (function (){
$ ("P"). size ();
});

32. Use your own Bullets
$ (Document). ready (function (){
$ ("Ul"). addClass ("Replaced ");
$ ("Ul> li"). prepend ("success ("‒");
// How to use
Ul. Replaced {list-style: none ;}
});

33. Reference The Jquery class library on the Google host (Google cannot use it, but Baidu CDN can be used)
// 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 Solution with other Javascript Class Libraries
$ (Document). ready (function (){
Var $ jq = jQuery. noConflict ();
$ Jq ('# id'). show ();
});

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.