Friday 21 December 2012

Ajax With Jquery


AJAX -- "Asynchronous JavaScript and XML" — is a means of loading data from a server without requiring a page reload. It uses a browser's built-in XMLHttpRequest (XHR) functionality to make a request to the server and then handle the data that the server returns.
JQuery provides the $.ajax method — and several convenience methods — to make it easier to work with XHRs across browsers.
$.ajax
We can use the jQuery $.ajax() method in a couple of different ways: we can pass it a configuration object as its sole argument, or we can pass it a URL and an optional configuration object. Let's take a look at the first approach:
// Create the "callback" functions that will be invoked when...
// ... the AJAX request is successful
var updatePage = function( resp ) {
  $( '#target').html( resp.people[0].name );
};

// ... the AJAX request fails
var printError = function( req, status, err ) {
  console.log( 'something went wrong', status, err );
};

// Create an object to describe the AJAX request
var ajaxOptions = {
  url: '/data/people.json',
  dataType: 'json',
  success: updatePage,
  error: printError
};

// Initiate the request!
$.ajax(ajaxOptions);
Of course, you can be less verbose by just passing an object literal to the $.ajax() method, and using anonymous functions for the success and error callbacks. This version is easier to write, and likely easier to maintain:
$.ajax({
  url: '/data/people.json',
  dataType: 'json',
  success: function( resp ) {
    $( '#target').html( resp.people[0].name );
  },
  error: function( req, status, err ) {
    console.log( 'something went wrong', status, err );
  }
});
As mentioned earlier, you can also call the $.ajax() method by passing it a URL and an optional configuration object. This can be useful if you want to use the default configuration for $.ajax(), or if you want to use the same configuration for several URLs.
$.ajax( '/data/people.json', {
  type: 'GET',
  dataType: 'json',
  success: function( resp ) {
    console.log( resp.people );
  },
  error: function( req, status, err ) {
    console.log( 'something went wrong', status, err );
  }
});
In this version, only the URL is required, but the configuration object lets us tell jQuery what data we want to send, which HTTP method to use (GET, POST, etc.), what kind of data we expect to receive, how to react when the request succeeds or fails, and much more.
See the $.ajax() documentation for a complete list of configuration options.
A is for asynchronous
AJAX requests run asynchronously — that means that the $.ajax method returns before the request is finished, and therefore before the success callback runs. That means that this function's return statement runs before the request is complete. This means the getSomeData function below will return data before it is defined, causing the code to throw an error.
caution broken code
var getSomeData = function() {
  var data;

  $.ajax({
    url: '/data/people.json',
    dataType: 'json',
    success: function(resp) {
      data = resp.people;
    }
  });

  return data;
}

$('#target').html(getSomeData().people[0].name );
X is for JSON
The term AJAX was coined in 2005 to describe a method for retrieving data from a server without requiring a page refresh. Back then, data sent by a server tended to be formatted as XML, but these days, most modern applications use JSON as the format for data from the server.
JSON is a string representation of data; it looks a whole lot like a normal JavaScript object, but it can only be used to represent a subset of the data that a normal JavaScript object can represent. For example, JSON cannot represent function or date objects. Here's an example of a JSON string; note how all property names are quoted:
{"people": [
  {
    "name" : "Ben",
    "url" : "http://benalman.com/",
    "bio" : "I create groovy websites, useful jQuery plugins, and play a mean funk bass. I'm also Director of Pluginization at @bocoup."
  },
  {
    "name" : "Rebecca",
    "url" : "http://rmurphey.com",
    "bio" : "Senior JS dev at Bocoup"
  },
  {
    "name" : "Jory",
    "url" : "http://joryburson.com",
    "bio" : "super-enthusiastic about open web education @bocoup. lover of media, art, and fake mustaches."
  }
] }
It's important to remember that JSON is a string representation of an object — the string must be parsed into an actual JavaScript object before working with it. When you're working with a JSON response to an XHR, jQuery takes care of this task for you, but it's crucial to understand the difference between the JSON representation of an object, and the object itself.
If you need to create a JSON string from a JavaScript object, or if you need to parse a JSON string outside of jQuery, modern browsers provide the JSON.stringify() and JSON.parse() methods. This functionality can be added to older browsers using the json2.js library. jQuery also provides the jQuery.parseJSON method, which provides the same functionality as JSON.parse() across all browsers. However, jQuery does not provide a method that corresponds to JSON.stringify().
Convenience methods
If we're just making a simple request — and if we don't care about error handling — jQuery provides several "convenience methods" that let us use an abbreviated syntax. Each of these methods takes a URL, an optional data object, and an optional callback for handling a successful request.
$.get('/data/people.html', function( html ){
  $('#target').html(html);
});

$.post( '/data/save', { name: 'Rebecca' }, function( resp ) {
  console.log( JSON.parse( resp ) );
});
Sending data & working with forms
We can send data with our request by setting the data property on our configuration object, or by passing an object as the second argument to one of the convenience methods.
For a GET request, this data will be appended to the URL as a query string; for a POST request, it will be sent as form data. jQuery provides the helpful .serialize() method for taking form input and converting it to a query string format
(field1name=field1value&field2name=field2value...):
$( 'form' ).submit(function( event ) {
  event.preventDefault();

  var form = $( this );

  $.ajax({
    type: 'POST',
    url: '/data/save',
    data: form.serialize(),
    dataType: 'json',
    success: function( resp ) {
      console.log( resp );
    }
  });
});
jqXHR
$.ajax() (and related convenience methods) returns a jqXHR object — a jQuery XML HTTP Request — which has a host of powerful methods. We can make a request using $.ajax(), and then capture the returned jqXHR object in a variable.
var req = $.ajax({
  url: '/data/people.json',
  dataType: 'json'
});
We can use this object to attach callbacks to the request, even after the request has completed. For example, we can use the .then() method of the jqXHR object to attach success and error callbacks. The .then() method takes one or two functions as its arguments. The first function will be be called if the request succeeds; the second will be called if the request fails.
var success = function( resp ) {
  $( '#target' ).append(
    '<p>people: ' + resp.people.length + '</p>'
  );
  console.log( resp.people );
};

var err = function( req, status, err ) {
  $( '#target' ).append( '<p>something went wrong</p>' );
};

req.then( success, err );
req.then(function() {
  $( '#target' ).append( '<p>it worked</p>' );
});
We can call .then() on a request as many times as we'd like; it's a first-in, first-out queue.
If we don't want to attach success and error callbacks at the same time, we can use the .done() and .fail() methods of the request object.
req.done( success );
req.fail( err );
If we want to attach a callback that runs on success or failure, we can use the .always() method of the request object.
req.always(function() {
  $( '#target' )
    .append( '<p>one way or another, it is done now</p>' );
});
JSONP
Many JavaScript developers are alarmed when they first try to use $.ajax to fetch data from another domain and their request fails. For example, you may try fetching data from a third-party API, and discover that your request consistently fails.
As it turns out, for security reasons, XHRs to other domains are blocked by the browser. However, certain third-party APIs provide a response formatted as JSONP — "JSON with Padding" — which allows you to use their data even though it is hosted on another server.
JSONP isn't exactly AJAX — rather than using the browser's XHR functionality, it actually works by inserting a script tag into the page that contains the requested data, "padded" with a function wrapper. Nevertheless, jQuery lets you make a JSONP request with $.ajax() by specifying 'jsonp' as the dataType in the configuration object.
$.ajax({
  url: '/data/search.jsonp',
  data: { q: 'a' },
  dataType: 'jsonp',
  success: function( resp ) {
    $( '#target' ).html( 'Results: ' + resp.results.length );
  }
});
An API that offers JSONP will specify the name of the callback parameter to use in the query string; generally, this name is callback, and so jQuery uses that as its default. However, you can override this callback name by specifying the jsonp property in the configuration object passed to $.ajax().
You can also use the $.getJSON() convenience method to make a JSONP request; if the URL includes callback=? or similar, then jQuery will treat it as a JSONP request.
$.getJSON( '/data/search.jsonp?q=a&callback=?',
  function( resp ) {
    $( '#target' ).html( 'Results: ' + resp.results.length );
  }
);
CORS — cross-origin resource sharing — is another option for enabling cross-origin requests. However, it is not supported on older browsers, and it requires server-side configuration and manipulation of the XHR headers in order to work.
Deferreds
The jqXHR object is simply a special flavor of a "deferred". jQuery lets you create your own deferreds, which can be a powerful way for managing asynchronous code. Deferreds provide a means to react to the eventual success or failure of an asynchronous operation, and reduce the need for deeply nested callbacks.
$.Deferred
You can create your own deferreds using $.Deferred(). Here, we run a function in a setTimeout, and "resolve" our deferred with the return value of that function. We return the deferred's "promise" — an object to which we can attach callbacks, but which doesn't have the ability to modify the outcome of deferred itself. We "reject" the deferred if anything goes wrong with running the provided function.
function doSomethingLater( fn, time ) {
  var dfd = $.Deferred();

  setTimeout(function() {
    dfd.resolve( fn() );
  }, time || 0);

  return dfd.promise();
}

var promise = doSomethingLater(function() {
  console.log( 'This function will be called in 100ms' );
}, 100);
.then(), .done(), .fail(), .always()
Just like with a jqXHR, we can attach success and error handlers to a promise.
function doSomethingLater( fn, time ) {
  var dfd = $.Deferred();

  setTimeout(function() {
    dfd.resolve( fn() );
  }, time || 0);

  return dfd.promise();
}

