Easy Tip to write clean and manageable jQuery Code

jQuery gives amazing power to make things simple and easy to implement. For jQuery to work, we need to put all the code in $(document).ready() function and there can be many $(document).ready() function in a single page.

But putting everything inside $(document).ready() function may make your code look ugly, not understandable, unmanageable and sometimes buggy. In this post, I will show you how can you make your code look clean, easy to understand and manageable.


We all are familiar with below jQuery code. Most of us have habit of putting everything inside $(document).ready. Below code is very small piece of jQuery code but in real projects or application this would be more and then things become unmanageable. So is there any better way to do this?
$(document).ready(function() {
  $("a").live('click', function() {
      alert('I am clicked');
  });
  $("a").mouseover(function() {
      $(this).css('color','red');
  });
});
Well, the answer is YES. You can divide your code in functions.
//This function binds the click event to all the a element using live method.
function BindLivetoAnchor()
{
  $("a").live('click', function() {
      alert('I am clicked');
  });
}

//This function binds the mouseover event to all the a element.
function BindMouseOverEvent()
{
  $("a").mouseover(function() {
      $(this).css('color','red');
  });
}
Now these functions can be called from document.ready() function.
$(document).ready(function() {
   BindLivetoAnchor();
   BindMouseOverEvent();
});
This way you can make your jQuery code look
  • Clean and manageable
  • Easy to understand.
  • Commenting can be done easily.
  • Easy to debug.
  • It can be reused.

Feel free to contact me for any help related to jQuery. I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..