Write Better jQuery Code for Your Project

0
6404
Write Better jQuery Code for Your Project

Programming-visual

jQuery, the cross-platform JavaScript library designed to simplify the client-side scripting of HTML, is used by over 80 per cent of the 10,000 most popularly visited websites. jQuery is free open source software which has a wide range of uses. In this article, the author suggests some best practices for writing jQuery code.

This article aims to explain how to use jQuery in a rapid and more sophisticated manner. Websites focus not only on backend functions like user registration, adding new friends or validation, but also on how their Web pages will get displayed to the user, how their pages will behave in different situations, etc. For example, doing a mouse-over on the front page of a site will either show beautiful animations, properly formatted error messages or interactive hints to the user on what can be done on the site.
jQuery is a very handy, interactive, powerful and rich client-side framework built on JavaScript. It is able to handle powerful operations like HTML manipulation, events handling and beautiful animations. Its most attractive feature is that it works across browsers. When using plain JavaScript, one of the things we need to ensure is whether the code we write tends towards perfection. It should handle any exception. If the user enters an invalid type of value, the script should not just hang or behave badly. However, in my career, I have seen many junior developers using plain JavaScript solutions instead of rich frameworks like jQuery and writing numerous lines of code to do some fairly minor task.
For example, if one wants to write code to show the datepicker selection, on onclick event in plain Javascript, the flow is:

  1. For onclick event create one div element.
  2. Inside that div, add content for dates, month and year.
  3. Add navigation for changing the months and year.
  4. Make sure that, on first client, div can be seen, and on second client, div is hidden; and this should not affect any other HTML elements. Just creating a datepicker is a slightly more difficult task and if this needs to be implemented many times in the same page, it becomes more complex. If the code is not properly implemented, then making modifications can be a nightmare.
    This is where jQuery comes to our rescue. By using it, we can show the datepicker as follows:
$(“#id”).datepicker();

That’s it! We can reuse the same code multiple times by just changing the id(s); and without any kind of collision, we can show multiple datepickers in the same page. That is the beauty of jQuery. In short, by using it, we can focus more on the functionality of the system and not just on small parts of the system. And we can write more complex code like a rich text editor and lots of other operations. But if we write jQuery code without proper guidance and proper methodology, we end up writing bad code; and sometimes that can become a nightmare for other team members to understand and modify for minor changes.
Developers often make silly mistakes during jQuery code implementation. So, based on some silly mistakes that I have encountered, here are some general guidelines that every developer should keep in mind while implementing jQuery code.
General guidelines for jQuery

1. Try to use ‘’this’’ instead of just using the id and class of the DOM elements. I have seen that most developers are happy with just using $(‘#id’) or $(‘.class’) everywhere:

//What developers are doing:
$(‘#id’).click(function(){
var oldValue = $(‘#id’).val();
var newValue = (oldValue * 10) / 2;
$(‘#id’).val(newValue);
});

//What should be done: Try to use more $(this) in your code.
$(‘#id’).click(function(){
$(this).val(($(this).val() * 10) / 2);
});

2. Avoid conflicts: When working with a CMS like WordPress or Magento, which might be using other JavaScript frameworks instead of jQuery, you need to work with jQuery inside that CMS or project. Then use the noConflicts of jQuery.

var $abc = jQuery.noConflict();
$abc(‘#id’).click(function(){
//do something
});

3. Take care of absent elements: Make sure that the element on which your jQuery code is working/manipulating is not absent. If the element on which your code manipulates is dynamically added, then first find it, if that element is added on DOM.

$(‘#divId’).find(‘#someId’).length

This code returns 0 if there isn’t an element with ‘someId’ found; else it will return the total number of elements that are inside ‘divId’.
4. Use proper selectors and try to use more ‘find()’, because find can traverse DOM faster. For example, if we want to find content of #id3…

//demo code snippet
<div id=’#id1’>
<span id=’#id2’></span>
<div class=’divClass’>Here is the content.</div>
</div>

//developer generally uses
var content = $(‘#id1 .divClass’).html();

//the better way is [This is faster in execution]
var content = $(‘#id1’).find(‘div.divClass’).html();

5. Write functions wherever required: Generally, developers write the same code multiple times. To avoid this, we can write functions. To write functions, let’s find the block that will repeat. For example, if there is a validation of an entry for a text box and the same gets repeated for many similar text boxes, then we can write a function for the same. Given below is a simple example of a text box entry. If the value is left empty in the entry, then function returns 0; else, if the user has entered some value, then it should return the same value.

//Javascript
function doValidation(elementId){
//get value using elementId
//check and return value
}

//simple jQuery
$(“input[type=’text’]”).blur(function(){
//get value using $(this)
//check and return value
});

//best way to implement
//now you can use this function easily with click event also
$.doValidation = function(){
//get value
//check and return value
};

$(“input[type=’text’]”).blur($.doValidation);

6. Object organisation: This is another thing that each developer needs to keep in mind. If one bunch of variables is related to one task and another bunch of variables is related to another task, then get them better organised, as shown below:

//bad way
var disableTask1 = false;
var defaultTask1 = 5;
var pointerTask1 = 2;
var disableTask2 = true;
var defaultTask2 = 10;
var currentValueTask2 = 10;
//like that many other variables


//better way
var task1 = {
disable: false,
default: 5,
pointer: 2,
getNewValue: function(){
//do some thing
return task1.default + 5;
}
};

var task2 = {
disable: true,
default: 10,
currentValue: 10
};

//how to use them
if(task1.disable){
//do some thing…
return task1.default;
}

7. Use of callbacks: When multiple functions are used in your code and if the second function is dependent on the effects of the first output, then callbacks are required to be written.

For example, task2 needs to be executed after completion of task1, or in other words, you need to halt execution of task2 until task1 is executed. I have noticed that many developers are not aware of callback functions. So, they either initialise one variable for checking [like mutex in the operating system] or set a timeout for execution. Below, I have explained how easily this can be implemented using callback.

//Javascript way

task1(function(){
task1();
});

function task1(callback){
//do something
if (callback && typeof (callback) === “function”) {
callback();
}
}

function task2(callback){
//do something
if (callback && typeof (callback) === “function”) {
callback();
}
}

//Better jQuery way
$.task1 = function(){
//do something
};

$.task2 = function(){
//do something
};

var callbacks = $.Callbacks();
callbacks.add($.task1);
callbacks.add($.task2);
callbacks.fire();

8. Use of ‘’each’’ for iteration: The snippet below shows how each can be used for iteration.

var array;
//javascript way
var length = array.length;
for(var i =0; i<length; i++){
var key = array[i].key; 
// like wise fetching other values.
}

//jQuery way
$.each(array, function(key, value){
alert(key);
});

9. Don’t repeat code: Never write any code again and again. If you find yourself doing so, halt your coding and read the eight points listed above, all over again.
Next time I’ll explain how to write more effective plugins, using some examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here