Friday, June 15, 2012

Things you may not know about jQuery.

Do you have a tip nobody knows about? – Add it in the comments…
  • $.fn is just a shortcut to jQuery.prototype.
  • You can test if a jQuery collection contains any elements by trying to access the first element, e.g. if($(selector)[0]){...}.
  • jQuery normalizes the event object across all browsers! Have a look at all the available properties/methods over here:
  • When you create a plugin you have access to the jQuery chain’s previous object:
    jQuery.fn.doSomething = function() {
        this; // => $('a')
        this.prevObject; // => $('li')
        // Remember chaining in your plugins:
        return this;
    // You could even create a new 'root' plugin:
    // (Returns the 'root' of a chain)
    jQuery.fn.root = function() {
        // Root is always document so we have to 
        // go back to one before the last:
        var root = this;
        while(root.prevObject.prevObject) {
            root = root.prevObject;
        return root;
    $('li').find('a').children().root(); // <= $('li') is returned
    // Using root() is the same as using end().end() in this situation
  • You can namespace events! This is especially useful for plugin development:
    jQuery.fn.myPlugin = function() {
        // Clean up after yourself!
        jQuery.myPlugin = {
            cleanUp: function() {
                // Remove all click handlers binded
                // as a result of the plugin:
                // ALternatively, remove ALL events:
        return this.bind('click.myPlugin', function() {
            // Do something...
    // Note, you can also namespace data:
    // E.g. $(elem).data('whatever.myPlugin',value);
  • You can access all event handlers bound to an element (or any object) through jQuery’s event storage:
    // List bound events:
    console.dir( jQuery('#elem').data('events') );
    // Log ALL handlers for ALL events:
    jQuery.each($('#elem').data('events'), function(i, event){
        jQuery.each(event, function(i, handler){
            console.log( handler.toString() );
    // You can see the actual functions which will occur
    // on certain events; great for debugging!
  • jQuery natively supports JSONP (‘JSON with padding’) which effectively means you can make cross-domain "Ajax" requests (although not strictly Ajax since it doesn’t use XHR). For this to work the requested domain must have some JSONP API in place (it must be able wrap the JSON with a specified callback function). An example:
    function getLatestFlickrPics(tag,callback) {
        var flickrFeed = ''
                       + tag + '&tagmode=any&format=json&jsoncallback=?';
        jQuery.getJSON(flickrFeed, callback);
    // Usage:
    getLatestFlickrPics('ferrari', function(data){
        jQuery.each(data.items, function(i, item){
  • You might find it a little messy but jQuery enables us to create an entire DOM structure within a single chain:
    // Create and inject in one chain:
        .append('<p><a href="#">Foo</a></p>')
        .find('p a')
                // Do something...
                return false;
        .append('<p><a href="#">Bar</a></p>')
        .find('p:eq(1) a')
                // Do something else...
                return false;
  • Accessing the DOM elements within a jQuery collection is incredibly easy:
    var HTMLCollection = $('div').get();
    // Alternatively, if you only want the first element:
  • Not only can you bind events to DOM elements; you can also bind a custom event to ANY object!
    function Widget() {
        // Do something...
    var myPhotoWidget = new Widget('photos');
    jQuery(myPhotoWidget).bind('photoAdd', function() {
        // Custom event handling...
    // Trigger event:
  • Finding the index of a selected element is very easy. jQuery gives us the ‘index’ method:
    $('table tr').click(function(){
        // Find index of clicked table row:
        var index = $('table tr').index(this);
  • You can create your own filter selectors. I did a post on this a while back, but take a look at an example anyway:
    $.expr[':'].external = function(elem,index,match) {
        var url = elem.href || elem.src,
            loc = window.location;
        return !!url.match(new RegExp('^' + loc.protocol + '//' + '(?!' + loc.hostname + ')' ));
    // You can now use it within your selectors:
    // Find all external anchors:
    // Find all external script elements:
    // Determine if link is external:
    $('a#mylink').is(':external'); // true/false
  • I see quite a lot of people still using JavaScript’s FOR or WHILE constructs to create loops in their jQuery scripts. There’s nothing wrong with this but be aware that jQuery’s ‘each’ method can also iterate over arrays and objects!
    var myArr = ['apple','banana','orange'];
    $.each(myArr, function(index, item) {
        // Do something with 'item'
        // return false to BREAK
        // return true to CONTINUE
  • The ‘filter’ method accepts a String selector or a function. When using it with a function you must return false to remove the element from the stack and true to keep it:
        return this.childNodes.length > 10; // Must return a Boolean
  • You don’t have to give new elements IDs or classes to reference them later, just cache them into a variable:
    var myInjectedDiv = $('<div/>').appendTo('body');
    // Use 'myInjectedDiv' to reference the element:
    myInjectedDiv.bind('click', function(){
        // ...
  • jQuery’s ‘map’ method is incredibly useful, the passed function will be run on every item of the passed array (or object) and whatever the function returns each time is added to the new array, take a look:
    // Create an array containing all anchor HREF attributes:
    var URLs = $.map($('a'), function(elem, index){
        return elem.href;
    // URLs = ['', '', '']
  • This isn’t jQuery related but it can be very useful. When you need to compare two different ways of doing something (performance-wise) you can use the Firebug console to log the time taken to complete a chunk of code, for example:
    console.time('My first method');
    // Do something...
    console.timeEnd('My first method');
    console.time('My second method');
    // Do something else...
    console.timeEnd('My second method');
    // Firebug will log the time (in milliseconds) taken
    // to complete each chunk...

Thursday, June 14, 2012

how to write xml through datatable

write xml through datatable

StringWriter writer = new StringWriter();
        dt.WriteXml(writer, XmlWriteMode.WriteSchema, true);
        string str = writer.ToString();

Wednesday, June 13, 2012

How Set and Get ASP.NET session variables with JavaScript

Is there any possible method to directly set ASP.NET session variable with JavaScript? NO. You cannot directly set a session variable via JavaScript. But there is a work around.

In the early days of classic ASP, we achieved this by using a hidden frame and use a server post back behind the scene.

But with AJAX, we no longer need hidden frames. All you have to do is, create a new page which accepts the parameters you need to set and then call that page with necessary parameters.

var url = "AjaxCall.aspx?Userid= " + Userid; req = new ActiveXObject("Microsoft.XMLHTTP");"POST", url, true); req.send();

private void Page_Load(object sender, System.EventArgs e)
if(Request.QueryString["Userid"] != null)
Session["Userid"] =Request.QueryString["Userid"].ToString();

You can access the Session variable in your HTML page.

userid = <%=Session["Userid"]%>
Then after render it will show you the session value at the page

userid = 000912

Hope This Help..
Please leave a comment below.

Sunday, June 10, 2012

how to create polygon same like google search.

Just use the Google Map script engine...

var line;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(0, -180),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
var path = [new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)];

line = new google.maps.Polyline({
strokeColor: '#ff0000',
strokeOpacity: 1.0,
strokeWeight: 2


google.maps.event.addListener(map, 'click', addNewPoint);
function addNewPoint(e) {
var path = line.getPath();

Advanced Search In Gmail.

Using advanced search

What you have to just type these command in search and you will get the Result.
Suppose you want to search the all unread mail then type:

is:unread in:inbox

Advanced search operators are query words or symbols that perform special actions in Gmail search. These operators allow you to find what you're looking for quickly and accurately. They can also be used to set up filters so you can organize your inbox automatically. Some of the most useful operators are listed below.
You can also refine your search by clicking the arrow in the search box.
from:Used to specify the senderExample: from:amy
Meaning: Messages from Amy
to:Used to specify a recipientExample: to:david
Meaning: All messages that were sent to David (by you or someone else)
subject:Search for words in the subject lineExample: subject:dinner
Meaning: Messages that have the word "dinner" in the subject
ORSearch for messages matching term A or term B*
*OR must be in all caps
Example: from:amy OR from:david
Meaning: Messages from Amy or from David
Used to exclude messages from your searchExample: dinner -movie
Meaning: Messages that contain the word "dinner" but do not contain the word "movie"
label:Search for messages by label*
*There isn't a search operator for unlabeled messages
Example: from:amy label:friends
Meaning: Messages from Amy that have the label "friends"Example: from:david label:my-family
Meaning: Messages from David that have the label "My Family"
has:attachmentSearch for messages with an attachmentExample: from:david has:attachment 
Meaning: Messages from David that have an attachment
list:Search for messages on mailing listsExample: 
Meaning: Messages with the words in the headers, sent to or from this list
filename:Search for an attachment by name or typeExample:filename:physicshomework.txt
Meaning: Messages with an attachment named "physicshomework.txt"
Example: label:work filename:pdf
Meaning: Messages labeled "work" that also have a PDF file as an attachment
" "
Used to search for an exact phrase*
*Capitalization isn't taken into consideration
Example: "i'm feeling lucky"
Meaning: Messages containing the phrase "i'm feeling lucky" or "I'm feeling lucky"
Example: subject:"dinner and a movie"
Meaning: Messages containing the phrase "dinner and a movie" in the subject
( )Used to group words
Used to specify terms that shouldn't be excluded
Example: from:amy (dinner OR movie)
Meaning: Messages from Amy that contain either the word "dinner" or the word "movie"
Example: subject:(dinner movie)
Meaning: Messages in which the subject contains both the word "dinner" and the word "movie"
in:anywhereSearch for messages anywhere in Gmail*
*Messages in Spam and Trashare excluded from searches by default
Example: in:anywhere movie 
Meaning: Messages in All Mail,Spam, and Trash that contain the word "movie"
Search for messages in Inbox,Trash, or SpamExample: in:trash from:amy
Meaning: Messages from Amy that are in Trash
Search within messages thatPriority Inbox considers important.Example: is:important from:janet
Meaning: Messages from Janet that were marked as important by Priority Inbox
Search for messages that are starred, unread, or readExample: is:read is:starred from:David
Meaning: Messages from David that have been read and are marked with a star
Search for messages with a particular starExample: has:purple-star from:David
Meaning: Messages from David that are marked with a purple star
Used to specify recipients in thecc: or bcc: fields*
*Search on bcc: cannot retrieve messages on which you were blind carbon copied
Example: cc:david 
Meaning: Messages that were cc-ed to David
Search for messages sent during a certain period of time
(using the date format yyyy/mm/dd)
Example: after:2004/04/16 before:2004/04/18 
Meaning: Messages sent between April 16, 2004 and April 18, 2004.*
*More precisely: Messages sent after 12:00 AM (or 00:00) April 16, 2004 and before April 18, 2004.
is:chatSearch for chat messagesExample: is:chat monkey
Meaning: Any chat message including the word "monkey."
deliveredto:Search for messages within a particular email address in the Delivered-To line of the message
Meaning: Any message with in the Delivered-To: field of the message header (which can help you find messages forwarded from another account or ones sent to an alias).
circle:Search for messages that were sent from someone who you added to a particular Google+ circleExample: circle:friends
Meaning: Any message that was sent by a person in your "Friends" circle.

Examples: circle:"soccer friends (team blue)" or circle:"my \"fab four\""
Notes: For circle names that include a space, parentheses, curly brackets, or vertical bar, add quotes around the name. For names that include quotes, add a back slash immediately before the quotes.
has:circleSearch for all messages that were sent from someone who you added to your Google+ circlesExample: has:circle 
Meaning: Any message that was sent by a person in any of your circles.