var success = function( resp ) {
  $( '#target' ).html( 'it worked' );
};

var err = function( req, status, err ) {
  $( '#target' ).html( 'it failed' );
};

var dfd = doSomethingLater(function() { /* ... */ }, 100);

dfd.then( success, err );
pipe()
We can use the .pipe() method of a promise to react to the resolution of an asynchronous operation by manipulating the value it returns and creating a new deferred.
As of jQuery 1.8, the .then() method of a promise behaves like .pipe().
function doSomethingLater( fn, time ) {
  var dfd = $.Deferred();

  setTimeout(function() {
    dfd.resolve( fn() );
  }, time || 0);

  return dfd.promise();
}

var dfd = doSomethingLater(function() { return 1; }, 100);

dfd
  .pipe(function(resp) { return resp + ' ' + resp; })
  .done(function(upperCaseResp) {
    $( '#target' ).html( upperCaseResp );
  });
Reacting to maybe-asynchronous operations
Sometimes we have an operation that might return immediately, or might be asynchronous — for example, if a function does something async the first time it runs, and then caches the value for future use. In this case, we can use $.when() to react to either case.
function maybeAsync( num ) {
  var dfd = $.Deferred();

  // return a deferred when num === 1
  if ( num === 1 ) {
    setTimeout(function() {
      dfd.resolve( num );
    }, 100);
    return dfd.promise();
  }

  // return immediately otherwise
  return num;
}

// this will resolve async
$.when( maybeAsync( 1 ) ).then(function( resp ) {
  $( '#target' ).append( '<p>' + resp + '</p>' );
});

// this will return immediately
$.when( maybeAsync( 0 ) ).then(function( resp ) {
  $( '#target' ).append( '<p>' + resp + '</p>' );
});
You can also pass $.when() more than one argument, which lets you mix sync and async operations; you get their return values back as arguments to the callback.
function maybeAsync( num ) {
  var dfd = $.Deferred();

  // return a deferred when num === 1
  if ( num === 1 ) {
    setTimeout(function() {
      dfd.resolve( num );
    }, 100);
    return dfd.promise();
  }

  // return immediately otherwise
  return num;
}

$.when( maybeAsync( 0 ), maybeAsync( 1 ) )
  .then(function( resp1, resp2 ) {
    var target = $( '#target' );
    target.append( '<p>' + resp1 + '</p>' );
    target.append( '<p>' + resp2 + '</p>' );
  });
When a jqXHR is one of the arguments to $.when(), we get an array of arguments passed to our callback.
function maybeAsync( num ) {
  var dfd = $.Deferred();

  // return a deferred when num === 1
  if ( num === 1 ) {
    setTimeout(function() {
      dfd.resolve( num );
    }, 100);
    return dfd.promise();
  }

  // return immediately otherwise
  return num;
}

