WEB front end development should know jquery tips and jquery three abbreviations

  • 2020-11-03 22:02:33
  • OfStack

A collection of simple tips to help you improve your jQuery skills. So far this site has rounded up 14 jquery tips.

The directory structure

1 Back to top button
2. Pre-load image
3. Check whether the picture has been loaded
Automatic repair of damaged pictures
Class switch on 5Hover
6 Disable the input field
Stop link loading
Fade in and fade out/slide switch
Simple folding effect
Set both Div to the same height
Open external links in a new window
12 Find the text element
Toggle visible and hidden triggers

Here's what each tip means.

1. Go back to top button

By using the animate and scrollTop methods in jQuery, you can create a simple back to top animation without a plug-in:


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

Change the value of scrollTop to where you want scrollbar to stop. And then what you do is, you set it to go back to the top in 800 milliseconds.

2. Pre-load images

If your page USES a lot of images that are not initially visible (such as bound to hover), preloading them is 10 points 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 whether the picture has been loaded

Sometimes you may want to check that the image is fully loaded before you can do anything else in the script:


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

You can also check that a particular image has been loaded by replacing the img tag with ID or class.

4. Automatically repair damaged pictures

If you find that the link to your website's image is down, it's a hassle to replace it one by one. This simple piece of code can help a lot:


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

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

5. Class switch on Hover

If the user hovers over a clickable element on a page, you want to change the visual appearance of that element. You can use this code to add an class to the element when the user hovers over it. Remove this class when the user mouse away:


 $('.btn').hover(function () {
 $(this).addClass('hover');
 }, function () {
 $(this).removeClass('hover');
 });

You only need to add CSS as necessary. If you need a simpler approach, you can also use the toggleClass method:


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

Note: CSS may be a faster solution to this example, but it's still worth knowing.

Disable the input field

Sometimes you might want to make the form's submit button or its text entry box unavailable until the user performs a specific action (such as a check box to confirm that "I read this item"). Add disabled attribute to your input to achieve the desired effect:


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

When you want to change the value of disabled to false, simply run the prop method once more on that input.


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

7. Stop link loading

Sometimes you don't want to link to a page or reload it, but you want to be able to do something else, such as trigger another script. Here's a tip for disabling default behavior:


 $('a.no-link').click(function (e) {
 e.preventDefault();
 });

Fade in and out/slide switch

Fade-in and fade-out and sliding are the animations we often make with jQuery. Maybe you just want to show an element when a user clicks on something. Both fadeIn and slideDown are great. But if you want the element to appear on the first click and disappear on the second, the following code does the job nicely:


// Fade
 $('.btn').click(function () {
 $('.element').fadeToggle('slow');
 });
// Toggle
$('.btn').click(function () {
 $('.element').slideToggle('slow');
});

9. Simple accordion effect

This is a quick  accordion effect of simple method:


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

After adding this script, all you need to do is check to see if the script is working properly in the required HTML.

10. Make both Div heights 1 the same

Sometimes you might want both div to have the same height, no matter what's in them:


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

This example sets ES126en-ES127en, meaning it can be larger than the main div, but can never be smaller. But there is a more flexible approach is to traverse the 1 set of  element set, then put the high peak in the set for the element:


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

If you want all columns to have the same height:


$.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

11. In a new TAB/window open  inbound links

Open the external link in a new TAB or window and make sure that the in-site link opens in the same TAB or window:


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

Note: window.location.origin is not available in IE 10, the repair method for issue.

12. Find elements through text

You can find the text in an element by using the contains() selector in jQuery. If the text does not exist, the element will be hidden:


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

Visual change triggers

JavaScript is triggered when the user focuses on, or returns to, another tag:


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

Error handling for the Ajax call

Error handling is performed when an Ajax call returns a 404 or 500 error. But if this processing is not defined, the rest of the jQuery code may stop working. You can define a global Ajax error handling using this code:


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

14. Plugin chain call

jQuery supports chain-called plug-ins to slow down repeated queries on 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 chaining:


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

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


var $elem = $('#elem');
 $elem.hide();
 $elem.html('bla');
 $elem.otherStuff();

The chain operation and caching methods in jQuery greatly simplify and speed up the code.

Here are three abbreviations for the jquery tip

The terse way of writing is as follows:

Short for object

In the past, if you wanted to create an object, you would have to:


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

The same effect can be achieved by writing:


var car = { 
colour:'red', 
wheels:4, 
hubcaps:'spinning', 
age:4 
}

This is much easier, and you don't have to use the name of the object over and over again.
So car is defined, and maybe you'll run into problems with invalidUserInSession, which you'll only run into when you use IE, just remember the one point, don't put a semicolon in front of your curly braces, and you won't have trouble.

Short for array

The traditional way to define an array is this:


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

Here's the short version:


var moviesThatNeedBetterWriters = [
  'Transformers','Transformers2','Avatar','Indiana Jones 4']; 

The problem with arrays is that they don't really have a graph group. But you'll often find people defining car above like this:


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

Arrays aren't everything; It's confusing to write it incorrectly. Graph groups are actually functions of objects, and people confuse the two concepts.

Shorthand notation for a 3 - element condition

Another cool way to abbreviate is to use the three - element conditional notation.
You don't have to write it like this:


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

You can simplify this by using the 3 element conditional notation:


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

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


Related articles: