In other places you can't learn jquery tips and Tricks (Welcome collection) _jquery

Source: Internet
Author: User

The following small series for everyone to organize 8 tips for programmers is very helpful, as shown in the following:

1) Disable the right mouse button click

jquery programmers can use this code to disable the right mouse click on a Web page.

$ (document). Ready (function () {
//catch The right-click context menu
$ (document). Bind ("ContextMenu", function (e) { 
//warning prompt-optional
alert ("No right-clicking!");
Delete the default context menu, return false;});

2 The use of jquery to adjust the size of the text

With this code, the user can reset the size of the text on the site (increase and decrease)

$ (document). Ready (function () {
//find the current font size
var originalfontsize = $ (' html '). CSS (' font-size ');
//increase The text size
$ (". Increasefont"). Click (function () {
var currentfontsize = $ (' html '). CSS (' Font-size ');
var currentfontsizenumber = parsefloat (Currentfontsize, ten);
var newfontsize = currentfontsizenumber*1.2;
$ (' HTML '). CSS (' font-size ', newfontsize);
return false;
});
Decrease the Text Size
$ (". 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;
});
Reset Font Size
$ (". Resetfont"). Click (function () {
$ (' HTML '). CSS (' font-size ', originalfontsize);
});
});

3 Open links in new windows

Try This code and increase your site impressions because the using this jquery code users and the new window after clicking On any link to your site. Code is below:-

$ (document). Ready (function () {
//select all anchor tags, that have http in the href
//and apply the Target=_blank
   $ ("a[href^= ' http ')"). attr (' target ', ' _blank ');
};

4) Style Sheets Swap

Swap style sheets using this code and the ' style sheets swap ' script is below:-

$ (document). Ready (function () {
$ ("A.cssswap"). Click (function () { 
//swap the link rel attribute with the value in The Rel 
$ (' link[rel=stylesheet] '). attr (' href ', $ (this). attr (' rel '); 
}); 
};

5) back to the top of the link

This is very common function, you can, on eve site nowadays, is ' back to top '. This functionality was very useful for long pages for make-in-a single click. Visit This code below:-

$ (document). Ready (function () {
//when the id= "Top" link is clicked
$ (' #top '). Click (function () {
//scoll The page back to the top
$ (document). Scrollto (0,500);
}
);

6) get the X and y axes of the mouse cursor

You can find the values of X and Y coordinator of mouse pointer. Code is blow:-

$ (). MouseMove (function (e) {
//display the x and Y axis values inside the P element
$ (' P '). html ("x axis:" + E.pag EX + "| Y Axis "+ e.pagey);
}";

7 detect the current mouse coordinates

Using this script, you can find the coordinates of the current mouse in any Web browser that jquery supports. The code is as follows:

$ (document). Ready (function () {
$ (). MouseMove (function (e)
{
$ (' # mousecoordinates '). HTML ("X Axis Position = "+ E.pagex +" and Y Axis Position = "+ E.pagey);
}";

8 Pre-loading pictures in jquery

The pre-loaded script for this image helps to load images or Web pages very quickly. You don't have to wait for the image to load. Code:

Jquery.preloadimagesinwebpage = function () 
{for
(var ctr = 0; ctr<arguments.length; ctr++)
{
JQuery (" 
 

Do the following to guarantee your jquery performance boost

1. Append Outside of Loops

Anything that touches the DOM comes with a price. If you add a lot of elements to the DOM, you'll want to attach them all at once, rather than doing them multiple times. A common problem arises when additional elements are added to the loop.

$.each (myarray, function (I, item) {
var newlistitem = "<li>" + Item + "</li>";
$ ("#ballers"). Append (Newlistitem);

A common technique is to take advantage of document fragments (documents fragment). In each iteration of the loop, the element is appended to the fragment rather than the DOM element. When the loop is finished, append the fragment to the DOM element.

var frag = Document.createdocumentfragment ();
$.each (myarray, function (I, item) {
var newlistitem = document.createelement ("li");
var itemtext = document.createTextNode (item);
Newlistitem.appendchild (itemtext);
Frag.appendchild (Newlistitem);
});

Another simple trick is to keep building a string in each iteration of the loop. When the loop ends, the HTML of the DOM element is set to the string.

var myhtml = "";
$.each (myarray, function (I, item) {
myhtml + = "<li>" + Item + "</li>";
});

Of course there are other techniques you can try. A site called Jsperf provides a good way to test these performance. The site allows you to use benchmarks to test each technique and visualize its cross-platform performance test results.

2. Cache Length During Loops

In the For loop, do not access the length property of the array each time; it should be cached beforehand.

var mylength = myarray.length;
for (var i =; I < mylength. i++) {
//do Stuff

3. Detach Elements to Work with Them

Manipulating the DOM is slow, so you want to minimize alignment. jquery has introduced a method named Detach () in version 1.4 to help solve this problem, allowing you to separate them from the DOM when manipulating elements.

var $table = $ ("#myTable");
var $parent = $table. Parent ();
$table. Detach ();
... add lots and lots of rows to table

4. Don ' t Act on absent Elements

If you're trying to run a lot of code on an empty selector, jquery won't give you any hint-it will continue to execute as if there were no errors. It is up to you to verify how many elements the selector contains.

Bad:this runs three functions before it
//realizes there
$ ("#nosuchthing"). Selection Up ();
Better:
var $mySelection = $ ("#nosuchthing");
if ($mySelection. length) {
$mySelection. Slideup ();
}
Best:add a doonce plugin.
JQuery.fn.doOnce = function (func) {
this.length && func.apply (this);
return this;
}
$ ("Li.cartitems"). Doonce (function () {
//Make it ajax! \o/

This guide is especially useful for jQuery UI widgets that require a lot of overhead when selectors do not contain elements.

5. Optimize Selectors

Selector optimization is not as important as the past, as many browsers implement the Document.queryselectorall () method and jquery shifts the burden of selectors to the browser. But there are still some techniques to keep in mind.

ID-based Selector

It's always best to start with an ID as the selector.

Fast:
$ ("#container div.robotarm");
Super-fast:

Using the. Find () method will be much faster because the first selector has been processed without the need to use the document.getElementById () method to process the Id-only selector, which is fast and is because it is the native method of the browser.

Specificity

Try to describe the right side of the selector as detailed as possible, and do the opposite for the left.

Unoptimized:
$ ("Div.data. Gonzalez");
Optimized:

Try to describe the selector in the Tag.class form at the far right of the selector, while on the left try to use only tag or. class.

Avoid excessive use of specificity

$ (". Data table.attendees Td.gonzalez");
Better:drop the middle if possible.

Trying to curry favor with "DOM" always facilitates the performance of the selector because the selector engine does not need to traverse too much when searching for elements.

Avoid using universal selectors

If a selector explicitly or implicitly implies that it can match within an indeterminate range, it will greatly affect performance.

$ (". Buttons > *"); Extremely expensive.
$ (". Buttons"). Children (); Much better.
$ (". Category:radio"); Implied universal selection.
$ (". Category *:radio"); Same thing, explicit now.

6. Use stylesheets to changing CSS on Many Elements

If you use the. css () method to change more than 20 elements of CSS, you should consider adding a style label to the page as an alternative, which can increase the speed of nearly 60%.

Fine for up to elements, slow following that:
$ ("A.swedberg"). CSS ("Color", "#ad");
Much faster:
$ ("<style type=\" text/css\ ">a.swedberg {color: #ad}</style>")

7. Don ' t Treat jQuery as a black Box

The jquery source code as a document, you can keep it (Http://bit.ly/jqsource) in your favorite folder, often refer to the reference.

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.