$.when( maybeAsync( 0 ), $.get( '/data/people.json' ) )
  .then(function( resp1, resp2 ) {
    console.log( "Both operations are done", resp1, resp2 );

Thursday 20 December 2012

Animating Pages With Jquery


jQuery makes it trivial to add simple effects to your page. Effects can use the built-in settings or provide a customized duration. You can also create custom animations of arbitrary CSS properties.
An important note about animations: In modern browsers, and especially on mobile devices, it is often much more efficient to achieve animations using CSS rather than JavaScript. The details of doing this are beyond the scope of this guide, but if you are only targeting mobile devices or browsers that support CSS animations, then you should use CSS for animations where possible. You may also want to consider setting jQuery.fx.off  to true on low-resource devices; doing so will cause animation methods to immediately set elements to the desired state, rather than animating to that state.
Built-in effects
Frequently used effects are built into jQuery as methods that you can call on any jQuery object:
.show() Show the selected elements.
.hide() Hide the selected elements.
.fadeIn() Animate the opacity of the selected elements to 100%.
.fadeOut() Animate the opacity of the selected elements to 0%.
.slideDown() Display the selected elements with a vertical sliding motion.
.slideUp() Hide the selected elements with a vertical sliding motion.
.slideToggle() Show or hide the selected elements with a vertical sliding motion, depending on whether the elements are currently visible.
Once you've made a selection, it's simple to apply an effect to that selection.
$('.hidden').show();
You can also specify the duration of built-in effects. There are two ways to do this: you can specify a time in milliseconds.
$('.hidden').show(300);
... or use one of the pre-defined speeds:
$('.hidden').show('slow');
The predefined speeds are specified in the jQuery.fx.speeds object; you can modify this object to override the defaults, or extend it with new names:
// re-set an existing predefined speed
jQuery.fx.speeds.fast = 50;

// create a new pre-defined speed
jQuery.fx.speeds.turtle = 3000;

// Since we've re-set the 'fast' speed, this will now animate over the
// course of 50 milliseconds
$( '.hidden' ).hide( 'fast' );

// After they are created, we can use custom speeds just as we use the
// built-in speeds
$( '.other-hidden' ).show( 'turtle' );
Often, you'll want to do something once an animation is done — if you try to do it before the animation completes, it may affect the quality of the animation, or it may remove elments that are part of the animation. You can provide a callback function to the animation methods if you want to specify what should happen when the effect is complete. Inside the callback, this refers to the raw DOM element that the effect was applied to. Just like with event callbacks, we can turn it into a jQuery object by passing it to the $() function: $( this ).
$('p.old').fadeOut(300, function() {
  $(this).remove();
});
Note that if your selection doesn't contain any elements, then your callback will never run! If you need your callback to run regardless of whether there are elements in your selection, you can create a function and use it for both cases:
var oldElements = $( 'p.old' );
var thingToAnimate = $( '#nonexistent' );

// This function will be a "callback" to the "show" method when there are
// elements to show. Otherwise, we will simply call it immediately
var removeOldElements = function() {
  oldElements.remove();
};

if (thingToAnimate.length) {

  // When passed as a callback to "show", the function will be invoked
  // when the animation is complete
  thingToAnimate.show( 'slow', removeOldElements );

} else {
  removeOldElements();
}
Custom effects with .animate()
If the built-in animations don't suit your needs, you can use .animate() to create custom animations of many CSS properties. (Notably, you cannot animate the color property, but there is a plugin that makes it possible).
The .animate() method takes up to three arguments:
an object defining the properties to be animated
the duration of the animation, in milliseconds
a callback function that will be called when the animation is complete
The .animate() method can animate to a specified final value, or it can increment an existing value.
$( '.funtimes' ).animate({
    left: '+=50', // increase by 50
    opacity: 0.25,
    fontSize: '12px'
  },
  300,
  function() {
    // executes when the animation is done
  }
);
Note that if you want to animate a CSS property whose name includes a hyphen, you will need to use a "camel case" version of the property name if you do not quote the property name. For example, the font-size property must be referred to as fontSize.
Managing animations
jQuery provides two important methods for managing animations.
.stop() will stop currently running animations on the selected elements.
.delay() will pause before the execution of the next animation method. Pass it the number of milliseconds you want to wait.
jQuery also provides methods for managing the effects queue, creating custom queues, and adding custom functions to these queues. These methods are beyond the scope of this guide

Jquery Events


jQuery makes it easy to respond to user interaction with a web page. This means that you can write code that runs when a user clicks on a certain part of the page, or when she moves her mouse over a form element. For example, this code listens for a user to click on any li element in the page:
$('li').click(function( event ) {
  console.log( 'clicked', $( this ).text() );
});
The code above selects all list items on the page, then binds a handler function to the click event of each list item using jQuery's .click() method.
Methods such as .click(), .blur(), .change(), and others are "shorthand" methods for event binding. jQuery provides a number of these shorthand methods, each of which corresponds to a native DOM event:
Native Event Name Shorthand Method
Click .click()
Keydown .keydown()
Keypress .keypress()
Keyup .keyup()
Mouseover .mouseover()
Mouseout .mouseout()
Mouseenter .mouseenter()
Mouseleave .mouseleave()
Scroll .scroll()
Focus .focus()
Blur .blur()
Resize .resize()
Under the hood, all of the shorthand methods make use of jQuery's .on() method. You can use the .on() method in your own code; indeed, doing so gives you a lot more flexibility. When you use the .on() method, you pass the native event name as the first argument, and then the handler function as the second argument:
$( 'li' ).on( 'click', function( event ) {
  console.log( 'clicked', $( this ).text() );
});
Once you've "bound" an event handler to an element, you can trigger that event handler using jQuery as well.
$( 'li' ).trigger( 'click' );
If the event you want to trigger has a shorthand method (see the table above), you can also trigger the event by simply calling the shorthand method:
$('li').click();
When you .trigger() an event, you only trigger event handlers that were bound with JavaScript — you don't trigger the default behavior of the event. For example, if you trigger the click event of an a element, it will not automatically navigate to the href of that element (though you could write code that would make it do so).
Once you have bound an event, you can unbind the event using jQuery's .off() method. This will remove any event handlers that were bound to the specified event:
$( 'li' ).off( 'click' );
Namespaced events
One advantage that .on() offers is the ability to use "namespaced" events. When would you want to use namespaces? Consider a situation where you bind some events, and then want to unbind some of the handlers. As we just saw, you could do it this way:
caution antipattern
$( 'li' ).on( 'click', function()
 {
  console.log( 'a list item was clicked' );
});

$( 'li' ).on( 'click', function() {
  registerClick();
  doSomethingElse();
});

$( 'li' ).off( 'click' );
However, this will unbind all click handlers on all li elements, which isn't what we want. If you bind an event handler using a namespaced event, you can target that event handler specifically:
$( 'li' ).on( 'click.logging', function() {
  console.log( 'a list item was clicked' );
});

$( 'li' ).on( 'click.analytics', function() {
  registerClick();
  doSomethingElse();
});

$( 'li' ).off( 'click.logging' );
This code leaves our analytics-related click untouched, while unbinding our logging-related click.
We can also use namespaces to trigger only certain events:
$( 'li' ).trigger( 'click.logging' );
Binding multiple events at once
Another benefit of using .on() is the ability to bind to multiple events at once. For example, you might want to run the same code when a user scrolls the window or when a user resizes the window. The .on() method lets you pass both events — in a space-separated string — followed by the function that you want to handle both events:
$( 'input[type="text"]' ).on('focus blur', function() {
  console.log( 'The user focused or blurred the input' );
});

$( window ).on( 'resize.foo scroll.bar', function() {
  console.log( 'The window has been resized or scrolled!' );
});
Passing named functions as event handlers
In all of our examples up until now, we've been passing anonymous functions as event handlers. However, you can create a function ahead of time and store it in a variable, then pass that variable as the event handler. This is useful if you want to use the same handler for different events or events on different elements.
var handleClick = function() {
  console.log( 'something was clicked' );
};

$( 'li' ).on( 'click', handleClick );
$( 'h1' ).on( 'click', handleClick );
The event object
Whenever an event is triggered, the event handler function receives one argument, an event object that is normalized across browsers. This object has many useful properties, including the following:
$( document ).on( 'click', function( event ) {
  console.log( event.type );    // The event type, eg. "click"
  console.log( event.which );   // The button or key that was pressed.
  console.log( event.target );  // The originating element.
  console.log( event.pageX );   // The document mouse X coordinate.
  console.log( event.pageY );   // The document mouse Y coordinate.
});
Inside the event handler
When you specify a function to be used as an event handler, that function gets access to the raw DOM element that initiated the event as this. If you want to use jQuery to manipulate the element, you will need to pass it to $():
$( 'input' ).on( 'keydown', function( event ) {
  // this: The element on which the event handler was bound.
  // event: The event object.

  // Change the input element's background to red if backspace was
  // pressed, otherwise green.
  $( this ).css( 'background', event.which === 8 ? 'red' : 'green' );
});
Preventing the default action
Often, you'll want to prevent the default action of an event; for example, you may want to handle a click on an a element using AJAX, rather than triggering a full page reload. Many developers achieve this by having the event handler return false, but this actually has another side effect: it stops the propagation of the event as well, which can have unintended consequences. The right way to prevent the default behavior of an event is to call the .preventDefault() method of the event object.
$( 'a' ).on( 'click', function( event ) {
  // Prevent the default action.
  event.preventDefault();
  // Log stuff.
  console.log( 'I was just clicked!' );
});
This will allow the event to "bubble," which we'll explore below.
Event bubbling
Consider the following code:
$( '*' ).add( [ document, window ] ).on( 'click', function( event ) {
  event.preventDefault();
  console.log( this );
});
It binds a click handler to all elements in a document (something you should never do in real code), as well as to the document and window. What happens when you click on an a element that's nested inside other elements? In fact, the click event will be triggered for the a element as well as for all of the elements that contain the a — all the way up to the document and the window. (You can click on the icon to try it in the sandbox yourself.)
This behavior is called event bubbling — the event is triggered on the element on which the user clicked, and — unless you call .stopPropagation() on the event object — the event is then triggered all the way up the DOM.
You can see this more clearly when you consider the following markup:
<a href="#foo"><span>I am a Link!</span></a>
<a href="#bar"><b><i>I am another Link!</i></b></a>
And the following code:
$( 'a' ).on( 'click', function( event ) {
  event.preventDefault();
  console.log( $( this ).attr( 'href' ) );
});
When you click on "I am a Link!", you are not actually clicking on an a, but rather on a span inside of an a. Nevertheless, the click event bubbles up to the a, and the bound click handler fires.
Event delegation
The bubbling behavior of events allows us to do "event delegation" — binding handlers to high-level elements, and then detecting which low-level element initiated the event. For example, we could bind an event to an unordered list, and then determine which element initiated the event:
$( '#my-unordered-list' ).on( 'click', function( event ) {
  console.log( event.target ); // logs the element that initiated the event
});
Of course, if our unordered list contains list items that contain other markup, but we really only care about which list item was clicked, then this can get messy in a hurry. Thankfully, jQuery provides a helper that lets us specify which elements we care about, while still only binding to the high-level element.
$( '#my-unordered-list' ).on( 'click', 'li', function( event ) {
  console.log( this ); // logs the list item that was clicked
});

$( '<li>a new list item!</li>' ).appendTo( '#my-unordered-list' );
Event delegation has two main benefits. First, it allows us to bind fewer event handlers than we'd have to bind if we were listening to clicks on individual elements, which can be a big performance gain. Second, it allows us to bind to parent elements — such as an unordered list — and know that our event handlers will fire as expected even if the contents of that parent element change.
For example, this code adds a new list item after the event delegation is set up; clicking on the new item works just fine, without any additional event binding code.
$( '#my-unordered-list' ).on( 'click', 'li', function( event ) {
  console.log( this ); // logs the list item that was clicked
});

$( '<li>a new list item!</li>' ).appendTo( '#my-unordered-list' );
Conclusion
In this section, we took a look at various ways to listen for user interaction with our page, including how we can use event delegation to more efficiently set up event handlers. In the next section, we'll look at how we can animate elements using jQuery's effects methods.

JqueryInformation


The jQuery library makes it easy to manipulate a page of HTML after it's displayed by the browser. It also provides tools that help you listen for a user to interact with your page, tools that help you create animations in your page, and tools that let you communicate with a server without reloading the page. We'll get to those in a bit. First, let's look at some jQuery basics, and at how we can use jQuery to perform its core functionality: getting some elements and doing something with them.
This guide assumes that you understand HTML and CSS Selectors. If you are not familiar with how you can use CSS selectors to target elements, you should spend some time getting up to speed before trying to work through this guide.
What’s $, anyway?
The jQuery library provides the jQuery function, which lets you select elements using CSS selectors.
var listItems = jQuery( 'li' );
Of course, if you've seen any jQuery code, you're probably more accustomed to seeing something like this:
var listItems = $( 'li' );
As discussed in the JavaScript Basics section, valid names in JavaScript can be pretty much anything, as long as they don't begin with a number and don't include a hyphen. So, the $ in the code above is just a shorter, more convenient name for the jQuery function; indeed, in the jQuery source code, you'll find this near the end:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
When you call the $() function and pass a selector to it, you create a new jQuery object. Of course, in JavaScript, functions are objects too, so that means that $ (and jQuery, of course) has properties and methods, too. For example, you can refer to the $.support property for information on what the current browser environment supports, and you use the $.ajax method to make an AJAX request.
For the rest of this guide, we'll use $ instead of jQuery for the sake of brevity. Note that if your page contains more than one JavaScript library, then $ may be used by another library, which can cause jQuery not to work. If you experience this, you should consider using jQuery.noConflict before loading the other libraries.
$(document).ready()
Before you can safely use jQuery to do anything to your page, you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready(). As you can see here, the function we pass can just be an anonymous function.
$( document ).ready(function() {
  console.log( 'ready!' );
});
This will run the function that we pass to .ready() once the document is ready. What's going on here? We're using $(document) to create a jQuery object from our page's document, and then calling the .ready() function on that object, passing it the function we want to execute.
Since this is something you'll find yourself doing a lot, there's a shorthand method for this if you prefer — the $() function does double duty as an alias for $(document).ready() if you pass it a function:
$(function() {
  console.log( 'ready!' );
});
For the rest of this guide, we'll assume that the code we're looking at is enclosed in $(document).ready(function() { ... });, and we'll leave that part out for brevity.
Get some elements
The simplest thing we can do with jQuery is get some elements and do something with them. If you understand CSS selectors, getting some elements is very straightforward: you simply pass the appropriate selector to $().
$( '#header' ); // select the element with an ID of 'header'
$( 'li' );      // select all list items on the page
$( 'ul li' );   // select list items that are in unordered lists
$( '.person' ); // select all elements with a class of 'person'
It's important to understand that any selection you make will only contain elements that existed in the page when you made the selection. That is, if you write var anchors = $( 'a' ); and then add another <a> element to your page later, then your anchors variable will not contain that new element.
Other ways to create a jQuery object
In addition to passing a simple selector to $(), you can create jQuery objects in a few other ways:
// create a jQuery object from a DOM element
$( document.body.children[0] );

// create a jQuery object from a list of DOM elements
$( [ window, document ] );

// make a selection in the context of a DOM element
var firstBodyChild = document.body.children[0];
$( 'li', firstBodyChild );

// make a selection within a previous selection
var paragraph = $( 'p' );
$( 'a', paragraph );
Did my selection get anything?
Sometimes, you'll only want to do something when your selection matches some elements. Because the $() function always returns a jQuery object, and an object is always truthy, you'll need to test the contents of your selection to determine whether anything was found.
caution broken code
if ( $( '#nonexistent' ) ) {
  // Wrong! This code will always run!
}

if ( $( '#nonexistent' ).length > 0 ) {
  // Correct! This code will only run if there's an element in your page
  // with an ID of 'nonexistent'
}
We can shorten our check even further if we remember that 0 is a falsy value:
if ( $( '#nonexistent' ).length ) {
  // This code will only run if there's a matching element
}
Getting single elements from a selection
If you need to work with the raw DOM element from a selection, you need to access that element from the jQuery object. For example, if you wanted to access an <input> element's value property directly, you would want to work with the raw DOM element.
var listItems = $( 'li' );
var rawListItem = listItems[0]; // or listItems.get( 0 )
var html = rawListItem.innerHTML;
Note that you cannot call jQuery methods on raw DOM elements. So, the following will not work:
caution broken code
var listItems = $( 'li' );
var rawListItem = listItems[0];
var html = rawListItem.html();
// Object #<HTMLInputElement> has no method 'html'
If you need to work with a single element in a selection and you want to be able to use jQuery methods on that element, then you can get a new jQuery object containing a single element by using .eq() and passing the index of the element you're after.
var listItems = $( 'li' );
var secondListItem = listItems.eq( 1 );
secondListItem.remove();

Creating new elements
The $ function has one last role: creating new elements. If you pass an HTML snippet to $(), it will create a new element in memory — that is, the element will be created, but it won't be placed on the page until you place it on the page.
$( '<p>' ); // creates a new <p> element with no content
$( '<p>Hello!</p>' ); // creates a new <p> element with content
$( '<p class="greet">Hello!</p>' ); // creates a new <p> with content and class
You can also create an element by passing an object with information about how to create the element:
$( '<p>', {
  html: 'Hello!',
  'class': 'greet'
});
Note that we must wrap the class property in quotation marks, as class is a reserved word in JavaScript, and failing to quote it will cause errors in some browsers. See the jQuery documentation for details on the various properties you can include in the object.
We'll look at how to place created elements into the document in the next chapter, which covers traversing and manipulating the document.
Working with selections
Once you've created a jQuery object that contains your selection, you probably want to do something with your selection. Before we do that, though, there are a few concepts that are key to understanding the jQuery way of doing things.
Testing a selection
We can determine whether a selection meets certain criteria using the .is() method. The most common way to use this method is to provide a selector as its sole argument. It returns true or false depending on whether the selection matches the selector:
$( 'li' ).eq( 0 ).is( '.special' ); // false
$( 'li' ).eq( 1 ).is( '.special' ); // true
You can also pass the .is() method a jQuery object, a raw DOM element, or even a function if you need to do a more complex test. See the documentation for more details.
Getters, setters, and implicit iteration
There are many methods you can call once you've made a selection. These methods generally fall into two categories: getters and setters. Getters retrieve a piece of information from the selection, and setters alter the selection in some way. In almost all cases, getters operate only on the first element in a selection (.text() is a notable exception); setters operate on all elements in a selection, using what's known as implicit iteration.
Implicit iteration means that jQuery automatically iterates over all the elements in a selection when you call a setter method on that selection. This means that, when you want to do something to all of the elements in a selection, you don't have to call a setter method on every item in your selection — you just call the method on the selection itself, and jQuery iterates over the elements for you.
Let's say that you want to change the HTML of all of the list items on your page. To do this, we'd use the .html() method, which will change the HTML of all of the selected list items.
$( 'li' ).html( 'New HTML' );
You can also pass a function to jQuery's setter methods. This function's return value is used as the new value, and it receives two arguments: the index of the element in the selection, and the old value of the thing you're trying to change. This is useful when you need information about an element's current state in order to properly set the new state.
$( 'li' ).html(function( index, oldHtml ) {
  return oldHtml + '!!!'
});
Explicit iteration
Sometimes, the task you're trying to accomplish won't fit neatly into one of jQuery's existing methods, and you'll need to explicitly iterate over a selection. The .each() method lets you do this. In the following code, we use it to add a <b> tag at the beginning of the list item, containing the index of the list item.
$( 'li' ).each(function( index, elem ) {
  // this: the current, raw DOM element
  // index: the current element's index in the selection
  // elem: the current, raw DOM element (same as this)
  $( elem ).prepend( '<b>' + index + ': </b>' );
});
You'll notice that, inside the function that we pass to .each(), we have access to the current raw DOM element in two ways: as this and as elem. As discussed in the JavaScript Basics section, this is a special keyword in JavaScript, referring to the object that is the current context of the function. In jQuery, this almost always refers to the raw DOM element on which the function is currently operating. So, in the case of .each(), it refers to the current element in the set of elements we're iterating over.
Chaining
One of the most lucrative parts of jQuery is the ability to "chain" methods together. This means that we can call a series of methods on a selection without having to repeat the selection or store the selection in a variable. We can even make new selections based on previous selections, all without breaking the chain.

$( 'li' )
  .click(function() {
    $( this ).addClass( 'clicked' );
  })
  .find( 'span' )
    .attr( 'title', 'Hover over me' );
Chaining is possible because every setter method in jQuery returns the selection on which it was called. It's extraordinarily powerful, and it's a feature that many libraries have adopted. However, it must be used with care. Extensive chaining can make code extremely difficult to read, modify, and debug. There is no hard-and-fast rule on how long a chain should be, but even the simple chain above is probably worth refactoring for readability.
var listItems = $( 'li' );
var spans = listItems.find( 'span' );

listItems
  .click(function() {
    $( this ).addClass( 'clicked' );
  });

spans.attr( 'title', 'Hover over me' );
Conclusion
We've gotten a great overview of how jQuery ticks; in the next section, we'll take a look at how to actually start accomplishing things with it

JavaScript Basics


jQuery is built on top of JavaScript, a rich and expressive language in its own right. This section covers the basic concepts of JavaScript, as well as some frequent pitfalls for people who have not used JavaScript before. While it will be of particular value to people with no programming experience, even people who have used other programming languages may benefit from learning about some of the peculiarities of JavaScript.
Here's a simple JavaScript program that adds a message to the page:
// create a function that will greet a person,
// and assign the function to the `greet` variable
var greet = function( person, message ) {
  var greeting = 'Hello, ' + person + '!';
  log( greeting + ' ' + message );
};

// use the function to greet Jory, passing in her
// name and the message we want to use
greet( 'Jory', 'Welcome to JavaScript' );

// use the function to greet Rebecca, passing in her
// name and a different message
greet( 'Rebecca', 'Thanks for joining us' );

In the above example, we use a function called log. This is a helper function that is defined by the JavaScript that powers this site — it is not a built-in JavaScript function. You can use log in the built-in editor for this site, but you'll need to use console.log in your normal code, and then view the output in your browser's console.
You can try running this program by clicking the and it will copy the code to the built-in editor automatically. Once it's there, you can click the button to execute it; you can also make changes to it. Press the button to return to the original code.
It's OK if you don't understand everything that's going on in this program; in the rest of this section, we'll talk about variables, functions, and several other building blocks of JavaScript.
A comment about comments
Comments can be a useful tool for explaining what's happening in a piece of code. The contents of a comment will have no effect whatsoever on how your code runs. Some people like to heavily comment their code, while others prefer to include comments only to explain things that may not be immediately obvious.
JavaScript allows for single-line and multi-line comments. A single-line comment begins with //; a multi-line comment begins with /* and ends with */.
// This is a single line comment
var foo;

/*
  This is a multi-line comment. It can go on
  for several lines, like this.
 */
You'll also sometimes see multi-line comments used for inline comments:
function cornify( unicorns /* integer */, rainbows /* integer */ ) {

}
The building blocks of JavaScript
Variables
Variables are the way that we store values so we can use them later. Variables can contain any value — text, numbers, data (such as "arrays" and "objects"), even code (in the form of "functions"). We declare a variable using a var statement:
var myName = 'Rebecca';
Variable names can be just about anything, as long as they don't begin with a number and don't include a hyphen.
You can define one variable per statement:
var a = 1;
var b = 'two';
You can also define multiple variables in a single statement, by separating them with commas:
var a = 1,
    b = 'two';
Once you have assigned a value to a variable, you can use that variable whenever you want to get access to the value you stored.
log( myName ); // logs 'Rebecca'
Variables are a key ingredient in adhering to the Don't Repeat Yourself philosophy. If you need to use a value more than once, you probably want to store it in a variable.
We'll talk more about variables in the next section, Functions.
Functions
Functions are a fundamental building block of JavaScript programs; they provide a way that we can put small pieces of functionality in a neatly-wrapped package. For example, consider a function that adds two numbers:
function(a, b) {
  return a + b;
}
This function takes two arguments, a and b. It adds them together, and returns the result.
This is a valid bit of JavaScript, but as written, there's no way for us to call our function if we actually want to add two things. We can solve this by assigning our function to a variable:
var addTwoNumbers = function(a, b) {
  return a + b;
};
What we've done here is take a function expression and assign it to a variable. Now that we've done this, we can call our function by using the name of the variable:
log( addTwoNumbers(1, 1) ); // logs 2
We could also use a function declaration to give our function a name:
function addTwoNumbers(a, b) {
  return a + b;
}
This lets us call our function just like we did before, but this approach should be used with caution, as explained in this post.
Bottom line: naming functions using the function declaration approach can have unexpected results if you don't fully understand a feature of JavaScript known as hoisting. The details of hoisting are beyond the scope of this guide, but for now we'll stick to assigning function expressions to variables.
Functions and variable scope
Variables that are declared inside a function with a var statement are only available inside of the function; this is generally desirable, and all variables should be declared with a var statement unless they are intended to be global — that is, available anywhere in your code. This usually isn't what you want, unless you want it to be possible for other code to change the value of the variable.
What does it mean that a variable is only accessible inside of a function? Give the following code a try:
caution broken code
var myFunction = function() {
  var foo = 'bar';
};

myFunction();
log( typeof foo ); // logs undefined!
In the example above, if we'd tried to actually use foo outside of the function — rather than just checking its type — our browser would have reported an error, and any code after the line where we used foo would not run.
The next example shows how we can have two variables with the same name, as long as each variable exists in a separate scope. In this example, we declare the variable foo and assign it the value 'qux'; then, inside a function, we declare another variable named foo, and assign it the value 'bar'. Notice how, outside of the function, the variable foo does not change, even when we create the variable foo inside the function.
var foo = 'qux';
var myFunction = function() {
  var foo = 'bar';
};

log( foo ); // logs 'qux'
myFunction();
log( foo ); // still logs 'qux'
Despite the fact that both variables have the same name, JavaScript considers the two variables as completely separate entities. This is just one of many reasons that it's important to give your variables meaningful names.
Variable scope is one of the fundamental concepts of JavaScript, and one of the concepts that people struggle with often. It's important to remember that:
you should almost always declare variables with a var statement
variables declared inside of a function using a var statement are not available outside of that function
variables declared without a var statement are always global
Beware that variables that are not declared with the var keyword are implicitly global! In the following example, the variable a is available outside the function because it wasn't declared with the var keyword — this is generally undesirable.
caution unsafe code
function test() {
  a = 1;
}

test();

log( a ); // logs 1
Objects
As it turns out, most everything we work with in JavaScript is an object — in fact, there are only five kinds of values that are not objects:
strings (text)
booleans (true/false)
numbers
undefined
null
These values are called primitives, but even some of these values can be treated as though they were objects — more on that in a minute. But what's an object? Let's look at an example of a simple object:

var person = {
  firstName : 'Boaz',
  lastName : 'Sender'
};
The object we've created here has two properties: firstName and lastName. We've created it using the "object literal syntax" — that is, by putting a set of key-value pairs in { }. Note that, for each pair, there is a colon between the key and the value, and there is a comma between each pair. Note also that there is not a comma after the last key-value pair — if you accidentally include a comma after the last pair, you will get errors in older browsers.
Accessing properties
We've stored our object in a variable named person, which makes it easy to access its properties, using either dot notation or bracket notation.
var person = {
  firstName : 'Boaz',
  lastName : 'Sender'
};

log( 'First name: ' + person.firstName );     // dot notation
log( 'Last name: ' + person[ 'lastName' ] );  // bracket notation
You'll notice that with bracket notation, we used a quoted string for the property name we were after; with dot notation, we just used the literal property name, without quotes. Bracket notation is a useful approach if, say, the name of the property you're after is stored in a variable:
var person = {
  firstName : 'Boaz',
  lastName : 'Sender'
};

var prop = 'lastName';

log( 'Last name: ' + person[ prop ] );
Once we've created an object, we can modify its properties.
var person = {
  firstName : 'Boaz',
  lastName : 'Sender'
};

person.firstName = 'Ben';
person.lastName = 'Alman';

log( 'First name: ' + person.firstName );
log( 'Last name: ' + person.lastName );
This aspect of JavaScript is both blessing and curse. It means that objects are incredibly flexible, but it also means that there's no "privacy." Any code can easily overwrite the value of a property of any object to which it has access — another reason why it's important to keep variables out of the global scope unless it's OK for other code to modify them.
Object methods
Methods of an object are just properties whose values are functions. Let's add a .greet() method to our person object:
var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function(name) {
    log( 'Hi, ' + name );
  }
};

person.greet( person.firstName );
The .greet() method in the example above received a string, name, as its argument. When we called the method, though, we simply passed in the value of the firstName property of the person object. If we wanted a super-flexible .greet() method that could greet anyone, this might be what we want. But it probably makes more sense that the .greet() method will greet the particular person.
The meaning of this
Inside of a method — indeed, inside of any function — there is a special keyword available to us: this. It refers to the object that is the context in which the function was called.
When we call person.greet(), the context object is person itself. This means that we can use this to access a property of the person object from directly within the .greet() method.
The meaning of this can be incredibly perplexing to new JavaScript developers, and you should take comfort in knowing that jQuery largely makes it so that you don't need to understand it for a while. However, no discussion of objects and methods is complete without talking about this at least a little. In short, if this section is confusing, feel free to skip to  Objects in jQuery, and come back to it when you're ready.
Let's look at how we could use this in our method.
var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function() {
    log( 'Hi, ' + this.firstName );
  }
};

