jquery tips and jquery three shorthand _jquery for Web front-end development

Source: Internet
Author: User
Tags error handling

A collection of simple tips to help you improve your jQuery skills. At present, small series for everyone to organize 14 jquery tips.

Directory structure

1 Back to top button
2 Pre-loading pictures
3 Check whether the picture is loaded
4 Automatic repair of damaged pictures
The class switch on the 5Hover
6 Disabling the input field
7 Stop Link loading
8 Fade/Slide switch
9 Simple folding effect
10 set two Div to the same height
11 Open External links in new window
12 Find text elements
13 toggle between visible and hidden triggers

Here are a few tips for each of the specific meaning.

1. Back to the top of the button

By using the animate and ScrollTop methods in JQuery, you can create a simple return to the top animation without a plugin:

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

Change the value of the scrolltop to where you want the scrollbar to stop. And then all you have to do is set it back to the top in 800 milliseconds.

2. Pre-loading pictures

If your page uses a large number of images that cannot be initially visible (such as binding on hover), it is useful to preload them:

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

3. Check whether the picture is loaded

Sometimes you might want to check that the picture is completely loaded before you can follow up in the script:

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

You can also check whether a particular picture is loaded by replacing the IMG tag with an ID or class.

4. Automatic repair of damaged pictures

If you find yourself on the site of the picture link hanging up, one replacement is very troublesome. This simple piece of code can be a huge help:

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

Even if you don't have any broken links, adding this code won't have any effect.

Class switch on 5.Hover

If the user's mouse hovers over a clickable element on the page, you want to change the visual representation of the element. You can use this code to add a class to the element when the user hovers, and then remove the class when the user leaves the mouse:

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

You only need to add CSS. If you need a simpler way, you can also use the Toggleclass method:

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

Note: CSS may be a quicker way to solve this example, but it's still worth knowing.

6. Disable input fields

Sometimes you might want to make the form's submit button or its text input box unavailable until the user performs a specific behavior (such as confirming the check box "I have read this clause"). Add disabled attribute to your input, you can achieve the desired effect:

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

When you want to change the value of disabled to false, you only need to run the prop method again on that input.

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

7. Stop link Loading

Sometimes you don't want the link to jump to a page or reload the page, and you want to do something else, such as triggering other scripts. The following code is a trick to prevent default behavior:

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

8. Fade/Slide Switch

Fade and slide are animations that we often use with jQuery. Maybe you just want to show an element when a user clicks on something, and it's great to use FadeIn and Slidedown. But if you want the element to appear on the first click and disappear the second time, the following code can do the job well:

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

9. 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;
 });

After adding this script, all you need to do is to see if the script works in the necessary HTML.

10. Make two Div height

Sometimes you might want to have two div with the same height, regardless of what's inside it:

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

This example sets the min-height, which means it can be larger than the main Div, but never smaller. But there is a more flexible way to traverse a set of elements and then set the height to the highest value in the 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 have the same height:

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

11. Open Outbound links in new tabs/Windows

Open an external link in a new tab or a new window, and make sure that the inbound link opens in the same label 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 IE 10, the issue repair method.

12. Find elements by text

By using the CONTAINS () selector in JQuery, you can find the text in an element. If the text does not exist, the element will be hidden:

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

13. Visual Change Trigger

Triggers JavaScript when the user focus is on another label, or when it is returned to the label:

 $ (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! ');
 }
 );

Error handling for Ajax calls

When an Ajax call returns a 404 or 500 error, error handling is performed. But if the processing is not defined, other jQuery code may stop working. You can define a global Ajax error handling by following this code:

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

14. Plug-in Chain call

JQuery supports chained invocation plug-ins to slow down the query DOM repeatedly and create multiple jquery objects. Look at the following sample code:

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

The above code, can be greatly improved by chain operation:

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

There is another way to cache elements in a variable (prefixed by $):

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

The chain operation and caching methods in JQuery are greatly streamlined and speed up the code.

Here are three short jquery tips

The concise wording is as follows:

Abbreviations for objects

In the past, if you want to create an object, you need to do this:

var car = new Object (); 
Car.colour = ' red '; 
Car.wheels = 4; 
Car.hubcaps = ' spinning '; 
Car.age = 4;

The following writing can achieve the same effect:

var car = { 
colour: ' Red ', 
wheels:4, 
hubcaps: ' Spinning ', 
age:4 
}

This is much simpler, and you don't have to use the name of the object over and over again.
So the car is defined, maybe you will encounter invaliduserinsession problems, which only you will encounter when using IE, as long as you remember, do not write a semicolon in front of the right curly braces, you will not have trouble.

Shorthand for arrays

The traditional way of defining arrays is this:

var moviesthatneedbetterwriters = new Array (
  ' Transformers ', ' Transformers2 ', ' Avatar ', ' Indiana Jones 4 ');

The shorthand version is this:

var moviesthatneedbetterwriters = [
  

For arrays, there is a problem, but there is no graph group function. But you'll often find someone who defines the car on top like this:

var car = new Array (); 
car[' colour '] = ' red '; 
Car[' wheels '] = 4; 
car[' hubcaps '] = ' spinning '; 
car[' age ' = 4;

arrays are not omnipotent; it's confusing to write wrong. The graph group is actually the function of the object, people confuse these two concepts.

Shorthand for ternary conditional symbols

Another very cool shorthand method is to use the ternary conditional notation.
You don't have to write the following:

var direction; 
if (x < MB) { 
  direction = 1; 
}
else { 
  direction =-1; 
}

You can use the ternary conditional notation to simplify it:

var direction = x < 200? 1:-1;

When the condition is true, take the value following the question mark, or the value after the colon.

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.