Thursday 30 December 2010

Best Practices - JQuery

This space is for Best practices and various do & don'ts while writing JQuery code. (please drop comments if you (like)/(don't agree with) them or if you would like to contribute to the list)

Even before we start,first question we should answer is

In what cases we should be creating a plugin and in what cases we can simply write code in the page to do all the cool stuff?
In my view one should write a plugin if-

1. There are multiple functions required to be called to achieve one's requirement.Eg we need to convert a table to a grid, now this might require ajax functionality to get the data ,we might require functions to sort, filter etc and hence we should be writing a plugin for this. Now in other case in which we simply need to hide or show an element on click of a button , in that case we don't need to write a plugin for this.

2. In case we might want to extend the functionality in future. Again taking earlier example we might want to add filter/sorting etc to the table to grid functionality , in that case a plugin gives us better way to manage the code.

3. In case we may have various dynamic options which may change how a particular functionality works.In that case its always good to write a plugin and make use of default settings and then override those defaults by providing options while calling the plugin

4. Reusable Code : In case you would want to use the same bit of code across multiple pages/sites, its always good to code the functionality in a plugin and use it anywhere you want, rather than copy pasting the same bit of code again and again on multiple pages.


References :
http://docs.jquery.com/Plugins/Authoring
http://docs.jquery.com/
http://api.jquery.com/


note : i will be updating this post continuously as the scope for the subject is too big to be written in one go.

Sunday 5 December 2010

Search elements with custom attributes

Lately someone on asp.net forums wanted help for searching elements with custom attributes
just incase you have similar requirement -
<script type="text/javascript">
       $(document).ready(function () {
           var searchText = "a";  //change this as per required
           String.prototype.startsWith = function (str) {
               return (this.match("^" + str) == str)
           }
           var divs = $("div").filter(function () {
               var elem = $(this);
               var validElem = false;
               $(elem.get(0).attributes).each(function () {
                   var node = this.nodeName;
                   if (node.startsWith(searchText) == true) {
                       validElem = true;
                       return false;
                   }
               });
               return validElem;
           });   
 //now  following will return you number of divs having custom attributes starting with "a"       
 var length = divs.length;        
 });
   </script>