person.greet();
Not so confusing so far, right? The confusion arises because the meaning of this can change — as mentioned above, it depends on the context in which the function was called! Consider the following code:
caution broken code
var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function() {
    log( 'Hi, ' + this.firstName );
  }
};

var sayIt = person.greet; // store the method in a variable

sayIt(); // logs 'Hi, undefined' -- uh-oh
When we store the .greet() method in a variable sayIt and then call sayIt(), the context object changes to the global window object, not the person object. Since the window object doesn't have a property firstName, we get undefined when we try to access it.
What's a developer to do? First, be aware that storing object methods in variables can have unintended consequences for the meaning of this. Second, be aware that you can force the meaning of this to be what you want it to be, using the .call() or .apply() method on the function itself.
var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function() {
    log( 'Hi, ' + this.firstName );
  }
};

var sayIt = person.greet;

sayIt.call( person );
Both .call() and the very similar .apply() method also let us pass arguments to the function we're invoking. Imagine if our greet method took some arguments; we could pass those arguments using .call() like this:
var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function(greeting, punctuation) {
    log( greeting + ', ' + this.firstName + punctuation );
  }
};

var sayIt = person.greet;

sayIt.call( person, 'Hello', '!!1!!1' );
We could do the same thing using .apply(), but we'd pass the arguments within a single array instead of as separate arguments:
var person = {
  firstName : 'Boaz',
  lastName : 'Sender',
  greet : function(greeting, punctuation) {
    log( greeting + ', ' + this.firstName + punctuation );
  }
};

