Easy Tip to write clean and manageable jQuery Code
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.