Write Better jQuery Code for the project
jQuery, the cross-platform JavaScript library designed to simplify the client-side scripting of HTML, is used by over 80 percent 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, and how their pages will behave in different situations.
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.
Table of Contents
Why jQuery is Useful
jQuery is a convenient, interactive, powerful, and rich client-side framework built on JavaScript. It is able to handle powerful operations like HTML manipulation, event 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 toward 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 tasks.
Example: Date Picker Implementation
If one wants to write code to show a date picker on an onclick event in plain JavaScript, the flow is:
- Create one div element for the onclick event.
- Inside that div, add content for dates, months, and years.
- Add navigation for changing months and years.
- Ensure that, on the first client, the div can be seen, and on the second client, the div is hidden; this should not affect any other HTML elements.
Creating a date picker is slightly more difficult, and if this needs to be implemented multiple times on the same page, it becomes more complex. If the code is not properly implemented, making modifications can become a nightmare.
With jQuery, we can achieve the same with just:
$(#id).datepicker();That’s it! We can reuse the same code multiple times by just changing the id(s); and without any collisions, we can show multiple date pickers on the same page.
In short, using jQuery allows us to focus more on system functionality rather than minor tasks. We can also implement complex features like a rich text editor efficiently. However, writing jQuery code without proper methodology can result in messy code that is difficult for team members to understand and maintain.
General Guidelines for Writing jQuery Code
Developers often make silly mistakes during jQuery code implementation. Based on common mistakes I have encountered, here are general guidelines every developer should follow:
Use this Instead of Repeated IDs or Classes
Most developers use $(#id) or $(.class) repeatedly:
// what developers are doing
$('#id').click(function (){
  var oldValue = $('#id').val();
  var newValue = (oldValue*10)/2;
  $('#id').val(newValue);
});
// better approach
$('#id').click(function() {
  $(this).val(($(this).val()*10)/2);
});
Avoid Conflicts
When working with a CMS like WordPress or Magento, which might use other JavaScript frameworks, use jQuery in noConflict mode:
var $abc = jQuery.noConflict();
$abc('#id').click(function() {
  // do something
});Handle Absent Elements
Ensure the element exists before manipulating it, especially if it is dynamically added:
$('#divId').find('#someId').lengthThis returns 0 if #someId is not found, else it returns the number of elements inside #divId.
Use Proper Selectors and find()
<div id="#id1">
    <span id="#id2"></span>
    <div class="divClass">Here is the content.</div>
</div>find() can traverse the DOM faster:
// slower approach
var content = $('#id1 .divClass').html();
// faster approach
var content = $('#id1').find('div.divClass').html();Write Functions to Avoid Repetition
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 practice
$.doValidation = function(){
    // get value
    // check and return value
};
$('input[type=text]').blur($.doValidation);Organize Objects Properly
Keep related variables together:
// bad
var disableTask1 = false;
var defaultTask1 = 5;
var pointerTask1 = 2;
var disableTask2 = true;
var defaultTask2 = 10;
var currentValueTask2 = 10;
// better
var task1 = {
    disable: false,
    default: 5,
    pointer: 2,
    getNewValue: function () {
        return task1.default + 5;
    }
};
var task2 = {
    disable: true,
    default: 10,
    currentValue: 10
};
Use Callbacks for Dependent Functions
When one function depends on another, use callbacks:
function task1(callback) {
    // do something
    if (callback && typeof(callback) === 'function') {
        callback();
    }
}
function task2(callback) {
    // do something
    if (callback && typeof(callback) === 'function') {
        callback();
    }
}
// jQuery way
$.task1 = function() { /* do something */ };
$.task2 = function() { /* do something */ };
var callbacks = $.Callbacks();
callbacks.add($.task1);
callbacks.add($.task2);
callbacks.fire();Use each() for Iteration
var array;
// JavaScript way
var length = array.length;
for (var i = 0; i < length; i++) {
    var key = array[i].key;
}
// jQuery way
$.each(array, function(key, value) {
    alert(key);
});
Don’t Repeat Code
If you find yourself writing the same code repeatedly, pause and refactor using the principles above.
Originally posted in: Open Source for You