var sayIt = person.greet;

sayIt.apply( person, [ 'Hello', '!!1!!1' ] );
For more details about .call() and .apply(), see the MDN documentation on .call() and .apply().
Objects in jQuery
We've barely scratched the surface of objects, but you now know the basics you'll need to know to work with objects as you learn jQuery. In basic jQuery, you'll mainly use objects to provide configuration options. For example, you can provide an object to change several CSS properties on an element at once:
$('#main').css({
  color: 'red',
  border: '1px solid blue'
});
As far as this, jQuery tends to take control over its meaning. In the case of event handlers, this will refer to the element to which you bound the handler; in the case of iterating over a set of elements in a selection, this will refer to the current element in the iteration. You shouldn't need to worry about understanding this too much during your initial learning — it's just a good thing to keep in mind as your learning continues.
Arrays
Arrays are a type of object used to store lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays.
The preferred way to create an array is to use the array literal notation:
var myArray = [ 'a', 'b', 'c' ];
You will sometimes see code that creates an array using the new Array('a', 'b', 'c') construct. This is generally frowned upon among JavaScript developers; it provides no advantages over the literal construct, and has some disadvantages, such as the fact that new Array(3) will create an array with three undefined elements, rather than the array [ 3 ].
You can access properties of arrays (sometimes called elements) with the same bracket notation we used for objects. Each element is automatically given a name based on its position in the array. Be careful, though: the numbers start at zero! Lets look at an example array with three elements:
caution antipattern
var myArray = [ 'a', 'b', 'c' ];
var firstItem = myArray[ "0" ]; // access the first item
When retrieving array elements, it's usually much more convenient to use numbers to specify the index of the element you're after:
var myArray = [ 'a', 'b', 'c' ];
var firstItem = myArray[ 0 ];

var secondItem = myArray[ 1 ]; // access the item at index 1
log( secondItem ); // logs 'b'
We can determine how many items are in an array by accessing an array's length property:
var myArray = [ 'a', 'b', 'c' ];
var len = myArray.length;
log( len ); // logs 3
for Loops: Iterating over Arrays
Since we know how to get the length of an array, and we know that an array's first item is at index 0, we can iterate over the items in an array using a for loop:
var myArray = [ 'a', 'b', 'c' ];
var i;
var len = myArray.length;

// we'll use the variable i as our index; it starts at 0,
// and we increment it by 1 (using i++) until i is no longer
// less than the length of the array
for (i = 0; i < len; i = i + 1) {
  log( 'item at index ' + i + ' is ' + myArray[ i ] );
}
Logic and Truthiness
JavaScript provides if and else, as well as the ternary operator, to allow us to do certain things only when certain conditions are met. JavaScript determines whether a condition is met by evaluating a value or an expression for its "truthiness." Because JavaScript is a dynamically typed language, we can use any value or combination of values; however, the rules by which JavaScript determines whether a given value or expression is true or false can be confusing.
Here's an example of a simple if statement in JavaScript. It evaluates the truthiness of the number 1; because 1 is truthy, the code inside the block — delineated by { and } — will run.
if ( 1 ) {
  // this code will run!
  log( '1 is truthy' );
}
As it turns out, most values in JavaScript are truthy — in fact, there are only five values in JavaScript that are falsy:
undefined (the default value of declared variables that are not assigned a value)
null
NaN ("not a number")
0 (the number zero)
'' (an empty string)
When we want to test whether a value is "falsy," we can use the ! operator:
var a = '';

