"JQuery is most powerful and rich tool for client side development. But improper use of jQuery might become nightmare for developer. In this article I have explained all about what developers are doing and what they should do with jQuery.”
This article aims to explain use of jQuery for rapid and more sophisticated manner. Now a days any website does not only focus on backend functionalities like user registration, adding new friends or validation like stuffs, but also focuses on how their web page will appear to user, how their page will behave in different - different situations. For example, slideshow on front page, onmouseover show beautiful animations, show properly formatted error message or show interactive hints to user for what to do on their site.
So, what is jQuery:
JQuery is very handy and more interactive, powerful and rich client side framework built on Javascript. JQuery is able to handle many powerful stuffs like HTML manipulation, events handling, beautiful animations. And its most attractive feature is it is cross browser. By using plain Javascript we need to make sure for many things like, the code we write is good as well as must be tends to more perfection. It should handle any exception if user enters any other invalid type of values and not just hangs script or show horrible behaviour. But in my career what I have seen is many junior developers are using plain Javascript solution instead of jQuery like rich frameworks and writes numbers of line of code for just doing some small stuffs.
For example, one wants to write code for showing datepicker selection on onclick event. If we are writing code using plain Javascript, what could be the flow is,
1) onclick event create one div element.
2) inside that div, add content for dates, month and year.
3) Add navigation for changing months and year.
4) Need to make sure that, on first client div should show and and on second client div must be hidden, and should not affect any other HTML elements. So, just creating datepicker is little more difficult task and if this needs to implement more times in same page, then it becomes more complex and if code is not properly implemented then doing modification can be a nightmare.
Instead of doing this type of complex things, jQuery comes to rescue in that nightmare. By using jQuery we can show datepicker like this:
$(“#id”).datepicker();
That’s it, we can reuse same code multiple times by just changing id(s) and without any kind of collision we can show multiple datepickers in same page. That is the beautifulness of jQuery. In short, by using jQuery we can focus on more functionality of system, not just only small-small parts of system. Using jQuery we can write more complex code like rich text editor and many other stuffs. But writing jQuery code without proper guidance and proper methodology, we ends up writing code in horrible formation, and sometimes that kind of code becomes more panic for other team members to understand and modify for just small changes.
In my professional career, many times I have seen that, developers make silly mistakes during jQuery code implementation. So, based on some silly mistakes, here is some general guideline that every developer should keep in their mind during implementation of jQuery code.
General guideline for jQuery:
1) Try to use ‘this’ instead of just using id and class of DOM elements. I have seen that most of developers are happy with just using $('#id') or $('.class') every where.
//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 we are working with cms like wordpress or magento etc. they might have use other Javascript frameworks instead of jQuery. And if you needs to work with jQuery inside that cms or project. Then use noConflicts of jQuery.
var $abc = jQuery.noConflict();
$abc('#id').click(function(){
//do something
});
3) Make Sure for 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 will manipulate is adding dynamically then first find it, if that element is added on dom.
$('#divId').find('#someId').length;
This code returns 0 if there is not any element with 'someId' founded else it will return total numbers of elements which are inside 'divId'.
4) Use proper selectors and try to use more ‘find()’, because find can traverse DOM more faster. For example, we want to find content of #id3
//developer generally uses
var content = $(‘#id1 .divClass’).html();
//better way is [This is more faster in execution]
var content = $(‘#id1’).find(‘div.divClass’).html();
5) Write functions wherever required. Generally developers write same code multiple times. What should he do is, first make a flow how that task is going to implement. Find the block that will repeat again and again. For example, on blur of any text box get validated value. If value is empty then return 0 else give values that user has entered. So, there are some way to implement that functionality.
//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 Organization: This is another thing that each developer needs to keep in mind. If some bunch of variables are related to one task and some bunch of variables are related to another task then make them more organized.
//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 second function is dependent on effects of first output, at that time you need to write callbacks.
For example, task2 needs to be executed after completion of task1 or in other way, you need to halt execution of task2 until task1 is executed. I have seen many developers are not aware of callback functions. So, they either initializing one variable for checking [like mutex in operating system] or setting timeout for execution. Below I have explained how easily you can implement using callback.
//Javascript way
task1(function(){
task1(function(){
task2();
});
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
var array;
//javascript way
var length = array.length;
for(var i =0; i < length; i++) {
var key = array[i].key;
var key = array[i].key;
// like wise fetching other values.
}
//jQuery way
$.each(array, function(key, value){
alert(key);
});
9) Never write any code again and again. If so, you are doing wrong holt your coding and read above described all 8 points again.
So, I think this is it for getting started with writing more manageable and reusable code. There are many things that needs to be taken care of during development. Next time I’ll explain how to write more effective plugin with some example.