Home>

A collection of simple tricks,Help you improve your jquery skills. At present we have organized 14 jquery tips for everyone.

Directory Structure

1Back to top button

2 preloaded pictures

3 check if the picture is loaded

4 Automatically repair damaged pictures

5hover class switch

6Disable the input field

7 stop link loading

8 fade in/out switch

9 simple folding effects

10Set two divs to the same height

11Open external link in new window

12 find text elements

13 toggle between visible and hidden triggers

Here are the specific meanings of each tip.

1.Back to top button

By using the animate and scrolltop methods in jquery, you can create a simple back-to-top animation without a plugin:

//back to top
 $("a.top"). click (function (e) {
 e.preventdefault ();
 $(document.body) .animate ((scrolltop:0}, 800);
 });
 <!-Create an anchor tag->
 <a href="#">back to top</a>

Change the value of scrolltop to where i want the scrollbar to stop.Then all you have to do is,Set back to top in 800 ms.

2. Preloaded pictures

If your page uses a lot of images that are not initially visible (such as binding to hover), preloading them is useful:

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

3. Check if the picture is loaded

Sometimes you may want to check if the image is completely loaded,In order to follow up in the script:

$("img"). load (function () {
 console.log ("image load successful");
});

You can also check if a particular image is loaded by replacing the img tag with an id or class.

4. Automatically repair damaged pictures

If you find that your website ’s image link is hanging,One by one replacement is troublesome.This simple code can help a lot:

$("img"). on ("error", function () {
 $(this) .prop ("src", "img/broken.png");
});

Even if you do n’t have any broken links,Adding this code will have no effect.

5.hover class switch

If the user ’s mouse hovers over a clickable element on the page,You want to change the visual appearance of this element.You can use the following code,When the user hovers,Add a class to the element;remove the class when the user leaves the mouse:

$(". btn"). hover (function () {
 $(this) .addclass ("hover");
 }, function () {
 $(this) .removeclass ("hover");
 });

You just need to add the necessary css. If an easier way is needed,You can also use the toggleclass method:

$(". btn"). hover (function () {
 $(this) .toggleclass ("hover");
});

Note:css may be a faster solution for this example,But it's still worth knowing.

6. Disable the input field

Sometimes you might want to make a form's submit button or its text input box unavailable,Until the user performs a specific action (such as confirming the checkbox for "I have read the terms"). Add the disabled attribute to your input to achieve the effect i want:

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

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

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

7. Stop link loading

Sometimes you do n’t want links to jump to a page or reload the page,And hopefully can do something else,Such as triggering other scripts.The following code is a little trick to disable the default behavior:

$("a.no-link"). click (function (e) {
 e.preventdefault ();
 });

8. Fade In/Fade Out/Slide Switch

Fade in and slide out are animation effects that we often use jquery to make.Maybe you just want to show an element when a user clicks on something,Both fadein and slidedown are great. But if i want the element to appear on the first click,Disappears on second click,The following code does the job well:

//fade
 $(". btn"). click (function () {
 $(". element"). fadetoggle ("slow");
 });
//toggle
$(". btn"). click (function () {
 $(". element"). slidetoggle ("slow");
});

9. Simple Accordion Effect

This is an easy way to quickly 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,See if the script works in the required html.

10. Make two divs the same height

Sometimes you might want two divs to have the same height,No matter what they contain:

(".div"). css ("min-height", $(". main-div"). height ());

This example sets min-height, meaning it can be larger than the main div, but it can never be smaller.But there is a more flexible way to iterate through the settings of a group of elements,Then set the height to the highest value in the element:

var $columns=$(". column");
 var height=0;
 $columns.each (function () {
 if ($(this) .height ()&height;{
 height=$(this) .height ();
 }
 });
 $columns.height (height);

If i want all columns to have the same height:

var $rows=$(". same-height-columns");
 $rows.each (function () {
 $(this) .find (". column"). height ($(this) .height ());
});

11.Open in new tab/window

Open an external link in a new tab or window,And make sure that the site link will open 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 ie 10,The fix for this issue.

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

When the user focuses on another tab,Or back to the label,Triggering javascript:

$(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 process is not defined,Other jquery code may stop working.You can define a global ajax error handler with the following code:

$(document) .ajaxerror (function (e, xhr, settings, error) {
 console.log (error);
 });

14. Plug-in chaining

jquery supports chained call plugins,To slow iterative querying of the dom and create multiple jquery objects. Look at the following example 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,Cache the element in a variable (prefixed by $):

var $elem=$("#elem");
 $elem.hide ();
 $elem.html ("bla");
 $elem.otherstuff ();

chained operations and caching methods in jquery,Both greatly streamline and speed up the code.

Here are three abbreviations for jquery tips

The succinct wording is as follows:

Shorthand for object

In the past, if i wanted to create an object,You need 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,You don't need to use the name of this object repeatedly.

Then car is defined.Maybe you will encounter the problem of invaliduserinsession, this is only you will encounter when using ie,Just keep in mind,Don't put a semicolon before the closing brace,You won't have trouble.

Shorthand for array

The traditional way to define an array is this:

var moviesthatneedbetterwriters=new array (
  "transformers", "transformers2", "avatar", "indiana jones 4");

The short version is this:

var moviesthatneedbetterwriters=[
  "transformers", "transformers2", "avatar", "indiana jones 4"];

For arrays,There is a problem here,In fact, there is no graph group function.But you will often find that someone defines the car above like this:

var car=new array ();
car ["colour"]="red";
car ["wheels"]=4;
car ["hubcaps"]="spinning";
car ["age"]=4;

Arrays are not a panacea;This is incorrectConfusing.Graph groups are actually functions of objects,People confuse these two concepts.

Shorthand for ternary conditional symbols

Another very cool shorthand way is to use ternary conditional notation.

You don't have to write it like this:

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

You can simplify it using the ternary conditional notation:

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

Take the value after the question mark when the condition is true,Otherwise take the value after the colon.

  • Previous Talking about the implementation of objects in JavaScript and Promise objects
  • Next PHP uses redis to implement statistical caching mysql pressure method