jQuery tips

jQuery tips

Today I want to share with you some jQuery tips you should know. I recognize that I am stopping using jQuery, but I am sure this article helps lots of people.

Preload images
If you have lot of images that are not visible in the screen, you can preload them to improve performance. For example:

$.preload = function () {
  for (var i = 0; i < arguments.length; i++) {
    $('<img>').attr('src', arguments[i]);
  }
};

$.preload('path/to/image.jpg', 'path/to/anotherimage.jpg');

Check if images are loaded
This is very useful to add some animation when the image is loaded.

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

Check if jQuery loaded
Probably this is the easiest of all, but sometimes is very useful.

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

Fix broken images
You can find useful to change broken images for another to prevent UX problems.

$('img').on('error', function () {
  if(!$(this).hasClass('is-broken')) {
    $(this).prop('src', 'path/to/broken-image.png').addClass('is-broken');
  }
});

The importance of cache selectors
It has no sense repeating the same selector in the same function. You can prevent lots of searching DOM elements if you set the selector to a variable, and use it in all cases.

var menuItems = $('.menu li'); //All the menu items

$('.button-close').on('click', function() {
  menuItems.hide(); //Instead of $('.menu li').hide();
});

$('.button-open').on('click', function() {
  menuItems.show(); //Instead of $('.menu li').show();
});

Find elements by text
The contains() search the text inside an element.

$('div:not(:contains("example"))').hide();

Trigger on visibility change
Trigger JavaScript when the user is no longer focusing on a tab, or refocuses on a tab:

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

Chaining
jQuery allows the chaining to prevent repeating calls to the DOM. For example:

$('.example1').hide();
$('.example1').addClass('example2);
$('.example1').find('div').show();

You can change it for:

$('.example1').hide();
.addClass('example2);
.find('div').show();