10 jQuery Tips and Tricks for Developers

By Focusoncode May 23, 2018

We will look some jQuery techniques which will be useful for your use of the library.

1)Use noConflict()

The $ used by jQuery is also used by other libraries in Javascript. Using noConflict() method makes sure that jQuery doesn’t conflict with $ object of other libraries.

jQuery.noConflict();

You can refer the jQuery object using jQuery variable name instead of $. If you have multiple version of jQuery on the same page, you can use noConflict()  to set an alias to a specific version:

let $x = jQuery.noConflict();

2) Use delay() for Animations

 

Chaining animation effects is a powerful tool in every jQuery developer’s toolbox. One of the more overlooked features is that you can introduce delays between animations.

$('#elem').animate({width:200},function(){

setTimeout(function(){

$('#elem').animate({marginTop:100});

},2000);

});



// Do it like this:

$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});


3) Local Storage and jQuery

Local storage is a dead simple API for storing information on the client side. Simply add your data as a property of the global localStorage object:

localStorage.someData = "This is going to be saved
 across page refreshes and browser restarts";

The bad news is that it is not supported in older browsers. This is where you can use one of the many jQuery plugins that provide different fallbacks if localStorage is not available, which makes client-side storage work almost everywhere.

Here is an example using the $.jStorage jQuery plugin

// Check if "key" exists in the storage

var value = $.jStorage.get("key");

if(!value){

// if not - load the data from the server

value = load_data_from_server(); // and save it

$.jStorage.set("key",value); }

4) jQuery Objects as Arrays

The result of running a selector is a jQuery object. However, the library makes it appear as if you are working with an array by defining index elements and a length.

// Selecting all the navigation buttons:

var buttons = $('#navigation a.button');

// We can loop though the collection:

for(var i=0;i<buttons.length;i++){

console.log(buttons[i]);    // A DOM element, not a jQuery object

}

// We can even slice it:

var firstFour = buttons.slice(0,4);

5) The Selector Property

jQuery provides a property which contains the selector that was used to start the chain.

$('#container li:first-child').selector // #container li:first-child

$('#container li').filter(':first-child').selector //#container li.filter(:first-child)
 

Although the examples above target the same element, the selectors are quite different. The second one is actually invalid – you can’t use it as the basis of a new jQuery object. It only shows that the filter method was used to narrow down the collection.

6) Create an Empty jQuery Object

Creating a new jQuery object can bring significant overhead. Sometimes, you might need to create an empty object, and fill it in with the add() method later.

var container = $([]);
container.add(another_element);

7) Select a Random Element

As I mentioned above, jQuery adds its own selection filters. As with everything else in the library, you can also create your own. To do this simply add a new function to the $.expr[‘:’] object. One awesome use case was presented by Waldek Mastykarz on his blog: creating a selector for retrieving a random element. You can see a slightly modified version of his code below:

(function($){

var random = 0;

$.expr[':'].random = function(a, i, m, r) {

if (i == 0) {

random = Math.floor(Math.random() * r.length);

}

return i == random;

};

&nbsp;

})(jQuery);

&nbsp;

// This is how you use it:

$('li:random').addClass('glow');

 

8) Use Custom Easing Functions

You have probably heard of the jQuery easing plugin by now – it allows you to add effects to your animations. The only shortcoming is that this is another JavaScript file your visitors have to load. Luckily enough, you can simply copy the effect you need from the plugin file, and add it to the jQuery.easing object:

$.easing.easeInOutQuad = function (x, t, b, c, d) {

if ((t/=d/2) < 1) return c/2*t*t + b;

return -c/2 * ((--t)*(t-2) - 1) + b;

};

&nbsp;

// To use it:

$('#elem').animate({width:200},'slow','easeInOutQuad');

9) The $.proxy()

One of the drawbacks to using callback functions in jQuery has always been that when they are executed by a method of the library, the context is set to a different element. For example, if you have this markup:

<div id="panel" style="display:none">
<button>Close</button>
</div>

And you try this code:

$('#panel').fadeIn(function(){

// this points to #panel $('#panel button').click(function(){

// this points to the button $(this).fadeOut();

});

});

 

You will run into a problem – the button will disappear, not the panel. With $.proxy, you can write it like this:

$('#panel').fadeIn(function(){

// Using $.proxy to bind this:

&nbsp;

$('#panel button').click($.proxy(function(){

// this points to #panel

$(this).fadeOut();

},this));

});

Which will do what you expect. The $.proxy function takes two arguments – your original function, and a context. It returns a new function in which the value of this is always fixed to the context.

10) Determine the Weight of Your Page

A simple fact: the more content your page has, the more time it takes your browser to render it. You can get a quick count of the number of DOM elements on your page by running this in your console:

console.log($('*').length);
 

The smaller the number, the faster the website is rendered. You can optimize it by removing redundant markup and unnecessary wrapping elements.

Share This

Leave a Comment

Your email address will not be published.