if ( !a ) {
  // this code will run if a is falsy
  log( 'a was falsy' );
}
The value NaN is a special case. Values that are NaN will evaluate to false in a simple conditional expression:
var notANumber = 'four' - 'five';

if ( !notANumber ) {
  // this code will run
  log( '!notANumber was truthy' );
}
However, if we compare the value NaN to false, we get back a falsy value:
var notANumber = 'four' - 'five';

if ( notANumber == false ) {
  // this code will not run!
  log( 'notANumber was falsy' );
} else {
  // this code will run
  log( 'notANumber was truthy' );
}
It's important to remember that all other values aside from the five values listed above are truthy. This includes empty arrays, empty objects, all non-empty strings (including the string '0'), and all numbers other than 0.
It is possible to write single-line if and else statements without using curly braces. This practice is discouraged, as it can make code difficult to read and maintain. It is mentioned here simply because you may encounter it in others' code.
Logical Operators
Logical operators allow you to evaluate operands using AND (&&) and OR (||) operations.
var foo = 1;
var bar = 0;
var baz = 2;

foo || bar;     // returns 1, which is truthy
bar || foo;     // returns 1, which is truthy

foo && bar;     // returns 0, which is falsy
foo && baz;     // returns 2, which is truthy
In the case of the || operator, the value returned is the first value that proves the statement truthy, or the last value. In the case of the && operator, the value returned is the first value that proves the statement falsy, or the last value.
You'll sometimes see logical operators used as a clever way to control code execution:
foo && bar();   // runs bar() only if foo is truthy

var bar = baz || createBar();  // use baz as value for bar unless
                               // baz is falsy; in that case, create bar
This style is elegant and pleasantly terse, but it can be difficult to read, especially for beginners. You should be aware of what it means if you come across it in code, but you may want to refrain from using this style at first, and use traditional if and else statements for clarity.
The Ternary Operator
Often, you'll want to set a variable's value differently depending on whether a certain condition is true or false. Of course, you could achieve this with an if and else statemenet:
caution antipattern
var propertyName;

if (dim === 'width') {
  propertyName = 'clientWidth';
} else {
  propertyName = 'clientHeight';
}
However, the ternary operator provides a much more succinct way of conditionally setting the value of a variable:
var propertyName = ( dim === 'width' ) ? 'clientWidth' : 'clientHeight';
The statement before the ? is evaluated for its truthiness. If it is truthy, the first value ('clientWidth') is used as the value of the propertyName variable; otherwise, the second value ('clientHeight') is used.
JavaScript gotchas
In addition to variable scope and truthiness, there are many other gotchas in JavaScript. Let's take a look at a few of them.
Naming things
Valid names in JavaScript begin with a letter or certain symbols, followed by zero or more letters, digits, underscores, or symbols. Names may not begin with numbers, and may not include hyphens. Besides these rules, you can name your variables however you'd like! All of these names are valid:
a
a1
foo_bar
fooBarBaz
$fooBar
_foo
__foo__
There are some conventions that people use when naming things in JavaScript, but these are optional, and don't have any effect on how the code works:
Names that begin with _ are usually "private" (more on this later).
Names that begin with uppercase letters are usually "constructors," used to create new instances of objects (more on this later as well).
In code that uses jQuery, names that begin with $ usually refer to jQuery objects.
Reserved words
JavaScript reserves certain words for its own use; you should avoid using these words for the names of things.
abstract boolean break byte case catch char class const continue debugger
default delete do double else enum export extends false final finally float
for function goto if implements import in instanceof int interface long
native new null package private protected public return short static super
switch synchronized this throw throws transient true try typeof var
volatile void while with
If you must use one of these names as the name of an object property, you should quote the property name:
var myObject = {
  'class': 'tasty'
};

Operations on numbers and strings
Working with numbers in JavaScript can be a bit unpredictable, due to the way JavaScript represents numbers internally. For example, addition using decimals can have results that are close but not quite accurate:
log( 0.0001 + 0.0002 ); // 0.00030000000000000003
This won't come up often when working with jQuery, but it's an important issue to be aware of, especially if you're working with decimal numbers like currency. If you're doing mathematical operations that require precision, you should convert values to integers before working with them, and convert them back when you're done.
JavaScript is a loosely-typed language. If you try to do mathematical operations using values that are not numbers, JavaScript will not throw errors, and the result may not be what you'd expect.

Wednesday 19 December 2012

binding values webservice to kendomobileListView

Code in Service class

public class mobileAppWebService : System.Web.Services.WebService
{
    public mobileAppWebService()
    {  
    }
    SqlConnection con = new SqlConnection("Data Source=SHANKAR-PC\\SQLEXPRESS;Initial Catalog=Occumen;Integrated Security=True");  
    [WebMethod]
    public List<EmpName> GetData()
    {
        SqlDataAdapter da = new SqlDataAdapter("select ename from emp", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "emp");
        return LstEmpNames(ds);
    }

    public List<EmpName> LstEmpNames(DataSet ds)
    {
        List<EmpName> objenamelst = new List<EmpName>();
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            EmpName objemp = new EmpName();          
            objemp.ename = ds.Tables[0].Rows[i][0].ToString();
            objenamelst.Add(objemp);
        }
        return objenamelst;
    }  
}
Code in .htm page

<head>
    <title>List View DataBinding</title>
    <script src="Scripts/jquery.min.js" type="text/javascript"></script>
    <script src="Scripts/kendo.mobile.min.js" type="text/javascript"></script>
    <script src="content/shared/js/console.js" type="text/javascript"></script>
    <link href="styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
    <link href="styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div data-role="view" id="flat" data-layout="databinding" data-init="mobileListViewDataBindInitFlat"
        data-title="ListViewForContacts">
        <ul id="flat-listview">
        </ul>
    </div>
    <div data-role="view" id="grouped" data-init="mobileListViewDataBindInitGrouped"
        data-transition="" data-title="ListViewForGroupedContacts" data-layout="databinding">
        <ul id="grouped-listview">
        </ul>
    </div>
    <div data-role="layout" data-id="databinding">
        <header data-role="header">
            <div data-role="navbar">
                <span data-role="view-title"></span>
            </div>
        </header>
        <div data-role="footer">
            <div data-role="tabstrip">
                <a href="#flat" data-icon="stop">Flat </a><a href="#grouped" data-icon="organize">Grouped</a>
            </div>
        </div>
    </div>
    <script type="text/x-kendo-template" id="ListViewTemplate">      
        <div class="DetData">
           ${ename}
        </div>
    </script>
    <script type="text/javascript">
        function mobileListViewDataBindInitFlat() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "mobileAppWebService.asmx/GetData",
                endlessScroll: true,
                dataType: "json",
                success: function (data) {
                    $("#flat-listview").kendoMobileListView({
                        dataSource: data.d,
                        template: $("#ListViewTemplate").html()
                    });
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
        var app = new kendo.mobile.Application(document.body);
    </script>
</body>


Monday 10 December 2012

kendo-ui information



1. AutoComplete
Remote method:-
<input id="autoComplete" />

<script>

$(function() {

    $("#autoComplete").kendoAutoComplete({
        dataSource: {
            transport: {
                read: {
                    url: "ControllerName/MethodName"
                }
            },
            serverFiltering: true
        },
        separator: ", "
        dataTextField: "ProductName"
     });

});

</script>

Local Method:-

var data = ["Item1", "Item2", "Item3"];
$("#autoComplete").kendoAutoComplete({
   dataSource: data
});
2. Calender
Local Method :-
<div id="calendar"></div>
And in the script tag just write the below code
Initialize the Calendar via a jQuery ID selector
$(document).ready(function(){
    $("#calendar").kendoCalendar();
});

3. ComboBox
There are two ways to create a ComboBox:
a) From a <select> element with HTML to define the list items
b) From an <input> element with databinding to define the listitems
First create a list like below
var people =
            [
                { Id: 1, FirstName: "John", LastName: "Doe" },
                { Id: 2, FirstName: "Jayne", LastName: "Smith" }
            ];
Now we show the list to the combobox
$('#comboBox').kendoComboBox({
    dataTextField: 'FirstName',
    dataValueField: 'Id',
    template: "<table><tr><td width='100px'>${ FirstName}</td><td width='100px'>${ LastName }</td></tr></table>",
    dataSource: { data: people }
});

Second way of assigning the Data to ComboBox

    $("#comboBox").kendoComboBox({
        dataTextField: "text",
        dataValueField: "value",
        dataSource: [
            { text: "Item1", value: "1" },
            { text: "Item2", value: "2" }
        ]
    });

<select> tag with pre-defined structure
<select id="comboBox">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>
</select>

<script>
    $(document).ready(function(){
        $("#comboBox").kendoComboBox();
    });
</script>

