I have found that if I don’t give myself a deadline then I have a hard time concentrating on something to actually get it done. I told Anita Luthra, the chairman of my local .NET user group http://triaddev.org that I’d be happy to do a talk whenever she needed. She asked what topics and I threw out jQuery along with some others. She liked the idea and so I’ll be presenting I presented on jQuery on Tuesday, September 14th.
Anyway, I had fooled with jQuery some but definitely didn’t consider myself proficient at it by any stretch. I wanted to sit down and really pull through it and see what all I could do with this cool framework. I despise javaScript. I mean, I really despise it. I did write my own ajax callback code before there were many frameworks like Anthem or the ASP.NET AJAX library. It was doable, but it wasn’t fun – at least I didn’t find it enjoyable.
jQuery is Awesome
jQuery changes all of that for me. I enjoy CSS. Well, I like the idea behind CSS. I don’t really enjoy pushing pixels around the screen too much but I like having the control to do so if I need to. I’ve always liked the selectors and jQuery utilizes those same selectors along with XPath to obtain different DOM elements on the page. This made it an instant win with me. But that is only one part of the story.
jQuery is only made up of one function – jQuery(); All the functions inside of jQuery return a jQuery object. This allows chaining and it is very powerful, intuitive and just plain awesome. We will talk about chaining a little later.
javaScript allows you to create a shortcut for a certain function. $ is a shortcut for the jQuery function so instead of having to type jQuery(…); you can type $(…); Now that is pretty slick.
It is all about selection. If you know CSS, you know how to use jQuery. Learn selectors because it will save you a world of hurt and lot of programming. If there are things that just can’t be done with a CSS selector, then an XPath expression may be beneficial. The actual selector engine inside of jQuery is Sizzle. Sizzle was extracted from jQuery to become its own stand alone library if you didn’t want to use jQuery itself. Check it out at http://sizzlejs.com/ and see all of the cool ways you can select items. Very useful documentation.
CSS Refresher
Now would be a good time for a refresher on CSS. CSS is made up of Selectors and Declarations.
p { color: red; text-align: center; }
p is the selector
There are two Declarations in this example. Each Declaration has a property and a value. The Declaration is what we use to style the HTML. In the above example, whenever a paragraph element is found it will be centered and red in color. Other typical items to select on are ids (i.e. #message) and classes (i.e. .required).
More information on CSS can be found at http://www.w3schools.com/css/
Since jQuery is just a framework built inside of javaScript to make working with javaScript easier, it makes sense that we have a basic understanding of a few things inside of javaScript.
javaScript is a dynamic language. Unlike C# you do not need to to associate a certain variable with a particular type. You don’t say this is a string and this is an int and this is a decimal or float, the language determines what the type is based on the data assigned to it at run time. There is no compiling a dynamic language. It is interpreted when it is ran.
JavaScript Basics
Declaring global variables in javaScript is as simple as:
myGlobalVariable = "Some Global Value";
Notice there was no type declared. To declare a local variable you do the following:
var myLocalVariable = "Some Local Value";
By putting the var keyword in front of the variable, it lets jQuery know this is a local variable that should be disregarded once out of scope.
Functions inside of javaScript can be declared like:
function doSomething() {
//Do something here
}
And then you call that function by:
Having a function with parameters is simply done by:
function doSomething(someValue1, someValue2) {
//Do something with the values passed in
}
Again, the parameters don’t need to be typed with any syntax as the language determines the type at runtime.
Anonymous Functions
javaScript also has Anonymous Functions which allows you to define a function with no name to a variable or to be passed in as a parameter to another function. This is normally used for callbacks much like the event and delegate features in C#. Anonymous functions have no name.
Here is an example of assigning an anonymous function to a variable:
var anonFunctionVariable = function() {
//do what the functions does best
};
anonFunctionVariable();
Where anonymous functions really shine is when we need to pass in logic to another function. We will see this a little later. We will utilize anonymous functions a lot in jQuery as we do AJAX calls.
Objects
JavaScript is an object oriented programming language. It was hard for me to see this too. It really appeared like a bunch of procedural code but it relies on the fact that everything within the language is actually an object. But it also has the requirement that code has to be created in order. If you are creating a function to be used elsewhere in the code, that function must be interpreted before the code that calls it.
To instantiate an object in JavaScript you do the following:
var obj = new SomeObject();
obj.val = 5;
obj.click = function(){
alert(‘hello’);
};
A short hand notation and the basis of JSON and a way consistently done with jQuery is using “object literal notation”:
var obj = {
val: 5,
click: function(){
alert(‘hello’);
}
};
If we want to select something from the Document Object Model (DOM) then we need to call the following:
document.getElementById('idofelement');
When we use a simple selector in jQuery, it just drops down and calls that function directly.
Needless to say this is just scratching the surface of javaScript but it should provide a nice base before we jump into jQuery. I believe that is enough of an introduction. I do think it is good to know at least some of the underlying system of any framework being used and that is why I spent the time on it.
Let’s dig into jQuery
To actually use jQuery you can reference it locally or on Google’s CDN or Microsoft’s CDN. There are pros and cons to either host it yourself or link to the CDN. I’m not going to suggest one way or the other but to reference it locally you would do:
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
To reference it from the Microsoft CDN you would do:
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"
type="text/javascript"></script>
I already mentioned that jQuery is only one javaScript function that has a shortcut of a single character $.
The jQuery statements are consistent and are made up of a Selector, Action and Parameters. Some examples:
$(‘p’).css(‘color’,’red’)
$(‘#item’).hide(‘slow’)
$(‘div’).html(‘newly added text’)
All of the functionality within jQuery are handled by properties and functions within the jQuery object. Every jQuery function returns a jQuery object so they can be chained together.
One of the first functions we need to look at is the ready function. The ready function will get kicked off after the entire DOM is loaded in memory. This is faster than hooking up a function to the onload event. The onload event gets kicked off after everything loads – even images and ads – so your javaScript could take a while to load and your page could appear sluggish. The jQuery ready event can be executing your javaScript code as soon as the DOM is loaded and while images are still being downloaded.
A lot of examples will have everything in the ready event. While this is definitely fine you can probably get better performance by moving scripts to the bottom of the page and having them execute at that time as long as it doesn’t need the entire DOM loaded. There are times to use both but for these examples we will put everything in the ready event.
$(document).ready(function() {
// all code goes here
});
So inside of the ready function we are creating an anonymous function that contains all of our code. We are passing jQuery our document and telling it to execute our anonymous function as soon as the ready event fires. This is our first callback method. When jQuery gets to this code it checks to see if the DOM is already loaded, if it is then it calls it immediately. If it isn’t, then it pushes it on a stack to be picked up later and executed.
Inside of the anonymous function we can have as many other javaScript functions that we want. We can definitely call other jQuery functions inside of this since it is just javaScript.
Let’s assume we have an h1 tag on our page that we want to change the text on. We can do that by writing the following code:
$(document).ready(function() {
$('h1').text('My New Text');
});
To reinforce the notion of Selection, Action and Parameters, the above ready function has (document) as the selector. We are selecting the entire document. The Action is the ready statement and finally the parameters is the anonymous function. Every jQuery statement is made up of these parts.
To demonstrate that we can have other functions within this anonymous function we could do something like this:
$(document).ready(function() {
function getHeaderText() {
return 'My Super Text';
}
$('h1').text(getHeaderText());
});
If you just wanted to retrieve the text that was associated with the h1 tag already you could call the .text function again without passing in any parameters:
For a complete list of the jQuery functions you can got jQuery’s API page.
jQuery Plugins
jQuery is very extensible. There are tons of plugins available. Some of the ones I have found helpful are Validate (for form validation) which requires the plugin Form. The most popular plugin is jQuery UI.
jQuery UI is broken up into 3 parts: Effects, Interactions and Widgets. Take some time to see what all is available in that plugin.
jQuery AJAX
AJAX stands for Asynchronous JavaScript and XML. Nowadays most people utilize JSON instead of XML. JSON is JavaScript Object Notation. JSON is valid JavaScript. For example:
{ "key" : "value", "key2" : "value2" }
AJAX is used to asynchronously load data. This can be done in response to a user request (clicking a button, etc) or when the page is loading to let some long running process (perhaps a bringing up a report) be kicked off and not delay the rest of the page from loading.
The most simple ajax statement inside of jQuery is load. The load function will load a page (or a portion of a page) and put the results where you want. For example:
$('#result').load('somepage.ext');
$('#result').load('somepage.ext #container');
$('#result').load('somepage.ext', function() {
myCallBack(param1, param2);
};
The first line is the most simple which takes all of the contents from somepage.ext and shoves it into the #result. The second line just extracts data from the #container element. The last line actually has a callback function so we know if the AJAX call actually worked.
Besides load there is also get and post which does a HTTP GET and POST respectively. Finally, there is the all powerful ajax function:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json'
url: '/TaskService.asmx/Delete',
data: JSON.stringify({ 'id': taskId }),
success: $.proxy(function (result) {
if (result.d) {
$(this).fadeOut('slow', function () {
$(this).remove();
});
}
}, this)
});
In our usage we are passing in a type (POST) and the contentType and dataType are set to use JSON. Then we are stating what URL we want to POST to. In this case it is an ASP.NET Web Service. Then we need to pass in the data which in this case is the task id we are wanting to delete. Notice we are passing that into a JSON.stringify function. That function can be found in the json2.js file. The stringify function serializes the JSON object as a string. ASP.NET AJAX can then extract out the object from that string and the webservice doesn’t need to do any kind of parsing. The Delete method for example takes an integer.
Success is assigned an anonymous function that is wrapped into jQuery’s proxy function. Proxy was added recently to jQuery 1.4. Before this existed developers would typically do something like
And then reference “that” inside of the callback function. Let’s say the task we are adding is in a li element. We want to modify that li element inside of the callback function. If we just referenced "this" inside of the callback it would reference XMLHTTPResponse and not the original item. To try and allow developers to clean up their code the proxy function was added. The first parameter is the callback function and the second parameter is whatever you want to use as "this" in the method. Usually it is passed in "this".
The actual success method is only called if the web server responded with a successful response. At this time we check the result.d. In ASP.NET they wrap all return values into “d” (which stands for Data). This is done for security reasons. An excellent video that mentions this is the HaaHa Show from MIX10.
To finish out the code, after we determine the result is what we expected we slowly fade out the element and then remove it from the DOM.
ASP.NET AJAX
To utilize ASP.NET AJAX in a webservice simply uncomment the following attribute:
[System.Web.Script.Services.ScriptService]
So the question may come up as to why not just ASP.NET AJAX by itself and not fool with jQuery’s .ajax function. The key is to try and avoid UpdatePanels. It can be 50K to 100K of bloat just when you try to grab a small amount of data. This can be fine for prototypes but once you have this ajax skeleton in place, it isn’t really any more difficult than using UpdatePanels.
This was a very brief look at jQuery and AJAX but hopefully it makes you want to go and learn more and to actually try it out.
You can download the ppt and code I created for the talk I gave on Tuesday right here:
jQueryPPTAndCode.zip
NOTE: If you are using IE9 Beta, then you will want to run in Compatibility Mode. Also, the TaskSlip code is a work in progress and shouldn’t be used as a best practice example.
Know someone who might like this?