Thursday 3 March 2011

JQuery and Update Panels or Script Manager Asp.net

So many times we stuck up into problem of making Jquery work with update Panels/Script manager in asp.net (Ajax enabled sites). Now its not consistent on how we make jquery work in case ScriptManager based site in asp.net when compared to a site which does not use Script Manager so i thought of Creating a plugin to make things more consistent. Feel free to modify the code.

 
(function($) {
    /*
    * Author: Anirudh Gupta
    * This plugin checks if the update panels exists on the page 
    * if yes adds the specified code/function in Sys.Application.add_load
    * if not then adds it in $(document).ready function
    */
    $.fn.CallCode = function(codeToRun) {
        /*
        * start of method : Run Code
        * This method checks if the codeToRun is a function or a string to evaluate 
        * incase of function - the specified function is called
        * incase of string - evaluates the string specified  
        */
        function RunCode(codeToRun) {
            if ($.isFunction(codeToRun) == true) {
                codeToRun.call();
            }
            else if (typeof codeToRun == "string") {
                eval(codeToRun);
            }
        }
        $(document).ready(function() {
            /*
            * check if the page has update panel use sys.application.add_load 
            */
            if (typeof (Sys) == 'undefined') {
             
             
                RunCode(codeToRun);

            }
            else {

                Sys.Application.add_load(function() {
                    RunCode(codeToRun);
                });
            }
        });
    }
})(jQuery);
----------------End of plugin --------------- 
 
how to use ?

<script src="CallCode.js" type="text/javascript"></script>

<!------- Works for both with Script Manager and without Script Manager ---->

   <script type="text/javascript">
       var i =1;
       $().CallCode(function() {
           $(".button").append("<input type='button' value='ClickMe'/>");
           $("input[type='button']").click(function() {
               $(".helloWorld").html(" i am in " + i + "times");
               i++;
           });
       });
    </script>

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <div class="button" />
    <div class='helloWorld'>
    
    </div>


<!--------- another way to use  for simple operations ------->
 <script type="text/javascript">      
       $().CallCode('$("#helloWorld").html("i am in")');
 

Thursday 20 January 2011

Limit text or Show More script

Some times we need to limit the text in a Div and append "...show more" link at end and once the user clicks show more link, user will see full text without limit

Feel free to use the plugin the way you want. Leave a comment in case you like it or if you have any input

   /*  
   * plugin to limit the text and add ShowMore link incase the text exceeds the limit  
   * on click of the link full text   
   */  
   $.fn.limitText = function(options) {  
     /*set up the defaults*/  
     var defaults = {  
       showMoreText: '...Show more',  
       chartLimit: 30,  
       fullText: ''  
     };  
     /*extend the defaults*/  
     var options = $.extend(defaults, options);  
     return this.each(function() {  
       var $elem = $(this);  
       var text = '';  
       /*  
       * validation if the plugin is already attached, dont attach again  
       */  
       if ($elem.attr('limitTextAttached')) {  
         return;  
       }  
       /*set the attribute to the element to avoid multiple attachement of the plugin*/  
       $elem.attr('limitTextAttached', 'attached');  
       /*  
       * incase text of the element need to be used to trim   
       * if the options.fullText is specified then it will be used to trim   
       * and to append in the element  
       */  
       if ($.trim(options.fullText).length == 0) {  
         options.fullText = $elem.text();  
       }  
       text = options.fullText;  
       /*check if the text length is greater than charlimit specified*/  
       if (text.length > options.chartLimit) {  
         text = text.substring(0, (parseInt(options.chartLimit) - 1));  
         $elem.html("");  
         $elem.append(text);  
         var showMoreLink = $("<a href='#'>" + options.showMoreText + "</a>").appendTo($elem);  
         showMoreLink.click(function() {  
           $elem.html(options.fullText);  
         });  
       }  
       else {  
         $elem.html(options.fullText);  
       }  
     });  
   }  

use it like
$("#someDiv").limitText({fullText: 'hello world!!!!!'});
or if someDiv element already has any text in it then use it like simply
$("#someDiv").limitText() 

Tuesday 4 January 2011

Array Sort - Number expected in Internet Explorer

While working on sorting array for date with following code
/*sort the array with date*/
data.sort(function(a, b) {
var objA = a.date;
var objB = b.date;
var dateA = new Date(objA);
var dateB = new Date(objB);
return dateA - dateA;
});
i faced "Number expected" error in IE while it was working fine in other browsers.

Fix - Parse the return as Int like this
/*sort the array with date*/
data.sort(function(a, b) {
var objA = a.date;
var objB = b.date;
var dateA = new Date(objA);
var dateB = new Date(objB);
return parseInt(dateA - dateA);
});

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>

Saturday 20 November 2010

.net and JQGRID

Lately one of the asp.net forum user had issues with .net and jqgrid
Thread link : http://forums.asp.net/t/1624546.aspx

anyone else who needs a reference for similar requirement , have a look at the link

Saturday 13 November 2010

BlinkMe - Blink elements

Sometimes we have required to have the elements blinked on some events and then detach it on some event

Following script will help achieve that

// Done by Anirudh Gupta
//http://mykbdump.blogspot.com/
(function ($) {

$.fn.blinkme = function (options) {

var defaults = {
bordereffect: false,
bordercolor: 'red',
backgroundeffect: true,
backgroundcolor: 'yellow',
blinkinterval: 400,
eventstoattach: 'focus',
eventstodetach: 'blur'
};
options = $.extend(defaults, options);
return this.each(function () {
var elem = $(this);
var intervalobj = null;
var bordercolor = elem.css("border-color");
var bgcolor = elem.css("backgroundColor");
elem.bind(options.eventstoattach, function () {
var blinked = false;
intervalobj = setInterval(function () {
if (blinked == true) {
elem.css({
'backgroundColor': bgcolor,
'border-color': bordercolor
});
blinked = false;
}
else {
if (options.bordereffect == true) {
elem.css({
'border-color': options.bordercolor
});
}
if (options.backgroundeffect == true) {
elem.css({
'backgroundColor': options.backgroundcolor
});
}
blinked = true;
}
}, options.blinkinterval);
});
elem.bind(options.eventstodetach, function () {
if (intervalobj) {
clearInterval(intervalobj);
elem.css({
'backgroundColor': bgcolor,
'border-color': bordercolor
});
}
});
});
}

})(jQuery);