Remote data service
$(document).ready(function() {
    $("#comboBox").kendoComboBox({
        index: 0,
        dataTextField: "Name",
        dataValueField: "Id",
        filter: "contains",
        dataSource: {
            type: "odata",
            serverFiltering: true,
            serverPaging: true,
            pageSize: 20,
            transport: {
                read: "http://odata.netflix.com/Catalog/Titles"
            }
        }
    });
});
o Here in the Catalog is the controller name and Titles is the method in that controller.
Customization of the combobox
<input id="comboBox" />
<!-- Template -->
<script id="scriptTemplate" type="text/x-kendo-template">
    # if (data.BoxArt.SmallUrl) { #
        <img src="${ data.BoxArt.SmallUrl }" alt="${ data.Name }" />
        Title:${ data.Name }, Year: ${ data.Name }
    # } else { #
        <img alt="${ data.Name }" />
        Title:${ data.Name }, Year: ${ data.Name }
    # } #
</script>

<!-- ComboBox initialization -->
<script>
    $(document).ready(function() {
        $("#comboBox").kendoComboBox({
            autoBind: false,
            dataTextField: "Name",
            dataValueField: "Id",
            template: $("#scriptTemplate").html(),
            dataSource: {
                type: "odata",
                serverFiltering: true,
                serverPaging: true,
                pageSize: 20,
                transport: {
                    read: "http://odata.netflix.com/Catalog/Titles"
                }
            }
        });
    });
</script>

4. Date Picker
<input id="datePicker" />

In the script tag

$(document).ready(function(){
    $("#datePicker").kendoDatePicker();
});

Giving minimum and maximum date
$(document).ready(function(){
    $("#datePicker").kendoDatePicker({
       value: new Date(),
       min: new Date(1950, 0, 1),
       max: new Date(2049, 11, 31)
    })
});

Start view and Navigation depth

$("#datePicker").kendoDatePicker({
    start: "year",
    depth: "year"
});

Same Properties can be applicable to calendar also.

5. Date Time Picker
<input id="dateTimePicker" />

And write the below code in the script tag.

$(document).ready(function(){
    $("#dateTimePicker").kendoDateTimePicker();
});

Giving minimum and maximum to the datetimepicker.

$(document).ready(function(){
    $("#dateTimePicker").kendoDateTimePicker({
       value: new Date(2000, 10, 10, 10, 0, 0),
       min: new Date(1950, 0, 1, 8, 0, 0),
       max: new Date(2049, 11, 31, 18, 0, 0)
    })
});

Time Format

$("#dateTimePicker").kendoDateTimePicker({
    timeFormat: "hh:mm:ss tt" //this format will be used to format the predefined values in the time list.
});
The first rendered view can be defined with "start" option. Navigation depth can be controlled with "depth" option. Predefined views are:
"month" - shows the days from the month
"year" - shows the months of the year
"decade" - shows the years from the decade
"century" - shows the decades from the century
o Start and Navigation depth
$("#dateTimePicker").kendoDateTimePicker({
    start: "year",
    depth: "year"
});

Time intervals (in minutes) between values in the time drop-down list
$("#dateTimePicker").kendoDateTimePicker({
    interval: 15
})
6. DropDownList
There are two ways to create a DropDownList:
o From a <select> element with HTML to define the list items
o From an <input> element with databinding to define the listitems
Declaring the tag
<input id="dropDownList" />
Write the below code in the script tag
    $(document).ready(function() {
    $("#dropDownList").kendoDropDownList({
        dataTextField: "text",
        dataValueField: "value",
        dataSource: [
            { text: "Item1", value: "1" },
            { text: "Item2", value: "2" }
        ]
    });
   });

The above code was written statically (Hard coded)
The below code was written by using <select> tag
<select id="dropDownList">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>
</select>

<script>
    $(document).ready(function(){
        $("#dropDownList").kendoDropDownList();
    });
</script>

Binding data remote
$(document).ready(function() {
    $("#titles").kendoDropDownList({
        index: 0,
        dataTextField: "Name",
        dataValueField: "Id",
        dataSource: {
            type: "odata",
            transport: {
                read: "http://odata.netflix.com/Catalog/Titles"
            }
        }
    });
});
Accessing the existing dropdownlist
var dropDownList = $("#dropDownList").data("kendoDropDownList");

7. Editor
The Editor allows users to create rich text content by means of a WYSIWYG interface. The generated widget value is an XHTML Markup.
Declaring the Editor

  <textarea id="editor" rows="10" cols="30"></textarea>

Write the below code in the script tag.
$(document).ready(function(){
      $("#editor").kendoEditor({
         tools: [
             "bold",
             "italic",
             "underline",
             "foreColor"
         ]
      });
  });
Customise the editor tool
$("#editor").kendoEditor({
       tools: [
           {
               name: "toolName",
               tooltip: "Custom editor tool",
               exec: function(e) {
                   var editor = $(this).data("kendoEditor");

                   // execute command
               }
           }
       ]
   });
Image Browser
  The image browser tool can be configured through the imagebrowser configuration option
$(document).ready(function(){
     $("#editor").kendoEditor({
         imageBrowser: {
            transport: {
                read: "imagebrowser/read",
                destroy: "imagebrowser/destroy",
                create: "imagebrowser/createDirectory",
                uploadUrl: "imagebrowser/upload",
                thumbnailUrl: "imagebrowser/thumbnail"
                imageUrl: "/content/images/imagebrowser configuration option"
            }
         }
     });
  });

8. Grid
There are two primary ways to create a Kendo Grid:
o From an existing HTML table element, defining columns, rows, and data in HTML.
o From an HTML div element, defining columns and rows with configuration, and binding to data.

Creating Grid by using HTML TABLE elements
<!-- Define the HTML table, with rows, columns, and data -->
 <table id="grid">
  <thead>
      <tr>
          <th data-field="title">Title</th>
          <th data-field="year">Year</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Star Wars: A New Hope</td>
          <td>1977</td>
      </tr>
      <tr>
          <td>Star Wars: The Empire Strikes Back</td>
          <td>1980</td>
      </tr>
  </tbody>
 </table>
And initializing the Kendo Grid
$(document).ready(function(){
      $("#grid").kendoGrid();
  });
Creating the Grid by using HTML DIV element
<div id="grid">
 </div>
Initialize the Kendo Grid and configure columns & data binding
   $(document).ready(function(){
      $("#grid").kendoGrid({
          columns:[
              {
                  field: "FirstName",
                  title: "First Name"
              },
              {
                  field: "LastName",
                  title: "Last Name"
          }],
          dataSource: {
              data: [
                  {
                      FirstName: "Joe",
                      LastName: "Smith"
                  },
                  {
                      FirstName: "Jane",
                      LastName: "Smith"
              }]
          }
      });
  });
Enabling Grid paging, sorting, grouping, and scrolling
$(document).ready(function(){
      $("#grid").kendoGrid({
         groupable: true,
         scrollable: true,
         sortable: true,
         pageable: true
      });
  });
Grid UI Virtualization

When binding to large data sets or when using large page sizes, reducing active in-memory DOM objects is important for performance. Kendo Grid provides built-in UI virtualization for highly optimized binding to large data sets. Enabling UI virtualization is done via simple configuration.

This can be achieved by below code

   $(document).ready(function(){
      $("#grid").kendoGrid({
         scrollable: {
             virtual: true
         }
      });
  });

Configure CRUD for Remote datasource
var dataSource = new kendo.data.DataSource({
   transport: {
     read:   "/ControllerName",
     update: {
        url: "/ ControllerName /MethodName",
        type: "POST"
     },
     destroy: {
         url: "/ ControllerName /MethodName ",
         type: "POST"
      },
      create: {
          url: "/ ControllerName /MethodName ",
          type: "POST"
       }
     },
     // determines if changes will be send to the server individually or as batch
     batch: true
     //...
})

Declare fields definition through the datasource schema
var dataSource = new kendo.data.DataSource({
    //..
    schema: {
      model: {
         id: "ProductID",
         fields: {
             ProductID: {
                //this field will not be editable (default value is true)
                editable: false,
                // a defaultValue will not be assigned (default value is false)
                nullable: true
             },
             ProductName: {
                validation: { //set validation rules
                    required: true
                }
             },
             UnitPrice: {
                 //data type of the field {Number|String|Boolean} default is String
                 type: "number",
                 // used when new model is created
                 defaultValue: 42,
                 validation: {
                    required: true,
                    min: 1
                 }
            }
        }
    }
  }
});
Kendo Grid Editable
$("#grid").kendoGrid({
      dataSource: dataSource,
      editable: true
});
Another way
$("#grid").kendoGrid({
      dataSource: dataSource,
      editable: { //disables the deletion functionality
         update: true,
         destroy: false
      }
});
Enable to insert a new record the toolbar should be configured
$("#grid").kendoGrid({
     dataSource: dataSource,
     toolbar: ["create", "save", "cancel"],
     editable: true
});
Delete a record a delete command column should be given
$("#grid").kendoGrid({
     dataSource: dataSource,
     columns: [
        "ProductName",
        "UnitPrice",
        "UnitsInStock",
        {
            command: "destroy"
        }],
     editable: true
 });
9. ListView
Declaring the Listview by HTML tag
<ul id="listView"></ul>
Initialising the data to Listview in the script tag
 $(document).ready(function() {
      $("#listView").kendoListView({
          template: "<li>${FirstName} ${LastName}</li>",
          dataSource: {
              data: [
                  {
                      FirstName: "Joe",
                      LastName: "Smith"
                  },
                  {
                      FirstName: "Jane",
                      LastName: "Smith"
              }]
          }
      });
  });
