jquery technique (must be mastered) _jquery

Source: Internet
Author: User
Tags error handling visibility

Check to see if jQuery is loading

Before you do anything with jQuery, you need to verify that it is loaded:

if (typeof jquery = = ' undefined ') {
console.log (' jquery hasn\ ' t loaded ');
} else {
console.log (' jquery has lo Aded ');
}

Back to top button

Using the animate and ScrollTop methods in JQuery, you can create simple scroll up effects without plug-ins:

Returns the top
$ (' A.top '). Click (function (e) {
e.preventdefault ();
$ (document.body). Animate ({scrolltop:0},);
});
<!--set anchor-->
<a class= "Top" href= "#" >back to Top</a>

Adjust the scrolltop value to change the scrolling landing position. What you actually do is set the document body position continuously within 800 milliseconds until it scrolls to the top.

Pre-loading pictures

If your Web page uses a large number of images that are not immediately visible (such as a hover mouse-triggered picture), it makes sense to preload these images:

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

To determine whether a picture is loaded and completed

In some cases, in order to continue executing the script, you need to check that the picture is fully loaded:

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

Also, you can check whether a particular picture is loaded by using a tag with an ID or class attribute.

Automatically repair failed pictures

If you find an invalid picture link on your site, it will be a chore to replace them one by two. This simple code can greatly ease the pain:

$ (' img '). On (' Error ', function () {
if (!$). Hasclass (' Broken-image ')} {$ (this).
prop (' src ', ' img/ Broken.png '). addclass (' broken-image ');
}
);

Even if you do not have any broken links, adding this code will not have any loss.

Mouse Hover Switch class

If you want to change its visual effects when the user hovers over a clickable element, you can add a class to it when the element is paused, and remove this class when the mouse is no longer hovering:

$ ('. btn '). Hover (function () {
$ (this). addclass (' hover ');
}, Function () {
$ (this). Removeclass (' hover ');
);

If you're looking for a simpler approach, you can use the Toggleclass method, just add the necessary CSS:

$ ('. btn '). Hover (function () {
$ (this). Toggleclass (' hover ');
});

Note: In this case, using CSS may be a faster solution, but it is still worth a little understanding.

Disable input fields

Sometimes, you may want to disable the form's submit button or disable one of the input boxes before the user completes a specific action (for example, by checking the confirmation box for the "I read Regulations"). You can add the disabled attribute to your input field, and then you can enable it when you need it:

$ (' input[type= "submit"]). Prop (' disabled ', true);

You only need to run the prop method again on the input field, but this time change the disabled value to false:

$ (' input[type= "submit"]). Prop (' disabled ', false);

Block link loading

Sometimes you don't want to link to a specific page or reload the current page, but you want them to do something else, such as triggering other scripts. This requires a few articles to prevent the default action:

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

Cache JQuery Selector

Think about how many of the same selectors you've written over and over again in your project. Each $ ('. Element ') must query the entire DOM at once, regardless of whether it has been done so. Instead, we only run the selector once and store the result in a variable:

var blocks = $ (' #blocks '). Find (' Li ');

Now you can use the blocks variable anywhere without querying the DOM every time:

$ (' #hideBlocks '). Click (function () {
blocks.fadeout ();
});
$ (' #showBlocks '). Click (function () {
blocks.fadein ();
});

Caching JQuery's selectors is a simple performance boost.

Toggle Fade Out/Slide

Fade and slide are the effects we use heavily in jQuery. You may just want to show an element after the user clicks it, and the FadeIn and Slidedown methods are perfect. But if you want this element to appear on the first click and disappear when clicked again, this code is useful:

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

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

Simple accordion effect

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

Close all panels
$ (' #accordion '). Find ('. Content '). Hide ();

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

By adding this script, all you really have to do is provide the necessary HTML elements so that it works.

Make two div etc high

Sometimes you want to have the same height regardless of what the two div contains:

$ ('. Div '). css (' Min-height ', $ ('. Main-div '). Height ());

This example sets the min-height, which means that the height can be greater than the main div and not less than it. However, a more flexible approach is to traverse a set of elements and then set the height to the height of the highest element:

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

If you want all columns to be of the same height:

var $rows = $ ('. Same-height-columns ');
$rows. Each (the function () {
$ (this). Find ('. Column '). Height ($ (this). Height ())
;

Open External links in new Tab/New window

Open an external link in a new browser tab or window and make sure that the same source link opens in the same tab or window:

$ (' a[href^= ' http '] '). attr (' target ', ' _blank ');
$ (' a[href^= '//"]). attr (' target ', ' _blank ');
$ (' a[href^= ' + Window.location.origin + ' "]). attr (' target ', ' _self ');

Note: Window.location.origin is not available in IE10. This fix is focused on the problem.

Find elements by text

By using the CONTAINS () Selector of jQuery, you can find the text in the content of the element. If the text does not exist, the element is hidden:

var search = $ (' #search '). Val ();
$ (' Div:not (: Contains ("' + Search + ') '). Hide ();

Triggered when the visibility property changes

Triggers the javasrcipt when the user's focus leaves or returns to a tab page:

$ (document). On (' Visibilitychange ', function (e) {
if (e.target.visibilitystate = = "visible") {
Console.log (' Tab ' now in view! ');
} else if (e.target.visibilitystate = = "hidden") {
console.log (' Tab is now hidden! ');
}
);

Ajax Call error Handling

When an Ajax call returns a 404 or 500 error, the error handler is executed. If error handling is not defined, other jQuery code may no longer be valid. So define a global Ajax error handling:

$ (document). Ajaxerror (function (E, XHR, settings, error) {
console.log (error);
});

Chained plug-in calls

JQuery allows you to mitigate the process of repeatedly querying the DOM and creating multiple JQuery objects by means of a "chained" plug-in. For example, the following code represents your plug-in invocation:

$ (' #elem '). Show ();
$ (' #elem '). html (' bla ');
$ (' #elem '). Otherstuff ();

Through the use of chain operations, there has been significant improvement:

$ (' #elem '). Show
()
. html (' Bla ').
Otherstuff ();

Another approach is to cache elements in a variable (prefixed by $):

var $elem = $ (' #elem ');
$elem. Hide ();
$elem. html (' bla ');
$elem. Otherstuff ();

Both chained operations and cached elements are best practices in jQuery to simplify and optimize your code.

Here are some simple tips to help you play around with JQuery.

Check to see if jQuery is loading

Before you do anything with jQuery, you need to verify that it is loaded:

if (typeof jquery = = ' undefined ') {
console.log (' jquery hasn\ ' t loaded ');
} else {
console.log (' jquery has lo Aded ');
}

Back to top button

Using the animate and ScrollTop methods in JQuery, you can create simple scroll up effects without plug-ins:

Returns the top
$ (' A.top '). Click (function (e) {
e.preventdefault ();
$ (document.body). Animate ({scrolltop:0},);
});
<!--set anchor-->
<a class= "Top" href= "#" >back to Top</a>

Adjust the scrolltop value to change the scrolling landing position. What you actually do is set the document body position continuously within 800 milliseconds until it scrolls to the top.

Pre-loading pictures

If your Web page uses a large number of images that are not immediately visible (such as a hover mouse-triggered picture), it makes sense to preload these images:

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

To determine whether a picture is loaded and completed

In some cases, in order to continue executing the script, you need to check that the picture is fully loaded:

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

Also, you can check whether a particular picture is loaded by using a tag with an ID or class attribute.

Automatically repair failed pictures

If you find an invalid picture link on your site, it will be a chore to replace them one by two. This simple code can greatly ease the pain:

$ (' img '). On (' Error ', function () {
if (!$). Hasclass (' Broken-image ')} {$ (this).
prop (' src ', ' img/ Broken.png '). addclass (' broken-image ');
}
);

Even if you do not have any broken links, adding this code will not have any loss.

Mouse Hover Switch class

If you want to change its visual effects when the user hovers over a clickable element, you can add a class to it when the element is paused, and remove this class when the mouse is no longer hovering:

$ ('. btn '). Hover (function () {
$ (this). addclass (' hover ');
}, Function () {
$ (this). Removeclass (' hover ');
);

If you're looking for a simpler approach, you can use the Toggleclass method, just add the necessary CSS:

$ ('. btn '). Hover (function () {
$ (this). Toggleclass (' hover ');
});

Note: in this case, using CSS may be a faster solution, but it is still worth a little understanding.

Disable input fields

Sometimes, you may want to disable the form's submit button or disable one of the input boxes before the user completes a specific action (for example, by checking the confirmation box for the "I read Regulations"). You can add the disabled attribute to your input field, and then you can enable it when you need it:

$ (' input[type= "submit"]). Prop (' disabled ', true);

You only need to run the prop method again on the input field, but this time change the disabled value to false:

$ (' input[type= "submit"]). Prop (' disabled ', false);

Block link loading

Sometimes you don't want to link to a specific page or reload the current page, but you want them to do something else, such as triggering other scripts. This requires a few articles to prevent the default action:

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

Cache JQuery Selector

Think about how many of the same selectors you've written over and over again in your project. Each $ ('. Element ') must query the entire DOM at once, regardless of whether it has been done so. Instead, we only run the selector once and store the result in a variable:

var blocks = $ (' #blocks '). Find (' Li ');

Now you can use the blocks variable anywhere without querying the DOM every time:

$ (' #hideBlocks '). Click (function () {
blocks.fadeout ();
});
$ (' #showBlocks '). Click (function () {
blocks.fadein ();
});

Caching JQuery's selectors is a simple performance boost.

Toggle Fade Out/Slide

Fade and slide are the effects we use heavily in jQuery. You may just want to show an element after the user clicks it, and the FadeIn and Slidedown methods are perfect. But if you want this element to appear on the first click and then disappear when clicked again, this code is useful:

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

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

Simple accordion effect

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

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

By adding this script, all you really have to do is provide the necessary HTML elements so that it works.

Make two div etc high

Sometimes you want to have the same height regardless of what the two div contains:

$ ('. Div '). css (' Min-height ', $ ('. Main-div '). Height ());

This example sets the min-height, which means that the height can be greater than the main div and not less than it. However, a more flexible approach is to traverse a set of elements and then set the height to the height of the highest element:

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

If you want all columns to be of the same height:

var $rows = $ ('. Same-height-columns ');
$rows. Each (the function () {
$ (this). Find ('. Column '). Height ($ (this). Height ())
;

Open External links in new Tab/New window

Open an external link in a new browser tab or window and make sure that the same source link opens in the same tab or window:

$ (' a[href^= ' http '] '). attr (' target ', ' _blank ');
$ (' a[href^= '//"]). attr (' target ', ' _blank ');
$ (' a[href^= ' + Window.location.origin + ' "]). attr (' target ', ' _self ');

Note: Window.location.origin is not available in IE10. This fix is focused on the problem.

Find elements by text

By using the CONTAINS () Selector of jQuery, you can find the text in the content of the element. If the text does not exist, the element is hidden:

var search = $ (' #search '). Val ();
$ (' Div:not (: Contains ("' + Search + ') '). Hide ();

Triggered when the visibility property changes

Triggers the javasrcipt when the user's focus leaves or returns to a tab page:

$ (document). On (' Visibilitychange ', function (e) {
if (e.target.visibilitystate = = "visible") {
console.log (' Tab is now in view! ');
else if (e.target.visibilitystate = = "hidden") {
console.log (' Tab is now hidden! ');
}
);

Ajax Call error Handling

When an Ajax call returns a 404 or 500 error, the error handler is executed. If error handling is not defined, other jQuery code may no longer be valid. So define a global Ajax error handling:

$ (document). Ajaxerror (function (E, XHR, settings, error) {
console.log (error);
});

Chained plug-in calls

JQuery allows you to mitigate the process of repeatedly querying the DOM and creating multiple JQuery objects by means of a "chained" plug-in. For example, the following code represents your plug-in invocation:

$ (' #elem '). Show ();
$ (' #elem '). html (' bla ');
$ (' #elem '). Otherstuff ();

Through the use of chain operations, there has been significant improvement:

$ (' #elem '). Show
()
. html (' Bla ').
Otherstuff ();

Another approach is to cache elements in a variable (prefixed by $):

var $elem = $ (' #elem ');
$elem. Hide ();
$elem. html (' bla ');
$elem. Otherstuff ();

Both chained operations and cached elements are best practices in jQuery to simplify and optimize your code.

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.