Enabling Listview Paging, Navigation, Selection and Editing
 $(document).ready(function() {
      $("#listView").kendoListView({
         pageable: true,
         selectable: true,
         navigatable: true,
         editable: true,
         template: "<li>${FirstName}</li>",
         editTemplate: '<li><input type="text" data-bind="value:FirstName" name="FirstName" required="required"/></li>'
      });
  });


10. Menu
The Menu displays hierarchical data as a multi-level menu. It provides rich styling for unordered lists of items, and can be used for both navigation and executing JavaScript commands. Items can be defined and initialized from HTML, or the API can be used to add and remove items.

Declaring the Menu
<ul id="menu">
    <li>Item 1
        <ul>
            <li>Item 1.1</li>
            <li>Item 1.2</li>
        </ul>
    </li>
    <li>Item 2</li>
</ul>
Initialising the Menu in the Script
$(document).ready(function() {
    $("#menu").kendoMenu();
});

Initialising  the Menu by JSON object
$(document).ready(function() {
 $("#menu").kendoMenu({
  dataSource:
    [{
        text: "Item 1",
        url: "http://www.kendoui.com"                // Link URL if navigation is needed, optional.
    },
    {
        text: "<b>Item 2</b>",
        encoded: false,                                 // Allows use of HTML for item text
        content: "text"                                 // content within an item
    },
    {
        text: "Item 3",
        imageUrl: "http://www.kendoui.com/test.jpg", // Item image URL, optional.
        items: [{                                    // Sub item collection
             text: "Sub Item 1"
        },
        {
             text: "Sub Item 2"
        }]
    },
    {
        text: "Item 4",
        spriteCssClass: "imageClass3"                // Item image sprite CSS class, optional.
    }]
 })
});
Menu Customisation
Animation for Open Behaviour
By default, the Menu uses a slide animation to expand and reveal sub-items as the mouse hovers. Animations can be easily customized using configuration properties, changing the animation style and delay. Menu items can also be configured to open on click instead of on hover.

$("#menu").kendoMenu({
    animation: {
        open: { effects: "fadeIn" },
        hoverDelay: 500
    },
    openOnClick: true
});
Configuring the Menu Items
var menu = $("#menu").kendoMenu().data("kendoMenu");
menu.insertAfter(
    { text: "New Menu Item" },
    menu.element.children("li:last")
);
11. NumericTextBox
Declaring the NumericTextBox
<input id="textBox" />
Initialising the NumericTextBox
$(document).ready(function(){
    $("#textBox").kendoNumericTextBox();
});

12. TabStrip
A TabStrip displays a collection of tabs with associated content. It is composed of an unordered list of items - representing tabs - and a collection of div elements, which contain the content for each tab.
Declaring the TabStrip
<div id="tabStrip">
    <ul>
        <li>First tab</li>
        <li>Second tab</li>
    </ul>
    <div>First tab content</div>
    <div>Second tab content</div>
</div>
Initialising the TabStrip
$(document).ready(function() {
    $("#tabStrip").kendoTabStrip();
});
Initialising the TabStrip using JSON
$(document).ready(function() {
    $("#tabstrip").kendoTabStrip({
        dataTextField: "text",
        dataContentField: "content",
        dataUrlField: "url",
        dataImageUrlField: "imageUrl",
        dataSpriteCssClass: "spriteCssClass",
        dataContentUrlField: "contentUrl",
        dataSource:
        [{
            text: "Item 1",
            url: "http://www.kendoui.com"               // Link URL if navigation is needed, optional.
        },
        {
            text: "Item 2",
            content: "text"                             // Content for the content element
        },
        {
            text: "Item 3",
            contentUrl: "partialContent.html"           // From where to load the item content
        },
        {
            text: "Item 4",
            imageUrl: "http://www.kendoui.com/test.jpg" // Item image URL, optional.
        },
        {
            text: "Item 5",
            spriteCssClass: "imageClass3"               // Item image sprite CSS class, optional.
        }]
    });
});

Selecting Tab manually using HTML
<div id="tabstrip">
    <ul>
        <li class="k-state-active">First Tab</li>
        <li>Second Tab</li>
    </ul>
    <div></div>
    <div></div>
</div>
Initialize a TabStrip and select first tab via select(element)
$(document).ready(function(){
    var tabstrip = $("#tabstrip").kendoTabStrip().data("kendoTabStrip");
    tabstrip.select(tabstrip.tabGroup.children("li:first"));
});
Initialize a TabStrip and select first tab via select(index)
$(document).ready(function(){
    var tabstrip = $("#tabstrip").kendoTabStrip().data("kendoTabStrip");
    tabstrip.select(1);
});
13. TreeView

A TreeView can be created in two ways:
o Define a hierarchical list with static HTML
o Use dynamic data binding either to a local or remote data source.
Hierarchal List declaring in HTML
<ul id="treeView">
    <li>Item 1
        <ul>
            <li>Item 1.1</li>
            <li>Item 1.2</li>
        </ul>
    </li>
    <li>Item 2</li>
</ul>

Initialising the TreeView
$(document).ready(function() {
    $("#treeView").kendoTreeView();
});

Creating Local Datasource
<div id="treeView"></div>
Initialsing the TreeView
$(document).ready(function() {
    $("#treeView").kendoTreeView({
        dataSource: [
            {
                text: "Item 1",
                items: [
                    { text: "Item 1.1" },
                    { text: "Item 1.2" }
                ]
            },
            { text: "Item 2" }
        ]
    })
});

Creating Remote
$("#treeView").kendoTreeView({
    dataSource: {
        transport: {
            read: {
                url: "http://demos.kendoui.com/service/Employees",
                dataType: "json"
            }
        },
        schema: {
            model: {
                id: "EmployeeId",
                hasChildren: "HasEmployees"
            }
        }
    }
})

Items Definition can have following properties
var item = {
    text: "Item text",

    // if specified, renders the item as a link. (<a href=""></a>)
    url: "http://docs.kendoui.com/",

    // renders a <img class="k-image" src="/images/icon.png" />
    imageUrl: "/images/icon.png",

    // renders a <span class="k-sprite icon save" />
    spriteCssClass: "icon save",

    // specifies whether the node text should be encoded or not
    // useful when rendering node-specific HTML
    encoded: false,

    // specifies whether the item is initially expanded
    // (applicable when the item has child nodes
    expanded: true,

    // specifies whether the item is initially selected
    selected: true,

    // indicates the sub-items of the item
    items: [
        { text: "Subitem text" }
    ]
};

Getting the Node datain the select event handler
function onSelect(e) {
    // `this` refers to the TreeView object
    var dataItem = this.dataItem(e.node);

    console.log("Selected node with id=" + dataItem.id);
}

$("#treeview").kendoTreeView({
    dataSource: [
        { id: 1, text: "Item 1", items: [
            { id: 3, text: "Item 3" }
        ] },
        { id: 2, text: "Item 2" }
    ],
    select: onSelect
});

Reloading child nodes when nodes are expanded
function onExpand(e) {
    var dataItem = this.dataItem(e.node);

    dataItem.loaded(false);
}

$("#treeview").kendoTreeView({
    dataSource: remoteDataSource,
    expand: onExpand
});
Enabling drag-and-drop for TreeView nodes
$("#treeView").kendoTreeView({
    dragAndDrop: true
});
14. Windows
A Window displays content in a modal or non-modal HTML window. By default, a Window can be moved, resized, and closed. Its content can also be defined with either as static HTML or loaded dynamically via AJAX.
A Window can be initialized from virtually any DOM element. During initialization, the targeted content will automatically be wrapped in the div element of the Window.

Declaring the Windows
<div id="window">
    Content of the Window
</div>
Initialising the Windows
$(document).ready(function() {
    $("#window").kendoWindow();
});
Create a modal Window with all user actions enabled
$("#window").kendoWindow({
    actions: ["Custom", "Refresh", "Maximize", "Minimize", "Close"],
    draggable: false,
    height: "300px",
    modal: true,
    resizable: false,
    title: "Modal Window",
    width: "500px"
});
Custom actions
 $("#window").kendoWindow({
      actions: ["Custom", "Minimize", "Maximize", "Close"],
      title: "Window Title"
  }).data("kendoWindow").wrapper.find(".k-i-custom").click(function(e) {
      alert("Custom action button clicked");
      e.preventDefault();
  });

<h3>Positioning and Opening a Window</h3>
<p>
 In some scenarios, it is preferable to center a <strong>Window</strong> rather than open it near the HTML
 element used to define the content. It is also common to open a <strong>Window</strong> as the result of the
 action of a user rather than on the load event of a page. The <strong>Window</strong> API provides methods for
 handling these scenarios.
</p>

Centering a Window and opening on button click

<div id="window">
    Content of the Window
</div>
<button id="openButton">Open Window</button>
Initialize Window, center, and configure button click action
$(document).ready(function(){
    var win = $("#window").kendoWindow({
        height: "200px",
        title: "Centered Window",
        visible: false,
        width: "200px"
    }).data("kendoWindow");
});

$("#openButton").click(function(){
    var win = $("#window").data("kendoWindow");
    win.center();
    win.open();
});